HiQPdf Documentation

Preserve HTML Form and ASP.NET Session Values

Quickly Create High Quality PDFs

There are two common scenarios covered by this topic:

1. 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 this procedure. 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#
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);
            }
        }
    }
}
2. You have some variables stored in ASP.NET session and you want to convert a web page that uses those variables

When you convert an ASP.NET page given by an URL, the converter will make a GET request to the page URL in a new session and the values stored in the current ASP.NET Session are not available. There are two situations to consider when resolving this problem:

If you want to convert to PDF the same ASP.NET page with the page from where you call the converter (the current page) then the solution is to override the Render method of the current ASP.NET page, get the HTML code to be rendered and convert that HTML code to PDF. This method is described in detail, including sample C# code, in the section above.

If you want to convert a different ASP.NET page of the same application then the solution is to get the HTML code of the ASP.NET page to convert with a call to HttpServerUtility.Execute() method from ASP.NET. An object of the HttpServerUtility type is exposed by the Server property of the ASP.NET page object. The only restriction is that the ASP.NET page to convert must be in the same application with the ASP.NET page from where the converter is called.

The sample code below demonstrates the solution for this second situation. When a 'Convert Another Page to PDF' button in the current ASP.NET page is pressed, another ASP.NET page in the same application is converted to PDF:

C#
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
    {
        protected void buttonConvertAnotherPage_Click(object sender, EventArgs e)
        {
            // save custom value in ASP.NET session variable
            Session["SessionVariable"] = textBoxAnotherSessionVariable.Text;

            // setup a TextWriter to capture the HTML code of the page to convert
            TextWriter tw = new StringWriter();

            // execute the 'AnotherPageInThisApplication.aspx' page in the same application and capture the HTML code
            Server.Execute("AnotherPageInThisApplication.aspx", tw);

            // get the HTML code from writer
            string htmlCode = tw.ToString();

            // convert the HTML code to PDF

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

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

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

            // 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=ConvertAnotherHtmlWithState.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();
        }
    }
}
See Also

Other Resources