Friday, March 16, 2012

Callback in .Net

        First create a javascript function with name EndGetData(), You can use any name.
        this function will get executed after successfun call back.

        function EndGetData(arg) {          
                    alert(arg);         
                }

        Then Inherite your page by "ICallbackEventHandler" like
        public partial class _Default : System.Web.UI.Page ,ICallbackEventHandler
         {

        Now use the following code in the page load method of the page.

        String strfunction = Page.ClientScript.GetCallbackEventReference(this, "arg", "EndGetData", "context");
        String strcallbackScript;
        strcallbackScript = "function CallServer(arg, context)" +
        "{ " + strfunction + ";}";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
        "CallServer", strcallbackScript, true);

        Here we have used two function in the client script(You can use any name for function.)
        1. EndGetdata - Which will called after call back.
        2. CallServer - Which will called in the begining of the callback.

        Now call the CallServer() function on click of the button from the .aspx page.
        <input type="button" onclick="CallServer('Passing_Parameter',"");" value="Click Me" />

        string globalVariable;
        public void RaiseCallbackEvent(String Passing_Parameter)
            {
                //Code for callback function....
                //And store the output in the global variable.
            }
            public String GetCallbackResult()
            {
                //Do after callback result
                //Return the global variable.
                return globalVariable
            }

            If you have any query then feel free to comment.
           

Thursday, March 15, 2012

Capture image from Pdf

Use PDFLibCmdLine.exe and PDFLibNet.dll to your Bin folder to capture image from pdf.
Here FileName is the name of pfd file from which we want to capture image,
and intPageNumber is the page number which we want to capture.
Here is the code for class.
private string getImageFromPDF(string FileName,int intPageNumber)
        {
            try
            {
                intPageNumber = 1;
                string PngName = FileName.Replace(".pdf", "");
                if (File.Exists(Server.MapPath("PDF/" + PngName + ".png").ToString()))
                    return PngName + ".png";

                string imageLocation = null;
                imageLocation = ExternalPDFLib.GetPageFromPDF(Server.MapPath("bin"), Server.MapPath("PDF/" + FileName).ToString(), Server.MapPath("PDF").ToString(), intPageNumber , 120, "", 0, "", 0);
                return imageLocation;
            }
            catch (Exception ex)
            {
                return "";
            }
        }

By this method we can capture image of any page from pdf file.

Additionaly we have to use one more class to use the PDFLibCmdLine.exe and capture the image.

public class ExternalPDFLib
{
    public static string appName = "PDFLibCmdLine.exe";

    const int RENDER_DPI = 150;
   
    public static string GetPageFromPDF(string appPath, string sourceFileName, string destFolderPath, int iPageNumber, int DPI, string password, int rotations, string searchText, int searchDir)
    {
        string functionReturnValue = null;
        functionReturnValue = "";
        string myString = ExecuteCMD(appPath + "\\" + appName, string.Format("{0} \"{1}\" \"{2}\" {3} {4} \"{5}\" \"{6}\" {7}", "png", sourceFileName, destFolderPath, iPageNumber, DPI, password, searchText, searchDir));
        try {
            if (Regex.IsMatch(myString, "^authfail", RegexOptions.IgnoreCase)) {
                return "authfail";
            }
            string myFilePath = Regex.Replace(myString, "png=(.+)\\npage=.*$", "$1").Trim();
            string myPageNumString = Regex.Replace(myString, "[\\d\\D]+page=(\\d+)[\\d\\D]*$", "$1");
           
            functionReturnValue = myFilePath;
            iPageNumber = Convert.ToInt32(myPageNumString);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return functionReturnValue;
    }

    const int CmdTimeout = 3;
    public static string ExecuteCMD(string cmd, string args)
    {
        try
        {
            string functionReturnValue = null;
            functionReturnValue = "";
            using (Process myProcess = new Process())
            {
                myProcess.StartInfo.FileName = cmd;
                myProcess.StartInfo.Arguments = args;
                myProcess.StartInfo.UseShellExecute = false;
                myProcess.StartInfo.RedirectStandardOutput = true;
                myProcess.StartInfo.CreateNoWindow = true;
                myProcess.Start();
                ThreadedKill(myProcess.Id);
                //myprocess.PriorityClass = ProcessPriorityClass.Normal;
                functionReturnValue = myProcess.StandardOutput.ReadToEnd();
                myProcess.WaitForExit();               
            }
            return functionReturnValue;
        }
        catch (Exception ex)
        {
            return "";
        }
    }

    public static void KillProcessAfterTimeout(object Opid)
    {
        try
        {
            int pid = (int)Opid;
            Process pProcess = System.Diagnostics.Process.GetProcessById(pid);
            DateTime expiration = DateTime.Now.AddSeconds(CmdTimeout);
            while (DateTime.Now < expiration)
            {
                Thread.Sleep(100);
                if (null == pProcess)
                {
                    return;
                }
            }
            if (pProcess != null)
            {
                pProcess.Kill();
            }
        }
        catch (Exception ex)
        {
        }
    }

    public static void ThreadedKill(int pid)
    {
        Thread myThread = new Thread(new ParameterizedThreadStart(KillProcessAfterTimeout));
        myThread.Start(pid);
    }


}


C# Create Pdf from Div

Use iTextSharp.dll to create pdf from html div. Here id of my html div is "PrintPdf" which is runat="server".
Here UniqueNo is the name for generated pdf.
public bool CreatePdf(string UniqueNo)
        {
            Document document = new Document(PageSize._11X17, 40, 50, 30, 65);
            try
            {
                FileStream objFileStream = null;
                if (File.Exists(Server.MapPath("PDF/" + UniqueNo + ".pdf").ToString()))
                {
                    return true;
                }
                else
                {
                    objFileStream = new FileStream(Server.MapPath("PDF/" + UniqueNo + ".pdf"), FileMode.Create);
                }
                PdfWriter.GetInstance(document, objFileStream);

                document.Open();

                var sb = new StringBuilder();
                string head = "<html><head><meta name=\"Generator\" content=\"EditPlus\"><meta    name=\"Author\" content=\"\"><meta name=\"Keywords\" content=\"\"><meta name=\"Description\" content=\"\"><link href=\"css/style.css\" rel=\"stylesheet\" type=\"text/css\" /></head><body>";
                string tail = "</body></html>";               

                PrintPdf.RenderControl(new HtmlTextWriter(new StringWriter(sb)));
               
                string htmlText = head + sb.ToString() + tail;               

                //make an arraylist ....with STRINGREADER since its no IO reading file...
                var htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(htmlText), null);
                //add the collection to the document
                for (int k = 0; k < htmlarraylist.Count; k++)
                {
                    document.Add((IElement)htmlarraylist[k]);
                }
                document.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

If the div contains the GridView control then override following method.

 public override void VerifyRenderingInServerForm(Control control)
        {
            return;
        }