Wednesday, July 18, 2012

Convert HTML FORM data to PDF with HiQPDF Html to Pdf .net Library

The solution presented in this article covers the following very common scenario:
You have filled some values in a HTML form of a web page and you want to convert this web page to PDF preserving the values filled in the form and the ASP.NET Session Data
In order to capture the values filled in the ASP.NET page, you have to override the Render method of the ASP.NET page to get the HTML code that would be generated during Render phase of the page processing and convert that HTML code to PDF passing the page URL as base URL parameter to the converter.  The sample code below demonstrates how this procedure works in  HiQPDF HTML to PDF .NET Library.

When a 'Convert This Page to PDF' button in the page is pressed, the convertCrtPageToPdf boolean field is set to true. This field is checked in the overridden Render method and if it is true then the HTML code is captured, converted to PDF and the generated PDF is sent as response to browser instead of the normal HTML:

C# code:
---------
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Text;
using System.IO;

using HiQPdf;

namespace HiQPdf_Demo
{
    public partial class ConvertHtmlPreservingState : System.Web.UI.Page
    {
        // a flag to indicate to Render method if the current page
        // will be converted to PDF
        bool convertCrtPageToPdf = false;
        protected void buttonConvertCrtPage_Click(object sender, EventArgs e)
        {
            // indicate to Render method that the current page
            // will be converted to PDF
            convertCrtPageToPdf = true;

            // save custom value in ASP.NET session variable
            Session["SessionVariable"] = textBoxCrtSessionVariable.Text;

            // show session variable value
            panelSessionVariableValue.Visible = true;
            litSessionVariableValue.Text = Session["SessionVariable"].ToString();
        }
        // override the Render method of the ASP.NET page
        protected override void Render(HtmlTextWriter writer)
        {
            if (convertCrtPageToPdf)
            {
                // setup a TextWriter to capture the current page HTML code
                TextWriter tw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(tw);

                // render the HTML markup into the TextWriter
                base.Render(htw);

                // get the current page HTML code
                string htmlCode = tw.ToString();

                // convert the HTML code to PDF

                // create the HTML to PDF converter
                HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

                // hide the HTML buttons
                htmlToPdfConverter.HiddenHtmlElements = new string[] { "#convertCrtPageDiv"};

                // the base URL used to resolve images, CSS and script files
                string currentPageUrl = HttpContext.Current.Request.Url.AbsoluteUri;

                // convert HTML code to a PDF memory buffer
                byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlCode, currentPageUrl);

                // inform the browser about the binary data format
                HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf");

                // let the browser know how to open the PDF document, attachment or inline, and the file name
                HttpContext.Current.Response.AddHeader("Content-Disposition",
                    String.Format("attachment; filename=ConvertThisHtmlWithState.pdf; size={0}", pdfBuffer.Length.ToString()));

                // write the PDF buffer to HTTP response
                HttpContext.Current.Response.BinaryWrite(pdfBuffer);

                // call End() method of HTTP response to stop ASP.NET page processing
                HttpContext.Current.Response.End();
            }
            else
            {
                base.Render(writer);
            }
        }
    }
}