Saturday, 25 August 2012

Convert to html page to PDF ASp.net

The tool that really help me to do this is iTextSharp, a C# implementation of the iText open source java library for controlling PDF files, and the fact that you can use javascript within the PDF file . Below is the code that explain you how to use an ASPX page which manipulates and streams the PDF file into a zero-height, zero-width IFrame to keep away the user from manipulating the PDF in any way.  You also need to embed the JavaScript into the PDF, which will run once the document is loaded and pops up the Print dialog from Adobe Reader. 

The JavaScript for printing a PDF is not so complex, I embedded it into a function:



protected string GetMyAutoPrintJs()
{
    var script = new StringBuilder();
    script.Append("var kk = getPrintParams();");
    script.Append("kk.interactive = kk.constants.interactionLevel.full;");
    script.Append("print(kk);");

    return script.ToString();
}

In the code-behind for the ASPX page that will stream the PDF and place the script inside the PDF file, I built this function:


protected void StreamMyPdf(Stream pdfSource)
{
    var outputMyStream = new MemoryStream();
    var pdfReader = new PdfReader(pdfSource);
    var pdfMyStamper = new PdfMyStamper(pdfReader, outputMyStream);
    //Add the auto-print javascript
    var writer = pdfMyStamper.Writer;
    writer.AddJavaScript(GetMyAutoPrintJs());

    pdfMyStamper.Close();
    var content = outputMyStream.ToArray();
    outputMyStream.Close();
    Response.ContentType = "application/pdf";
    Response.BinaryWrite(content);
    Response.End();
    outputMyStream.Close();
    outputMyStream.Dispose();
}

 
The PDFReader and PdfMyStamper classes are associated with the iTextSharp library. You can use the classes together to get the stream for output and also access to PDFWriter object that allowed me to add the JavaScript.

No comments :