Click here to Skip to main content
15,889,867 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Gurus
I have a very small issue but I don't have any knowledge about it, so its getting to my nerves...

I would like to get values from the URL and make it available on the entire site.

The Flow is like shown below
1. posting of data from site 1 to site 2
2. Capture of data in Site 2
3. Using couple of variables from the Captured data in entire site

ISSUE .

1. Able to capture Data in homepage (Default.aspx)
2. BUT not able to make it available in any part of the site...

Solutions Tried with my basic skills....

1. Hidden Fields
2. Session
3. Cookies

RESOLUTION SO FAR:

ZERO

Files used in the site

Default.aspx (Home Page)
Default.aspx.cs (Background)
Editor.JS (Script for running)
Canvassave.aspx
CanvasSave.aspx.cs(THE MOST MESSY FILE - and this is where I would like to have the variables)

List of VAriables Needed
For NOW - 2 [ ID, NAME ]

REASON
Would like to create unique folders and sharing files


-------------------------------------------------------------------
DEFAULT.ASPX
-------------------------------------------------------------------

C#
<%@ Page Title="" Language="C#" MasterPageFile="~/AsposePdfEditor.Master" AutoEventWireup="true"  CodeBehind="Default.aspx.cs" Inherits="AsposePdfEditor.Default" %>

<script runat="server">
    
    protected void Page_Load(object sender, EventArgs e)
    {

    }
</script>


<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script src="Scripts/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
    jQuery(document).ready(function (e) {
    
        jQuery("#HiddenField2").text(blog);
     //   jQuery('#current_url').html(url);
        var blog = getUrlParameter('id');
      
        alert(blog);
               var test1 = $("#HiddenField2").val();
               
       
        //alert(ta +"sjkdh");
        jQuery.ajax({
            url: "CanvasSave.aspx.cs/defaultPdfFunction",// the name of the callback parameter, as specified by the YQL service
            method: "post",// tell jQuery we're expecting JSONP
            // dataType: "jsonp",// tell YQL what we want and that we want JSON
            data: '{ "fileName" : "' + blog + '" }',
       
            success: function (resp) {
              //  var data = JSON.stringify(resp.d);
                //data = (data.replace(/['"]+/g, ''));
                //dataLoad = data;
                /* var data = Object(resp.query.results.json);
                 if (data.sessionId) cbfnc(data.sessionId);
                 else {
                     cbfnc("Error: " + String(data.message));
                     console.log("rest_rb_login - " + un + " : " + pw + "\n" + data.message);
                 }*/
                alert("Hi");
            }
        });

    });
    var getUrlParameter = function getUrlParameter(sParam) {
        var sPageURL = decodeURIComponent(window.location.search.substring(1)),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : sParameterName[1];
            }
        }
        var blog = getUrlParameter('id');
        alert(blog + "id");
    };
    


    
    function getParameterByName(name) {

            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^]*)"),
		    results = regex.exec(location.search);
            results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        
            alert("with in getParameterByName:");

         //   document.getElementById('HiddenField2').value = results;

    //    var value = document.getElementById('HiddenField2').value;

     //   alert("value: " + value);

    //    alert("Hidden field: " + document.getElementById('HiddenField2').value);

        //  '<%Session["fileId"] = "' + document.getElementById('HiddenField1').value + '"; %>';
    }
    </script>

<script type="text/javascript" src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="a5nv6qw84rxabs6"></script>

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <body>
    <form id="form1" runat="server">

<input id="HiddenField2" type="hidden" />
<!-- Modal -->


<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="static" data-keyboard="false"  aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title" id="myModalLabel">File Upload Dialog</h4>
      </div>
      <div class="modal-body">
      
              <label for="fileToUpload">Select a File to Upload</label><br />
      <input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();" accept="application/pdf, image/png, image/jpg, image/jpeg, image/gif"/>
      
      </div>
      <div class="modal-footer">

      <div class="progress" >
  <div class="progress progress-striped active">
        <div class="progress-bar progress-bar-success" style="width:0%"></div>
    </div>
</div>
     

          <input id="hdnOpp" type="hidden" />
      </div>
    </div>
  </div>
</div>     

<div class="modal" id="moveModal"   tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
     <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" onclick="moveModeClose();return false;"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title" id="H1">Move Page After</h4>
      </div>
      <div class="modal-body">
      <label id="lblpagemove" for="txtMove">Enter Page Number</label><br />
      <input type="text" id="txtMove"/>
      </div>
      <div class="modal-footer">
      <button type="button" class="btn btn-default" id="btnMove" onclick="Move();" data-dismiss="modal">Move</button>
      <input id="hdnMove" type="hidden" />
    </div>
    </div>
  </div>
</div> 

<div class="modal" id="replaceModal"   tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
     <div class="modal-header">        
        <h4 class="modal-title" id="H2">Replace Text</h4>
      </div>
      <div class="modal-body">
      <label id="Label1" for="txtFind">Find Text</label><br />
      <input type="text" id="txtFind"/><br />
      <label id="Label2" for="txtReplace">Replace With</label><br />
      <input type="text" id="txtReplace"/>
      </div>
      <div class="modal-footer">
      <button type="button" class="btn btn-default" id="btnReplace" onclick="ReplaceText();" data-dismiss="modal">Replace</button>
     
    </div>
    </div>
  </div>
</div> 

<div class="modal fade bs-example-modal-sm" tabindex="-1" id="loadingModal" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false" >
  <div class="modal-dialog modal-sm">
    <div class="modal-content"> 
      <img src="framely.gif" />
    </div>
  </div>
</div>

<!-- Attachments -->
<div class="modal" id="divAttach" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="static" data-keyboard="false"  aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title" id="H3">Attachments</h4>
      </div>
      <div class="modal-body">
      <table class="table table-bordered" id="tblAttach">
  <thead>
  <tr>
  <th>File Name</th>
  <th>File Description</th>
  <th>Download File</th>
  <th>Remove File</th>
  </tr>
  </thead>
</table>
      </div>
      <div class="modal-footer">
      </div>
    </div>
  </div>
</div>     

<div id='divSignature' class="panel panel-success" style='removed:absolute;z-index:1030; visibility:hidden'>
<div class="modal-header">
<h4 class="modal-title" id="H4">Signature</h4>
</div>
<canvas id="signCanvas" width="350" height="150" style="z-index:1125;" ></canvas>
 <div class="modal-footer">
      <button type="button" class="btn btn-default" id="btnClear" onclick="clearSignature();">Clear</button>
      <button type="button" class="btn btn-default" id="btnSignDone" onclick="saveSignature();">Done</button>
      <button type="button" class="btn btn-default" id="btnSignClose" onclick="closeSignature();">Close</button>
      </div>
</div>

<div class="well well-sm">

    <!-- Single button -->
<div class="btn-group">

 <!-- <button type="button" class="btn btn-primary btn-lg dropdown-toggle" data-toggle="dropdown" aria-expanded="false" >
    <span class=" glyphicon glyphicon-upload"></span>
  </button>-->
<ul class="dropdown-menu">  
  <li><a > Create New File</a></li>
  <li><a class="open-myModal" data-toggle="modal" data-target="#myModal" data-id="uploading" data-placement="top" title="Upload File to Server">Open From Computer</a></li>
 <li><a >Open From Dropbox</a></li>
  </ul>   
</div>

    <button onclick="javascript:generalSetup('Add');AddPage();$('#divDel').css('visibility', 'hidden');return false;" class="btn btn-default btn-lg" id="btnAddPage" data-toggle="tooltip" data-placement="top" title="Add Page" disabled=disabled>
    <span class="glyphicon glyphicon-plus"></span>
    </button>
     <button onclick="javascript:generalSetup('Delete');DeletePage();$('#divDel').css('visibility', 'hidden');return false;" class="btn btn-default btn-lg" id="btnDeletePage" data-toggle="tooltip" data-placement="top" title="Delete Page" disabled=disabled>
    <span class="glyphicon glyphicon-minus"></span>
    </button>
    <button class="open-moveModal btn btn-default btn-lg" data-toggle="modal" onclick="generalSetup('Move');" data-target="#moveModal" data-toggle="tooltip" id="btnMoving" data-id="moving" data-placement="top" title="Move Page" disabled=disabled>    
    <span class="glyphicon glyphicon-transfer"></span> 
    </button>

     <button class="open-myModal btn btn-default btn-lg" data-toggle="modal" data-target="#myModal" onclick="generalSetup('Append');" data-id="appending" id="btnAppending" data-placement="top" title="Append File" disabled=disabled>
     <span class="glyphicon glyphicon-plus-sign"></span>    
    </button>

    <button onclick="javascript:generalSetup('Save');UploadPic();return false;" class="btn btn-default btn-lg" id="btnSave" data-toggle="tooltip"  data-placement="top" title="Save Pdf File" disabled=disabled>
    <span class="glyphicon glyphicon-floppy-disk"></span>
    </button>
    <div class="btn-group">
  <!-- <button type="button" class="btn btn-default btn-lg" data-placement="top" title="Export File" data-toggle="dropdown" onclick="generalSetup('Export');" id="btnExporting" aria-expanded="false"  disabled=disabled>
    <span class=" glyphicon glyphicon-export"></span>
  </button>-->
  <ul class="dropdown-menu" role="menu">
    <li><a > As PDF File</a></li>
    <li><a > As Word File </a></li>  
    <li><a > As Excel File </a></li> 
    <li><a > As Text File </a></li> 
    <li><a > As SVG File </a></li> 
    <li><a > As XPS File </a></li> 
    <li><a > As HTML File </a></li>   
  </ul>
</div>

    <button onclick="javascript:generalSetup('Previous');Previous();$('#divDel').css('visibility', 'hidden');return false;" class="btn btn-default btn-lg" data-toggle="tooltip" id="btnPrevious" data-placement="top" title="Previous Page" disabled=disabled>
    <span class="glyphicon glyphicon-circle-arrow-left"></span> 
    </button>
     <button  class="btn btn-default btn-lg" data-toggle="tooltip" data-placement="top" id="lblPages">Page 0 Of 0</button>
    <button onclick="javascript:generalSetup('Next');Next();$('#divDel').css('visibility', 'hidden');return false;" class="btn btn-default btn-lg" id="btnNext" data-toggle="tooltip" data-placement="top" title="Next Page" disabled=disabled>
     <span class="glyphicon glyphicon-circle-arrow-right"></span>    
    </button>


    <div class="btn-group">
  <!-- <button type="button" class="btn btn-default btn-lg dropdown-toggle" data-toggle="dropdown" aria-expanded="false" onclick="generalSetup('Search');" id="btnSearching" disabled=disabled>
    <span class=" glyphicon glyphicon-search"></span>
  </button> -->
  <ul class="dropdown-menu" role="menu">
    <li><a class="open-moveModal" data-toggle="modal" data-target="#moveModal" data-id="searching" data-placement="top" title="Search Text"> Search Text</a></li>
    <li><a class="open-replaceModal" data-toggle="modal" data-target="#replaceModal" data-id="replacing" data-placement="top" title="Replace Text"> Replace Text</a></li>
    <li><a > Clear Search</a></li>    
  </ul>
</div>
    <div class="btn-group">
  <button type="button" class="btn btn-default btn-lg dropdown-toggle" data-toggle="dropdown" aria-expanded="false" onclick="generalSetup('Image');" id="btnImage" disabled=disabled>
    <span class="glyphicon glyphicon-picture"></span>
  </button>
  <ul class="dropdown-menu" role="menu">
    <li><a class="open-myModal" data-toggle="modal" data-target="#myModal" data-id="images" data-toggle="tooltip" data-placement="top" title="Insert Image"> From Computer</a></li>
    <li><a > From Dropbox</a></li>    
  </ul>
</div>
      
    <div class="btn-group">
    <button id="btnRect" value="rect"  class="btn btn-default btn-lg" data-toggle="tooltip" data-placement="top" title="Highlight Mode" onclick="generalSetup('Rect');" disabled=disabled>
     <span class="glyphicon glyphicon-header"></span>  
    </button>

     <button id="btnRead" value="reading"  class="btn btn-default btn-lg" data-toggle="tooltip" data-placement="top" title="Read Mode" onclick="generalSetup('Read');" disabled=disabled>
     <span class="glyphicon glyphicon-hand-up"></span>  
    </button>

     <button id="btnDrag" value="dragging"  class="btn btn-default btn-lg" data-toggle="tooltip" data-placement="top" title="Drag Mode" onclick="generalSetup('Drag');" disabled=disabled>
     <span class="glyphicon glyphicon-move"></span>  
    </button>

     <button id="btnTexting" value="texting"  class="btn btn-default btn-lg" data-toggle="tooltip" data-placement="top" title="Text Mode" onclick="generalSetup('Text');" disabled=disabled> 
     <span class="glyphicon glyphicon-text-height"></span>  
    </button>
    </div>
      <div class="btn-group">
     <!-- <button id="btnAttachments" class="btn btn-default btn-lg dropdown-toggle" data-toggle="dropdown" aria-expanded="false"  title="Attachments" disabled=disabled> 
     <span class="glyphicon glyphicon-paperclip"></span>  
    </button> -->
    <ul class="dropdown-menu">  
  <li><a class="open-myModal" data-toggle="modal" data-target="#myModal" data-id="addAttachment" data-toggle="modal" data-placement="top" title="Add Attachment" >Add Attachment</a></li>
  <li><a data-id="attachment" data-toggle="modal" data-target="#divAttach" data-placement="top" title="View Attachments" >View Attachments</a></li>
  </ul>   
    

    <button id="btnSignature" value="signature"  class="btn btn-default btn-lg" data-toggle="tooltip"  data-placement="top" title="Signature" onclick="generalSetup('signature');" disabled=disabled> 
     <span class="glyphicon glyphicon-pencil"></span>  
    </button>

    </div>
</div>
    <div id="container">
       <canvas id="imageView" width="1138" height="760" style="z-index:5; background-color:GrayText;" >
      
        <p>Unfortunately, your browser is currently unsupported by our web
        application.  We are sorry for the inconvenience. Please use one of the
        supported browsers listed below, or draw the image you want using an offline tool.</p>        
       </canvas>
      </div>
<div class="modal bs-example-modal-sm" id="myColors" tabindex="-1"  aria-labelledby="mySmallModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
     <div class="modal-body">      
      <button id="btnRed" style="border:'1px solid'; background-color:Red; height:22px; width:22px;" name="red" onclick="selectColor(this);" class="btn btn-default btn-xs" data-toggle="button" data-placement="top" title="Red"></button>
      <button id="btnBlack" style="border:'1px solid'; background-color:Black; height:22px; width:22px;" name="black" onclick="selectColor(this);" class="btn btn-default btn-xs" data-toggle="button" data-placement="top" title="Black"></button>
      <button id="btnWhite" style="border:'1px solid'; background-color:White; height:22px; width:22px;" name="white" onclick="selectColor(this);" class="btn btn-default btn-xs" data-toggle="button" data-placement="top" title="White"> </button> 
      <button id="btnGreen" style="border:'1px solid'; background-color:Green; height:22px; width:22px;" name="green" onclick="selectColor(this);" class="btn btn-default btn-xs" data-toggle="button" data-placement="top" title="Green"></button>
      <button id="btnBlue" style="border:'1px solid'; background-color:Blue; height:22px; width:22px;" name="blue" onclick="selectColor(this);" class="btn btn-default btn-xs" data-toggle="button" data-placement="top" title="Blue"></button>
      <button id="btnGray" style="border:'1px solid'; background-color:Gray; height:22px; width:22px;" name="gray" onclick="selectColor(this);" class="btn btn-default btn-xs" data-toggle="button" data-placement="top" title="Gray"> </button> 
      <button id="btnYellow" style="border:'1px solid'; background-color:Yellow; height:22px; width:22px;" name="yellow" onclick="selectColor(this);" class="btn btn-default btn-xs" data-toggle="button" data-placement="top" title="Yellow"> </button> 
     
    </div>
    </div>
  </div>
</div> 

       <div id='textAreaPopUp' class="panel panel-success" style='removed:absolute;z-index:1030; visibility:hidden'>
       <table id="txtTable" class="table table-condensed">
       <tr>
       <td>
       <select id='ddFont' class="dropdown" onchange="ddFontChange()">
         <option value="Arial" selected="selected">Arial</option>
         <option value="Times">Times New Roman</option>
         <option value="Verdana">Verdana</option>
         <option value="Tahoma">Tahoma</option>
       </select>
       <select id='ddSize' class="dropdown" onchange="ddSizeChange()">
       <option value="8" selected="selected">8px</option>
       <option value="9">9px</option>
       <option value="10">10px</option>
       <option value="12">12px</option>
       <option value="14">14px</option>
       <option value="16">16px</option>
       <option value="18">18px</option>
       <option value="24">24px</option>
       <option value="36">36px</option>
       <option value="48">48px</option>
       <option value="72">72px</option>

       </select>
        <button id="btnBold" value="Bold" onclick="makeBold();"  class="btn btn-default btn-xs" data-toggle="button" data-placement="top" title="Bold">
     <span class="glyphicon glyphicon-bold"></span>  
    </button>

     <button id="btnItalic" value="Italic" onclick="makeItalic();" class="btn btn-default btn-xs" data-toggle="button" data-placement="top" title="Italic">
     <span class="glyphicon glyphicon-italic"></span>  
    </button>

     <button id="btnUnderline" value="Underline"  class="btn btn-default btn-xs" data-toggle="button" data-placement="top" title="Underline">
     <span class="glyphicon glyphicon-text-width"></span>  
    </button>

     <button id="btnColor" value="Color" style="border:'1px solid';  background-color:Black; height:22px; width:22px;" data-toggle="modal" data-target="#myColors" class="btn btn-default"  data-placement="bottom" title="Color">
       
    </button>
       </td>
       </tr>
       <tr>
       <td>
       <textarea id='textareaTest' class="form-control" style='width:350px; height:50px;'></textarea>
       <%--<div id='textareaTest' contentEditable="true"></div>--%>
       </td>
       </tr>
       <tr>
       <td>
       <button type='button' value='save' id='saveText' onclick='saveTextFromArea();' class="btn btn-default"> 
       <span class="glyphicon glyphicon-ok-sign"></span>  
       </button>
       <button type='button' value='cancel' id='Button1' onclick='closeTextEditor();' class="btn btn-default"> 
       <span class="glyphicon glyphicon-remove-sign"></span>
        </button>
       </td>
       </tr>
       </table>
       </div>
       <div id="divDel" class="panel panel-success" style='removed:absolute;z-index:30; visibility:hidden'>
       <button type='button' value='cancel' id='btnDel' onclick='DelShape();' class="btn btn-default"> 
       <span class="glyphicon glyphicon-remove-sign"></span>
        </button>
       </div>
  <script type="text/javascript" src="Editor.js">
  </script>
    </form>
  </body>
    
</asp:Content>


-------------------------------------------------------------------
DEFAULT.ASPX.CS
-------------------------------------------------------------------


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Collections;
using System.Diagnostics;
using System.Data;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Xml.Linq;
using Aspose.Pdf;
using Aspose.Pdf.Devices;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web.Script.Serialization;
using System.Web.Services;
using Aspose.Pdf.Facades;
using Aspose.Pdf.Text;
using System.Net;
namespace AsposePdfEditor
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
             {
            
            string Text1 = Request.QueryString["Text1"].ToString();

            Session["fileId"] = Text1;

            Label1.Text = Session["fileId"].ToString();

          cmdSend.OnClientClick = string.Format("return sendData('{0}')");
            string Text1 = Request.QueryString["Text1"].ToString();
           if (Session["Text1"] != null)
                Session.Add("Text1", Text1);
            else
                Session["Text1"] = Text1;
            string.Format("return sendData('{0}')", Text1);

            Session["fileId"] = HiddenField2.value;
            Response.Write("Session value" + Session["fileId"].ToString());

            // Create a PDF license object
            Aspose.Pdf.License license = new Aspose.Pdf.License();
           
           // Instantiate license file
          //  license.SetLicense("Aspose.Pdf.lic");
            license.SetLicense("Aspose.Pdf.lic");
            // Set the value to indicate that license will be embedded in the application
           license.Embedded = true;

        }

    }
}


-------------------------------------------------------------------
CANVASSAVE.ASPX.CS
-------------------------------------------------------------------


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Services;
using System.Web.Services;
using System.IO;
using Aspose.Pdf;
using Aspose.Pdf.Devices;
using Aspose.Pdf.Facades;
using System.Threading;
using System.Drawing;
using Aspose.Pdf.Text;
using System.Net;
using Aspose.Pdf.Text.TextOptions;
using Aspose.Pdf.InteractiveFeatures.Forms;
using System.Text.RegularExpressions;

namespace AsposePdfEditor
{
    [ScriptService]
    public partial class CanvasSave : System.Web.UI.Page
    {		
        protected void Page_Load(object sender, EventArgs e)
        {
           
            
        }

        public void ProcessRequest(HttpContext context)
        {		
            try
            {
                if (context.Request.QueryString["Download"] != null)
                {
                    context.Response.AddHeader("Content-disposition", "attachment; filename=" + context.Request.QueryString["Download"].Split('/')[1].ToString());
                    context.Response.ContentType = "application/octet-stream";
                    context.Response.TransmitFile(Server.MapPath(context.Request.QueryString["Download"].ToString()));
                    context.Response.End();
                }

                else
                {
					//Capture File From Post
                    HttpPostedFile file = context.Request.Files["fileToUpload"];

                    if (context.Request.Form["Opp"] == "uploading")
                    {
                        //Or just save it locally
                        file.SaveAs(Server.MapPath("Convert/input.pdf"));
                        file.SaveAs(Server.MapPath("Convert/output.pdf"));
						Startup();
                        context.Response.Write(ImageConverter());
                    }
                    else if (context.Request.Form["Opp"] == "appending")
                    {
                        string appPages = context.Request.Form["pages"];
                        string appRatios = context.Request.Form["ratios"];
                        string appHeights = context.Request.Form["heights"];

                        //Or just save it locally
                        file.SaveAs(Server.MapPath("Convert/append.pdf"));
                        context.Response.Write(AppendConverter(appPages, appRatios, appHeights));
                    }
                    else if (context.Request.Form["Opp"] == "addAttachment")
                    {
                        //Or just save it locally
                        file.SaveAs(Server.MapPath("Attachments/" + file.FileName));
                        AddAttachments(Server.MapPath("Attachments/" + file.FileName), file.FileName);                      
                        context.Response.Write(file.FileName);
                    }
                    else
                    {
                        //Or just save it locally
                        file.SaveAs(Server.MapPath("Images/" + file.FileName));
                        context.Response.Write(file.FileName);
                    }
                }
            }
            catch (IndexOutOfRangeException exception)
            {

                if (exception.Message.Contains("evaluation"))
                {
                    context.Response.Write("Only 4 elements of any collection are allowed.");
                }
                else
                {
                    context.Response.Write("An exception occurred during processing of your document.");
                }

            }
            catch (Exception exp)
            {

                context.Response.Write("An exception occurred during processing of your document. ");
            }
        }


        [WebMethod()]
        public static string Download_Dropbox(string file_url, string process)
        {
            try
            {
                // Create a new WebClient instance.
                using (WebClient myWebClient = new WebClient())
                {
                    if (process == "upload")
                    {

                        // myStringWebResource = remoteUri + fileName;
                        // Download the Web resource and save it into the current filesystem folder.
                        myWebClient.DownloadFile(file_url, HttpContext.Current.Server.MapPath("Convert/input.pdf"));
                        myWebClient.DownloadFile(file_url, HttpContext.Current.Server.MapPath("Convert/output.pdf"));

                        return ImageConverter();
                    }
                    else
                    {
                        string[] filename = file_url.Split('/');
                        string name = filename[filename.Length - 1];

                        // Download the Web resource and save it into the current filesystem folder.
                        myWebClient.DownloadFile(file_url, HttpContext.Current.Server.MapPath("Images/"+name));

                        return name;
                    }
                }
            }
            catch (Exception Exp)
            {
                return Exp.Message;
            }
        }

        [WebMethod()]
        public static string AddPage_Click(string lastpage)
        {
            try
            {
                Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf"));

                //insert an empty page at the end of a PDF file
                doc.Pages.Add();

                doc.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf"));

                string height = "";

                int counter = GetHighestPage();
                counter = counter + 1;

                using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath("Input/image-1" + counter + ".png"), FileMode.Create))
                {
                    //Create Resolution object
                    Resolution resolution = new Resolution(300);
                    //create PNG device with specified attributes
                    PngDevice pngDevice = new PngDevice();
                    //Convert a particular page and save the image to stream
                    pngDevice.Process(doc.Pages[doc.Pages.Count], imageStream);
                    //Close stream
                    imageStream.Close();
                }
                string Aratio = "";
                System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("Input/image-1" + counter + ".png"));
                ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath("Input/image" + counter + ".png"), out height, out Aratio);
                image.Dispose();
                return "image" + counter + ".png";
            }
            catch (Exception Exp)
            {
                return Exp.Message;
            }
        }

       

        [WebMethod()]
        protected static void ScaleImage(System.Drawing.Image image, int maxWidth, int maxHeight, string path, out string height,out string Aratio)
        {
            var ratio = (double)maxWidth / image.Width;
            Aratio = ratio.ToString();
            var newWidth = (int)(image.Width * ratio);
            var newHeight = (int)(image.Height * ratio);
            height = newHeight.ToString();
            var newImage = new Bitmap(newWidth, newHeight);
            Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
            Bitmap bmp = new Bitmap(newImage);
            bmp.Save(path);

        }


        [WebMethod()]
        public static void DeletePage_Click(string imageData, string imageName)
        {
            try
            {
                Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf"));

                doc.Pages.Delete(Convert.ToInt32(imageData));

                doc.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf"));

                System.IO.File.Delete(HttpContext.Current.Server.MapPath("Input/" +imageName));
            }
            catch (Exception Exp)
            {
               // return Exp.Message;
            }
            
        }

        [WebMethod()]
        public static string[] MovePages(string moveFrom, string moveTo, string[] pageList)
        {
            try
            {
                int pageFrom = Convert.ToInt32(moveFrom);
                int pageTo = Convert.ToInt32(moveTo);
                List<string> str = pageList.ToList();

                Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf"));

                Aspose.Pdf.Page page = doc.Pages[pageFrom];

                //insert an empty page at the end of a PDF file
                doc.Pages.Insert(pageTo + 1, page);

                if (pageFrom > pageTo)
                {
                    doc.Pages.Delete(pageFrom+1);
                    str.Insert(pageTo, pageList[pageFrom - 1]);
                    str.RemoveAt(pageFrom);
                }
                else
                {
                    doc.Pages.Delete(pageFrom);                    
                    str.Insert(pageTo, pageList[pageFrom - 1]);
                    str.RemoveAt(pageFrom-1);
                }

                doc.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf"));

                pageList = str.ToArray();

                
                                
            }
            catch (Exception Exp)
            {
                // return Exp.Message;
            }

            return pageList;

        }


        [WebMethod()]
        public static void UploadPic(List<shap> shapes , string filename, string aspectRatio)
        {
          
                Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf"));

                //Create image stamp
                ImageStamp imageStamp = new ImageStamp(HttpContext.Current.Server.MapPath("test.png"));

                for (int i = 0; i < shapes.Count; i++)
                {
                    //create stamp
                    Aspose.Pdf.Facades.Stamp stamp = new Aspose.Pdf.Facades.Stamp();

                    float shapeX = (shapes[i].x * 72 / 150) / (float)Convert.ToDouble(shapes[i].ratio);
                    float shapeY = (shapes[i].y * 72 / 150) / (float)Convert.ToDouble(shapes[i].ratio);
                    float shapeW = (shapes[i].w * 72 / 150) / (float)Convert.ToDouble(shapes[i].ratio);
                    float shapeH = (shapes[i].h * 72 / 150) / (float)Convert.ToDouble(shapes[i].ratio);
                                                            
                    double yaxis = (float)(doc.Pages[shapes[i].p].Rect.URY - (shapeH + shapeY));

                    var isSpecial = true;//regexItem.IsMatch(shapes[i].imName);

                    if (shapes[i].Itype == "highlight" || shapes[i].Itype == "image")
                    {

                        if (shapes[i].Itype == "highlight")
                        {
                            imageStamp = new ImageStamp(HttpContext.Current.Server.MapPath("test.png"));
                        }
                        else
                        {

                            imageStamp = new ImageStamp(HttpContext.Current.Server.MapPath("Images/"+shapes[i].imName));
                        
                        }
                                                
                        imageStamp.Background = false;
                        imageStamp.XIndent = (float)(shapeX);
                        imageStamp.YIndent = (float)(yaxis);
                        imageStamp.Height = shapeH;
                        imageStamp.Width = shapeW;
                        
                        //Add stamp to particular page
                        doc.Pages[shapes[i].p].AddStamp(imageStamp);
                    }                   
                    else if(shapes[i].Itype == "text")
                    {

                        /*
                        // create TextBuilder for first page
                        TextBuilder tb = new TextBuilder(doc.Pages[shapes[i].p]);

                        // TextFragment with sample text
                        TextFragment fragment = new TextFragment(shapes[i].t);

                        // set the font for TextFragment
                        fragment.TextState.Font = FontRepository.FindFont(shapes[i].n);
                        fragment.TextState.FontSize = Convert.ToInt32(shapes[i].s);
                        if (shapes[i].wt == "bold")
                        {
                            fragment.TextState.FontStyle = FontStyles.Bold;
                        }

                        if (shapes[i].st == "italic")
                        {
                            fragment.TextState.FontStyle = FontStyles.Italic;
                        }

                        // set the formatting of text as Underline
                        // fragment.TextState.Underline = true;
                        fragment.TextState.ForegroundColor = GetColor(shapes[i].c);
                        // specify the removed where TextFragment needs to be placed
                        fragment.Position = new Position((float)(shapeX), (float)(yaxis));

                       // fragment.Rectangle.Rotate((360 - (Convert.ToDouble(shapes[i].fieldType)) * 180 / Math.PI);

                        // append TextFragment to PDF file
                        tb.AppendText(fragment);
                        */
                        
                        //create text stamp
                        TextStamp textStamp = new TextStamp(shapes[i].t);
                        //set whether stamp is background
                       // textStamp.Background = true;
                        //set origin
                        textStamp.XIndent = (float)(shapeX); 
                        textStamp.YIndent = (float)(yaxis);
                        //rotate stamp
                        textStamp.RotateAngle = 360 - ((Convert.ToDouble(shapes[i].fieldType)) * 180 / Math.PI);
                        
                        //set text properties
                        textStamp.TextState.Font = FontRepository.FindFont(shapes[i].n);
                        textStamp.TextState.FontSize = Convert.ToInt32(shapes[i].s) * 0.75f;

                        if (shapes[i].wt == "bold")
                        {
                            textStamp.TextState.FontStyle = FontStyles.Bold;
                        }

                        if (shapes[i].st == "italic")
                        {
                            textStamp.TextState.FontStyle = FontStyles.Italic;
                        }
                        
                       
                        textStamp.TextState.ForegroundColor = GetColor(shapes[i].c);
                        //add stamp to particular page
                        doc.Pages[shapes[i].p].AddStamp(textStamp);

                    }
                    else if (shapes[i].Itype == "field" && isSpecial)
                    {
                        if (shapes[i].fieldType == "Text")
                        {
                            // Get a field
                            TextBoxField textBoxField = doc.Form.Fields[Convert.ToInt32(shapes[i].imName)] as TextBoxField;
                            // Modify field value
                            textBoxField.Value = shapes[i].t;
                        
                        }
                        else if (shapes[i].fieldType == "CheckBox")
                        {

                            // Get a field
                            CheckboxField checkBoxField = doc.Form.Fields[Convert.ToInt32(shapes[i].imName)] as CheckboxField;
                            if(shapes[i].t != "")
                            // Modify field value
                            checkBoxField.Checked = Convert.ToBoolean(shapes[i].t);
                        }
                        else if (shapes[i].fieldType == "Radio")
                        {
                            RadioButtonOptionField field = (RadioButtonOptionField)doc.Form.Fields[Convert.ToInt32(shapes[i].imName)];

                            RadioButtonField rbf = (RadioButtonField)field.Parent;
                            if (Convert.ToBoolean(shapes[i].t))
                            {
                                rbf.Selected = rbf.Options[field.OptionName].Index;

                            }
                            else
                            {
                                field.ActiveState = "Off";

                            }
                        }
                        else if (shapes[i].fieldType == "ComboBox")
                        {                            

                            // Get a field
                            ComboBoxField comboBoxField = doc.Form.Fields[Convert.ToInt32(shapes[i].imName)] as ComboBoxField;
                            var values = shapes[i].t.Split(new string[]{"^^^"},StringSplitOptions.None)[0];

                            foreach (var item in comboBoxField.Options.Cast<Option>())
                            {
                                if (item.Value == values)
                                {

                                    comboBoxField.Selected = item.Index;
                                }
                            }
                        }
                    }

                }
            
                doc.Save(HttpContext.Current.Server.MapPath("Convert/Export.pdf"));
            
           
        }

        [WebMethod]
        public static string defaultPdfFunction(string fileName)
        {			
            string result = null;
            result = Path.GetFileName(fileName);
  			Document pdfdoc = new Document(HttpContext.Current.Server.MapPath("pdf-sample2.pdf"));
          	//Document pdfdoc = new Document(file);
			
            string paths = fileName.ToString();
            string Aratio = "";
            string pages = "";
            string Ratios = "";
            string height = "";
            string Allheights = "";
            string fields = "";
            try
            {
				if (context.Request.Form["Opp"] == "appending")
                {
                   context.Response.Write("test");
                   // context.Response.Write('blah');

                    /*
                   //Or just save it locally
                   file.SaveAs(Server.MapPath("Convert/input.pdf"));
                   file.SaveAs(Server.MapPath("Convert/output.pdf"));
                    Startup();
                   context.Response.Write(ImageConverter());
                    */
                }
                pdfdoc.Save(HttpContext.Current.Server.MapPath("Convert/input.pdf"));
                pdfdoc.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf"));
              //  Startup();
                Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf"));                
                int TotalPages = 0;
                bool licensed = CheckLicense();

                if (licensed || (!licensed && doc.Pages.Count <= 4))
                    TotalPages = doc.Pages.Count;
                else
                    TotalPages = 4;

                for (int pageCount = 1; pageCount <= TotalPages; pageCount++)
                {
                    using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath("Input/image-1" + pageCount + ".png"), FileMode.Create))
                    {
                        //Create Resolution object
                        // Resolution resolution = new Resolution(150);
                        //create PNG device with specified attributes
                        PngDevice pngDevice = new PngDevice();
                        //Convert a particular page and save the image to stream
                        pngDevice.Process(doc.Pages[pageCount], imageStream);
                        //Close stream
                        imageStream.Close();

                        System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("Input/image-1" + pageCount + ".png"));



                        ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath("Input/image" + pageCount + ".png"), out height, out Aratio);

                        image.Dispose();

                        if (pageCount == 1)
                            fields = CheckFields(doc, pageCount, "image" + pageCount + ".png", fields, Convert.ToDouble(Aratio), licensed);

                        pages = pages + "," + "image" + pageCount + ".png";
                        Ratios = Ratios + "," + Aratio;
                        Allheights = Allheights + "," + height;

                    }

                }

                Ratios = Ratios.Substring(1, Ratios.Length - 1);
                pages = pages.Substring(1, pages.Length - 1);
                Allheights = Allheights.Substring(1, Allheights.Length - 1);
                if (fields != "")
                {
                    fields = fields.Substring(3, fields.Length - 3);
                }
                
            }
            catch (IndexOutOfRangeException exception)
            {
                context.Response.Write(exception);
            }

            return pages + "%#" + Ratios + "%#" + Allheights + "%#" + fields;
        }

        [WebMethod]
        public static string CreateNewFile()
        {
            Startup();

            Document doc = new Document();
            doc.Pages.Add();
            doc.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf"));


            return ImageConverter();
        }
        [WebMethod]
        public static string ImageConverter()
        {
                          
                Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf"));
                
                
                string Aratio = "";
                string pages = "";
                string Ratios = "";
                string height = "";
                string Allheights = "";
                string fields = "";
                int TotalPages = 0;
                bool licensed = CheckLicense();

                if (licensed || (!licensed && doc.Pages.Count <= 4))
                    TotalPages = doc.Pages.Count;
                else
                    TotalPages = 4;

                for (int pageCount = 1; pageCount <= TotalPages; pageCount++)
                {
                    using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath("Input/image-1" + pageCount + ".png"), FileMode.Create))
                    {
                        //Create Resolution object
                       // Resolution resolution = new Resolution(150);
                        //create PNG device with specified attributes
                        PngDevice pngDevice = new PngDevice();
                        //Convert a particular page and save the image to stream
                        pngDevice.Process(doc.Pages[pageCount], imageStream);
                        //Close stream
                        imageStream.Close();

                        System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("Input/image-1" + pageCount + ".png"));



                        ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath("Input/image" + pageCount + ".png"), out height, out Aratio);

                        image.Dispose();

                        if(pageCount == 1)
                        fields = CheckFields(doc, pageCount, "image" + pageCount + ".png", fields, Convert.ToDouble(Aratio), licensed);

                        pages = pages + "," + "image" + pageCount + ".png";
                        Ratios = Ratios + "," + Aratio;
                        Allheights = Allheights + "," + height;
                        
                    }

                }

                Ratios = Ratios.Substring(1, Ratios.Length - 1);
                pages = pages.Substring(1, pages.Length -1);
                Allheights = Allheights.Substring(1, Allheights.Length -1);
                if (fields != "")
                {
                    fields = fields.Substring(3, fields.Length - 3);
                }
                return pages + "%#" + Ratios + "%#" + Allheights + "%#" + fields;
           
        }

        private static string CheckFields(Document doc, int pageCount, string filename, string fields, double ratio, bool licensed)
        {
            double marginLeft = doc.Pages[pageCount].PageInfo.Margin.Left;
            double marginTop = doc.Pages[pageCount].PageInfo.Margin.Top;
                       
            int fieldcounter = 0;
            
            Aspose.Pdf.Facades.Form pdfForm = new Aspose.Pdf.Facades.Form(doc);

            // Get values from all fields
            foreach (Field formField in doc.Form.Fields)
            {
                    

                    double lowerLeftY = (doc.Pages[pageCount].Rect.Height) - (formField.Rect.ToRect().Y + formField.Height);

                    double lowerLeftX = formField.Rect.ToRect().X;
                    var fieldType = formField.GetType().Name; //pdfForm.GetFieldType(formField.FullName);
                    var imValue = "";

                    if (fieldType.ToString() == "CheckboxField" || fieldType.ToString() == "ComboBoxField" || fieldType.ToString() == "RadioButtonOptionField" || fieldType.ToString() == "TextBoxField")
                    {
                        var value = formField.Value;

                        if (fieldType.ToString() == "TextBoxField")
                        {
                            fieldType = "Text";
                        }
                        if (fieldType.ToString() == "CheckboxField")
                        {
                            CheckboxField field = (CheckboxField)formField;
                            if (field.Parent != null) 
                            imValue = field.Parent.FullName;
                            fieldType = "CheckBox";
                            if (field.Checked)
                            {
                                value = "true";
                            }
                            else
                            {
                                value = "false";
                            }
                        }
                        if (fieldType.ToString() == "RadioButtonOptionField")
                        {
                            RadioButtonOptionField field = (RadioButtonOptionField)formField;
                            RadioButtonField rbf = (RadioButtonField)field.Parent;

                            fieldType = "Radio";
                            if (field.Parent != null)
                                imValue = field.Parent.FullName;
                            if ((rbf.Options[field.OptionName].Index == rbf.Selected))
                            {
                                value = "true";
                            }
                            else
                            {
                                value = "false";
                            }
                        }
                        if (fieldType.ToString() == "ComboBoxField")
                        {
                            ComboBoxField field = (ComboBoxField)formField;
                            string optValues = value;
                            fieldType = "ComboBox";
                            foreach (Option opt in field.Options)
                            {

                                optValues = optValues + "^^^" + opt.Value;

                            }
                            value = optValues;


                        }

                        bool isRequired = pdfForm.IsRequiredField(formField.FullName);
                        //fields += "$#$" + (lowerLeftX * 2.08) * ratio + "$#$" + (lowerLeftY * 2.08) * ratio + "$#$" + (formField.Width * 2.08) * ratio + "$#$" + (formField.Height * 2.08) * ratio + "$#$" + formField.PageIndex + "$#$" + "image" + formField.PageIndex + ".png" + "$#$" + value + "$#$" + formField.DefaultAppearance.FontName + "$#$" + formField.DefaultAppearance.FontSize + "$#$" + " " + "$#$" + " " + "$#$" + " " + "$#$" + ratio + "$#$" + " " + "$#$" + formField.FullName.Replace('/', '-') + "$#$" + fieldType;
                        fields += "$#$" + (lowerLeftX * 2.08) * ratio + "$#$" + (lowerLeftY * 2.08) * ratio + "$#$" + (formField.Width * 2.08) * ratio + "$#$" + (formField.Height * 2.08) * ratio + "$#$" + formField.PageIndex + "$#$" + "image" + formField.PageIndex + ".png" + "$#$" + value + "$#$" + formField.DefaultAppearance.FontName + "$#$" + formField.DefaultAppearance.FontSize + "$#$" + " " + "$#$" + " " + "$#$" + isRequired + "$#$" + ratio + "$#$" + imValue + "$#$" + fieldcounter + "$#$" + fieldType;
                    }
                    int length = fields.Length;
                    fieldcounter += 1;
                    if (!licensed && fieldcounter == 5)
                    {
                        break;
                    }
            }

            

            return fields;

        }

        [WebMethod]
        public static string AppendConverter(string appPages, string appRatios, string appHeights)
        {
           
                Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf"));
                int totalCount = doc.Pages.Count;

                //open second document
                Document pdfDocument2 = new Document(HttpContext.Current.Server.MapPath("Convert/append.pdf"));

                //add pages of second document to the first
                doc.Pages.Add(pdfDocument2.Pages);
                               

                //save concatenated output file
                doc.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf"));

                string Aratio = "";
                string pages = "";
                string height = "";
                string Allheights = "";

                for (int pageCount = 1; pageCount <= doc.Pages.Count; pageCount++)
                {
                    if (pageCount > totalCount)
                    {
                        using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath("Input/image-1" + pageCount + ".png"), FileMode.Create))
                        {
                            //Create Resolution object
                            //Resolution resolution = new Resolution(300);
                            //create PNG device with specified attributes
                            PngDevice pngDevice = new PngDevice();
                            //Convert a particular page and save the image to stream
                            pngDevice.Process(doc.Pages[pageCount], imageStream);
                            //Close stream
                            imageStream.Close();

                            System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("Input/image-1" + pageCount + ".png"));



                            ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath("Input/image" + pageCount + ".png"), out height, out Aratio);

                            image.Dispose();

                            appPages = appPages + "," + "image" + pageCount + ".png";

                            appRatios = appRatios + "," + Aratio;

                            appHeights = appHeights + "," + height;
                        }
                    }                   

                }


                return appPages + "%#" + appRatios + "%#" + appHeights;
           
        }

        [WebMethod]
        public static string btnTextExport_Click(string fileType)
        {
          Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/Export.pdf"));

                switch (fileType)
                {
                    case "txt":

                        //create TextAbsorber object to extract text
                        TextAbsorber textAbsorber = new TextAbsorber();

                        //accept the absorber for all the pages
                        doc.Pages.Accept(textAbsorber);

                        //get the extracted text
                        string extractedText = textAbsorber.Text;

                        System.IO.File.WriteAllText(HttpContext.Current.Server.MapPath("Convert/output.txt"), extractedText);
                        return "output.txt";
                    case "pdf":
                        return "Export.pdf";
                    case "docx":
                        doc.Save(HttpContext.Current.Server.MapPath("Convert/output.docx"), SaveFormat.DocX);
                        return "output.docx";
                    case "svg":
                        doc.Save(HttpContext.Current.Server.MapPath("Convert/output.svg"), SaveFormat.Svg);
                        return "output.svg";
                    case "xps":
                        doc.Save(HttpContext.Current.Server.MapPath("Convert/output.xps"), SaveFormat.Xps);
                        return "output.xps";
                    case "xls":
                        doc.Save(HttpContext.Current.Server.MapPath("Convert/output.xls"), SaveFormat.Excel);
                        return "output.xls";
                    case "html":
                        doc.Save(HttpContext.Current.Server.MapPath("Convert/output.html"), SaveFormat.Html);
                        return "output.html";
                    default:
                        return "";
                }
           

        }
             

        public static int GetHighestPage()
        {
            string[] files = Directory.GetFiles(HttpContext.Current.Server.MapPath("Input/"));
            int[] highPage = new int[files.Length];
            for (int i = 0; i < files.Length; i++)
                highPage[i] = Convert.ToInt32(Path.GetFileName(files[i]).Replace("image", "").Replace(".png", ""));


            return highPage.Max();
        }

        [System.Web.Services.WebMethod()]
        public static string SearchData(string searchText, string[] pageList)
        {
            string name = DateTime.Now.Millisecond.ToString();
            System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath("search/"));

            foreach (FileInfo file in downloadedMessageInfo.GetFiles())
            {
                file.Delete();
            }
            foreach (DirectoryInfo dir in downloadedMessageInfo.GetDirectories())
            {
                dir.Delete(true);
            }

            System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("search/" + name));

            Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf"));

                

                for (int i = 1; i <= doc.Pages.Count; i++)
                {
                    string filename = "Input/" + pageList[i-1];
                    filename = filename.Replace("image", "image-1");
                    Bitmap bmp = (Bitmap)Bitmap.FromFile(HttpContext.Current.Server.MapPath(filename));
                    using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp))
                    {
                        float scale = 150 / 72f;
                        gr.Transform = new System.Drawing.Drawing2D.Matrix(scale, 0, 0, -scale, 0, bmp.Height);


                        Aspose.Pdf.Page page = doc.Pages[i];
                        //create TextAbsorber object to find all words
                        TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(searchText);
                        //   textFragmentAbsorber.TextSearchOptions.IsRegularExpressionUsed = true;
                        page.Accept(textFragmentAbsorber);
                        //get the extracted text fragments
                        TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;

                        Brush brush = new SolidBrush(System.Drawing.Color.FromArgb(50, 255, 255, 0));
                        //loop through the fragments
                        foreach (TextFragment textFragment in textFragmentCollection)
                        {
                            //  if (i == 0)
                            {
                                gr.FillRectangle(
                                    //   gr.DrawRectangle(
                                brush,
                                (float)(textFragment.Position.XIndent),
                                (float)(textFragment.Position.YIndent),
                                (float)(textFragment.Rectangle.Width),
                                (float)(textFragment.Rectangle.Height));

                                for (int segNum = 1; segNum <= textFragment.Segments.Count; segNum++)
                                {
                                    TextSegment segment = textFragment.Segments[segNum];


                                    gr.DrawRectangle(
                                    Pens.Green,
                                    (float)segment.Rectangle.LLX,
                                    (float)segment.Rectangle.LLY,
                                    (float)segment.Rectangle.Width,
                                    (float)segment.Rectangle.Height);
                                }
                            }
                        }
                        gr.Dispose();
                    }

                    bmp.Save(HttpContext.Current.Server.MapPath(filename.Replace("image-1","image_search")), System.Drawing.Imaging.ImageFormat.Png);
                    bmp.Dispose();
                   
                    string height = "";
                    string Aratio = "";
                    System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(filename.Replace("image-1", "image_search")));
                    ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath("search/" + name + "/" + pageList[i - 1]), out height, out Aratio);
                    image.Dispose();

                  //  System.IO.File.Copy(HttpContext.Current.Server.MapPath("Input/image_search" + i + ".png"), HttpContext.Current.Server.MapPath("Input/image" + i + ".png"));


                }

                return name;
        }

        public static string AddAttachments(string path, string filename)
        {
            // Open document
            using (Document pdfDocument = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")))
            {
                // Setup new file to be added as attachment
                FileSpecification fileSpecification = new FileSpecification(path, filename);
                // Add attachment to document's attachment collection
                pdfDocument.EmbeddedFiles.Add(fileSpecification);
                // Save new output
                pdfDocument.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf"));
            }
            return "success";
        }

        [System.Web.Services.WebMethod()]
        public static string GetFileAttachments()
        {
            string outAttach = "";

            // Open document
            using (Document pdfDocument = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")))
            {

                // Get embedded files collection
                EmbeddedFileCollection embeddedFiles = pdfDocument.EmbeddedFiles;

                // Loop through the collection to get all the attachments
                foreach (FileSpecification fileSpecification in embeddedFiles)
                {
                    string[] filename = fileSpecification.Name.Split('\\');

                    outAttach = outAttach + "," + filename[filename.Length - 1] + "," + fileSpecification.Description;

                    // Get the attachment and write to file or stream
                    byte[] fileContent = new byte[fileSpecification.Contents.Length];
                    fileSpecification.Contents.Read(fileContent, 0, fileContent.Length);
                    FileStream fileStream = new FileStream(HttpContext.Current.Server.MapPath("Attachments/" + filename[filename.Length - 1]), FileMode.Create);
                    fileStream.Write(fileContent, 0, fileContent.Length);
                    fileStream.Close();
                }
                if (outAttach.Length > 1)
                {

                    outAttach = outAttach.Substring(1);
                }
            }
                return outAttach;
        }

        [System.Web.Services.WebMethod()]
        public static string RemoveAttachments(string name)
        {

            // Open document
            using (Document pdfDocument = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")))
            {

                // Delete all attachments
                pdfDocument.EmbeddedFiles.Delete(name);

                // Save updated file
                pdfDocument.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf"));

            }
            return "success";
        }

        [System.Web.Services.WebMethod()]
        public static bool CheckLicense()
        {

            Document pdfDocument = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf"));

            // Create TextAbsorber object to extract text
            TextAbsorber textAbsorber = new TextAbsorber();
            
            // Accept the absorber for all the pages
            pdfDocument.Pages[1].Accept(textAbsorber);
            
            // Get the extracted text
            String extractedText = textAbsorber.Text;
            
            if (extractedText.Contains("Evaluation Only. Created with Aspose.Pdf"))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        [WebMethod]
        public static string CreateSignature(string imageData)
        {

            System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath("Images/Signature/"));

            foreach (FileInfo file in downloadedMessageInfo.GetFiles())
            {
                file.Delete();
            }
            Random random = new Random();
            int rand =  random.Next(1000000);
            string fileNameWitPath = HttpContext.Current.Server.MapPath("Images/Signature/sign"+rand+".png");
            using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
            {
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    byte[] data = Convert.FromBase64String(imageData);
                    bw.Write(data);
                    bw.Close();
                }
            }

            return "Signature/sign" + rand + ".png";
        }
        [System.Web.Services.WebMethod()]
        public static string ReplaceText(string txtFind, string txtReplace, string[] pageList)
        {
            try
            {
                Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf"));

                //create TextAbsorber object to find all instances of the input search phrase
                TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("(?i)" + txtFind, new Aspose.Pdf.Text.TextOptions.TextSearchOptions(true));

                textFragmentAbsorber.TextReplaceOptions.ReplaceAdjustmentAction = TextReplaceOptions.ReplaceAdjustment.WholeWordsHyphenation;

                //accept the absorber for all the pages
                doc.Pages.Accept(textFragmentAbsorber);

                //get the extracted text fragments
                TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;

                //loop through the fragments
                foreach (TextFragment textFragment in textFragmentCollection)
                {
                    //update text and other properties
                    textFragment.Text = txtReplace;
                }

                doc.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf"));

                doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf"));

                System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath("Input/"));

                foreach (FileInfo file in downloadedMessageInfo.GetFiles())
                {
                    file.Delete();
                }


                for (int pageCount = 1; pageCount <= doc.Pages.Count; pageCount++)
                {
                    string filename = "Input/" + pageList[pageCount - 1];
                    filename = filename.Replace("image", "image-1");

                    using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath(filename), FileMode.Create))
                    {
                        //Create Resolution object
                        Resolution resolution = new Resolution(300);
                        //create PNG device with specified attributes
                        PngDevice pngDevice = new PngDevice();
                        //Convert a particular page and save the image to stream
                        pngDevice.Process(doc.Pages[pageCount], imageStream);
                        //Close stream
                        imageStream.Close();

                        System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(filename));

                        string height = "";
                        string Aratio = "";

                        ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath(filename.Replace("image-1", "image")), out height, out Aratio);

                        image.Dispose();

                    }

                }
            }
            catch (Exception exp)
            { 
                
            }
            return "success";
        }

        public static void Startup()
        {

            System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath("Input/"));

            foreach (FileInfo file in downloadedMessageInfo.GetFiles())
            {
                file.Delete();
            }

            downloadedMessageInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath("Attachments/"));

            foreach (FileInfo file in downloadedMessageInfo.GetFiles())
            {
                file.Delete();
            }

            downloadedMessageInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath("Images/"));

            foreach (FileInfo file in downloadedMessageInfo.GetFiles())
            {
                file.Delete();
            }

            downloadedMessageInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath("Images/Signature/"));

            foreach (FileInfo file in downloadedMessageInfo.GetFiles())
            {
                file.Delete();
            }

            downloadedMessageInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath("search/"));

            foreach (FileInfo file in downloadedMessageInfo.GetFiles())
            {
                file.Delete();
            }
            foreach (DirectoryInfo dir in downloadedMessageInfo.GetDirectories())
            {
                dir.Delete(true);
            }
        
        }
        public static Aspose.Pdf.Color GetColor(string color)
        { 
            switch(color)
            {
                case "red":
                    return Aspose.Pdf.Color.Red;
                case "black":
                    return Aspose.Pdf.Color.Black;
                case "green":
                    return Aspose.Pdf.Color.Green;
                case "white":
                    return Aspose.Pdf.Color.White;
                case "blue":
                    return Aspose.Pdf.Color.Blue;
                case "grey":
                    return Aspose.Pdf.Color.Gray;

                case "yellow":
                    return Aspose.Pdf.Color.Yellow;
                default:
                    return Aspose.Pdf.Color.Black;
            }
        }
    }

    public class shap
    {
        public float x { get; set; }
        public float y { get; set; }
        public float w { get; set; }
        public float h { get; set; }
        public int p { get; set; }
        public string f { get; set; }
        public string t { get; set; }
        public string n { get; set; }
        public string s { get; set; }
        public string c { get; set; }
        public string wt { get; set; }
        public string st { get; set; }
        public string ratio { get; set; }
        public object imfile { get; set; }
        public string imName { get; set; }
        public string Itype { get; set; }
        public string fieldType { get; set; }

    }
}


-------------------------------------------------------------------
CANVASSAVE.ASPX
--------------------------------------------------------------------------------------------------------------------------------------

C#
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CanvasSave.aspx.cs" Inherits="AsposePdfEditor.CanvasSave" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        string s = Session["fileId"].ToString();
        HiddenField1.Value = s;
        Label1.Text = HiddenField1.Value;
    }

</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
function defaultSelecting() {

alert("Inside defaultSelecting function");

/*    var first = getUrlVars()["host"];
     var second = getUrlVars()["user"];
 first = document.getElementById("myLabel").htmlFor;
     
     alert(first);
     alert(second);   */

  // alert(getParameterByName('host'));

    var url, tesxtval;
    var fp = "Convert/pdf-sample2.pdf";
    var fd = new FormData();
    url = fp;
    var xhr = new XMLHttpRequest(), blob;
    var str = document.getElementsByName('Hiddenfilename').item = fp;
alert(fp);
alert(str);
    alert("path:"+ str);

    $.ajax({
        type: 'POST',
        url: 'CanvasSave.aspx/defaultPdfFunction',
        data: '{ "fileName" : "' + str + '" }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (response) {

            var data = JSON.stringify(response.d);
            data = (data.replace(/['"]+/g, ''));
            dataLoad = data;
           // alert("Data load " + data);
            First();

        },

        error: function (xhr, tesxtval, error) {
            $('#loadingModal').modal('hide');
        }

    });

}
</head>
<body style="width: 1129px">
<asp:Label ID="Label1" runat="server" 
        Text="Label"></asp:Label>
    </div>
    <asp:HiddenField ID="HiddenField1" runat="server" />

    <form id="form1" runat="server">
    <div>
    
    </form>
</body>
</html>



sorry for such a messy code but I badly need help in here.

-------------------------------------------------
WHAT IS THE EXPECT RESULT
-------------------------------------------------

All the Input/output / image / export options from CAnvasSave.aspx.cs file must concatenate with UID (e.g: input+name+uid / image+name+uid / export+uid / uid_export+name
Posted
Comments
Sinisa Hajnal 25-Jan-16 2:29am    
If they are in two different sites, you really don't have any options except to keep separate sessions / cookies / whatever in each and share the values between them by calling some page on the site with given parameters.

Or you could use common database - this is what I would do - and just read current values. You could replace database with shared file, but database would be better.
Member 12277111 25-Jan-16 5:21am    
Sinisa... Well the URL which gets posted from SITE A already has all the values in there.
Site B is the place where I would like to capture it and use it in Canvassave.aspx.cs

FYI - There is no database as the whole process is only [ Binary - PDF - PNG ]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900