Preserve HTML Form and ASP.NET Session Values

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.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.Rendering;

using System.IO;
using HiQPdfClient;

namespace HiQPdf_Demo.Controllers
{
    public class ConvertHtmlPreservingStateController : Controller
    {
        private ICompositeViewEngine m_viewEngine;

        public ConvertHtmlPreservingStateController(ICompositeViewEngine viewEngine)
        {
            m_viewEngine = viewEngine;
        }

        // GET: ConvertHtmlPreservingState
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ConvertThisViewToPdf(IFormCollection formCollection)
        {
            // add the custom value to view data
            ViewDataDictionary viewData = new ViewDataDictionary(ViewData);
            viewData.Clear();

            viewData.Add("MyTextValue", formCollection["textBoxText"]);
            viewData.Add("MyDropDownListValue", formCollection["dropDownListValues"]);

            // get the HTML code of this view
            string htmlToConvert = RenderViewAsString("Index", viewData);

            // the base URL to resolve relative images and css
            HttpRequest httpRequest = this.ControllerContext.HttpContext.Request;
            UriBuilder uriBuilder = new UriBuilder();
            uriBuilder.Scheme = httpRequest.Scheme;
            uriBuilder.Host = httpRequest.Host.Host;
            if (httpRequest.Host.Port != null)
                uriBuilder.Port = (int)httpRequest.Host.Port;
            uriBuilder.Path = httpRequest.PathBase.ToString() + httpRequest.Path.ToString();
            uriBuilder.Query = httpRequest.QueryString.ToString();

            String thisViewUrl = uriBuilder.Uri.AbsoluteUri;
            String baseUrl = thisViewUrl.Substring(0, thisViewUrl.Length - "ConvertHtmlPreservingState/ConvertThisViewToPdf".Length);

            string serverIP = formCollection["textBoxServerIP"];
            uint serverPort = uint.Parse(formCollection["textBoxServerPort"]);
            string serverPassword = formCollection["textBoxServerPassword"];

            // instantiate the HiQPdf HTML to PDF converter
            HtmlToPdf htmlToPdfConverter = new HtmlToPdf(serverIP, serverPort);

            // use server password if necessary
            if (serverPassword.Length > 0)
                htmlToPdfConverter.ServerPassword = serverPassword;

            // render the HTML code as PDF in memory
            byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlToConvert, baseUrl);

            FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
            fileResult.FileDownloadName = "ThisViewToPdf.pdf";

            return fileResult;
        }

        public string RenderViewAsString(string viewName, ViewDataDictionary viewData)
        {
            // create a string writer to receive the HTML code
            StringWriter stringWriter = new StringWriter();

            // get the view to render
            ViewEngineResult viewResult = m_viewEngine.FindView(ControllerContext, viewName, true);
            // create a context to render a view based on a model
            ViewContext viewContext = new ViewContext(
                    ControllerContext,
                    viewResult.View,
                    viewData,
                    TempData,
                    stringWriter,
                    new HtmlHelperOptions()
                    );

            // render the view to a HTML code
            viewResult.View.RenderAsync(viewContext).Wait();

            // return the HTML code
            return stringWriter.ToString();
        }
    }
}

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.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.Rendering;

using System.IO;
using HiQPdfClient;

namespace HiQPdf_Demo.Controllers
{
    public class ConvertHtmlPreservingStateController : Controller
    {
        private ICompositeViewEngine m_viewEngine;

        public ConvertHtmlPreservingStateController(ICompositeViewEngine viewEngine)
        {
            m_viewEngine = viewEngine;
        }

        // GET: ConvertHtmlPreservingState
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ConvertAnotherViewToPdf(IFormCollection formCollection)
        {
            // set a session variable to be used in the the converted view
            ViewDataDictionary viewData = new ViewDataDictionary(ViewData);
            viewData.Clear();

            viewData["MySessionVariable"] = formCollection["textBoxAnotherSessionVariable"];

            // get the About view HTML code
            string htmlToConvert = RenderViewAsString("AnotherView", viewData);

            // the base URL to resolve relative images and css
            HttpRequest httpRequest = this.ControllerContext.HttpContext.Request;
            UriBuilder uriBuilder = new UriBuilder();
            uriBuilder.Scheme = httpRequest.Scheme;
            uriBuilder.Host = httpRequest.Host.Host;
            if (httpRequest.Host.Port != null)
                uriBuilder.Port = (int)httpRequest.Host.Port;
            uriBuilder.Path = httpRequest.PathBase.ToString() + httpRequest.Path.ToString();
            uriBuilder.Query = httpRequest.QueryString.ToString();

            String thisViewUrl = uriBuilder.Uri.AbsoluteUri;
            String baseUrl = thisViewUrl.Substring(0, thisViewUrl.Length - "ConvertHtmlPreservingState/ConvertAnotherViewToPdf".Length);

            string serverIP = formCollection["textBoxServerIP"];
            uint serverPort = uint.Parse(formCollection["textBoxServerPort"]);
            string serverPassword = formCollection["textBoxServerPassword"];

            // instantiate the HiQPdf HTML to PDF converter
            HtmlToPdf htmlToPdfConverter = new HtmlToPdf(serverIP, serverPort);

            // use server password if necessary
            if (serverPassword.Length > 0)
                htmlToPdfConverter.ServerPassword = serverPassword;

            // render the HTML code as PDF in memory
            byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlToConvert, baseUrl);

            // send the PDF document to browser
            FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
            fileResult.FileDownloadName = "AnotherViewToPdf.pdf";

            return fileResult;
        }
    }
}

See Also