How to convert ASPX page to PDF with forms filled by data using C# and .NET?

How to convert ASPX page to PDF with forms filled by data using C# and .NET?

PDF Vision .Net

.Net assembly to convert HTML, ASPX to PDF in .Net and Image, JPG, Multipage TIFF to PDF in .Net and C#.
html-to-rtf-scheme

PDF Vision .Net

How to convert ASPX page to PDF with forms filled by data using C# and .NET?
pdf-vision-scheme

Introduction

If you are looking for a solution to programmatically convert ASPX page with form filled by data to PDF in .NET and C#, you are in the right place!

How to convert ASPX page to PDF with forms filled by data using C# and .NET?
  • Various API to convert ASPX to PDF
  • Requires only .NET 2.0
  • Completely written in C#
  • Preserve all data filled by user in forms

PDF Vision .Net is what you need. It's a very simple in use and robust component! We offer you 100% .NET library, which will enhance your Web-Server ASP.Net or Windows Forms application to generate PDF documents on fly from ASPX and HTML.


Download

To see this functionality firsthand, download the freshest «PDF Vision .Net» with code examples, 46.7 Mb.

Limitations

PDF Vision .Net The limitations of the free version are: The trial notice "Created by unlicensed version of PDF Vision .Net" and the random addition of the word "TRIAL".


Implementation and code sample

In this article we'll create a simple ASP.Net C# application with some forms controls (TextBox, ListBox and CheckBox) and the button "Print to PDF.

As you might agree, if you simply take an ASPX page and pass it to any PDF converter you will see the colorful result but all field forms and controls will have their default states. In other words, the basic problem in conversion of ASPX pages is to preserve all various data entered by an user.

Here you'll find the step by step answer how to solve this inconvenient problem:

The ready project you may find inside "PDF Vision .Net->Code Samples->CSharp->ASP.Net - Print ASPX to PDF".

See the Online demo of ASPX to PDF.

Let's start:

First of all, create a new ASP.Net Web application. Next add controls inside form: TextBox, ListBox and CheckBoxes.


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>How convert ASPX page to PDF with filled forms in C# and .Net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>How convert ASPX page to PDF with filled forms in C# and .Net</h1>
        <div>Fill some house description here:<br />
            <br />
            House space (m2):
            <asp:TextBox ID="txtHouseSpace" runat="server"></asp:TextBox>
            <br />
            <br />
            Number of floors:
            <asp:ListBox ID="lstFloorsNum" runat="server" Rows="1">
                <asp:ListItem Selected="True">1</asp:ListItem>
                <asp:ListItem>2</asp:ListItem>
                <asp:ListItem>3</asp:ListItem>
            </asp:ListBox>
            <br />
            <br />
            <asp:CheckBox ID="chkBathroom" runat="server" Checked="True" Text="Bathroom" />
&nbsp;<asp:CheckBox ID="chkToilet" runat="server" Checked="True" Text="Toilet" />
&nbsp;<asp:CheckBox ID="chkSwimmingPool" runat="server" Text="Swimming pool " />
        </div>
        <br />
            <p>
                <asp:Button ID="ButtonPDF" runat="server" onclick="GetPDF_Click"
                            Text="Print to PDF" />
            </p>
        </div>
    </form>
</body>
</html>

The main idea is to get the state and values of all controls and store in a our custom class object before start conversion to PDF.

The next step is prepare the class to store all data and values from all of our controls (TextBoxes, ListBoxes and CheckBoxes). The next step is add this custom class to our application:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// 
/// Summary description for HouseDescription
/// 
public class HouseDescription
{
	public HouseDescription()
	{
        HouseSpace = 120.0f;
        FloorsNumber = 2;
        IsBathroom = true;
        IsToilet = true;
        IsSwimmingPool = false;
	}
    public float HouseSpace { set; get; }
    public int FloorsNumber { set; get; }
    public bool IsBathroom { set; get; }
    public bool IsToilet { set; get; }
    public bool IsSwimmingPool { set; get; }
}

After that we've got the object with all data we need to place it inside Page.Application with unique ID. Thus all of our data will be available approx during 20 minutes if we know the unique ID. By the way you can customize the time of keeping objects inside Page.Application property.

Actually it's insecure to keep at server this data during 20 minutes, so the good practice is to remove the object from Application at once after PDF generation.

The final logic is recreate the page state by ID. In other words, the method which will convert ASPX to PDF will open the page with parameter, like a:

http://www.mysite.com/default.aspx?id=123456789

Knowing the ID you will find the necessary object of custom class and fill all controls: TextBoxes, CheckBoxes and ListBoxes.

This is rest of C# code (Default.aspx.cs):

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string id = Request.QueryString["id"];
        HouseDescription hd = null;


        if (id != null)
        {
            // Recreate the page state
            hd = (HouseDescription)Application[id];
            SetPageState(hd);
        }
        // First time loading. Set all to default.
        else
        {
            if (!IsPostBack)
                SetPageState(new HouseDescription());
        }

    }
    protected void GetPDF_Click(object sender, EventArgs e)
    {
        // 1. Save the current page state
        // 1.1. Create ID
        string id = Guid.NewGuid().ToString();

        // 1.2 Save the current state in the Application State.
        HouseDescription hd = GetPageState();
        Application[id] = hd;

        // 2. Create url
        string pageUrl = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
        string pageUrlWithQuerry = string.Format("{0}?id={1}", pageUrl, id);

        // 3. Get PDF
        SautinSoft.PdfVision v = new SautinSoft.PdfVision();

        // Set "Edge mode" to support all modern CSS.
        SautinSoft.PdfVision.TrySetBrowserModeEdgeInRegistry();
        byte[] pdf = v.ConvertHtmlFileToPDFStream(pageUrlWithQuerry);

        // 4. Show PDF result
        if (pdf != null)
        {
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = "application/PDF";
            //Response.AddHeader("Content-Disposition:", "attachment; filename=Result.pdf");
            Response.AddHeader("Content-Disposition:", "inline; filename=Result.pdf");
            Response.BinaryWrite(pdf);
            Response.Flush();
            Response.End();
        }
    }
    protected void SetPageState(HouseDescription hd)
    {
        txtHouseSpace.Text = hd.HouseSpace.ToString();
        lstFloorsNum.SelectedValue = hd.FloorsNumber.ToString();
        chkBathroom.Checked = hd.IsBathroom;
        chkToilet.Checked = hd.IsToilet;
        chkSwimmingPool.Checked = hd.IsSwimmingPool;
    }
    protected HouseDescription GetPageState()
    {
        HouseDescription hd = new HouseDescription();

        float houseSpace = 0f;

        if (float.TryParse(txtHouseSpace.Text, out houseSpace))
            hd.HouseSpace = houseSpace;

        int floorsNum = 1;
        if (Int32.TryParse(lstFloorsNum.SelectedValue, out floorsNum))
            hd.FloorsNumber = floorsNum;

        hd.IsBathroom = chkBathroom.Checked;
        hd.IsToilet = chkToilet.Checked;
        hd.IsSwimmingPool = chkSwimmingPool.Checked;
        return hd;
    }
}

The method "GetPageState" gets all data from controls and keeps it an object of a custom class.

The method "SetPageState" fills all page controls from an object of a custom class.

The method "GetPDF_Click" inserts the object of a custom class inside Page.Application using unique ID. Next this method calls the conversion to PDF, but this ID.

And the method "Page_Load" recreates the page state (fill all controls) in case of it met the ID and found an object of custom class corresponding to this ID.

See how this project works in real...


Requirements and Technical Information

Requires only .NET 2.0 or above. Our product is compatible with all .NET languages and supports all Operating Systems where .NET Framework can be used. Note that «PDF Vision .Net» is entirely written in managed C#, which makes it absolutely standalone and an independent library.


Platform component, runs on Windows


Our component has proven itself on cloud platforms and services:

  • Microsoft Azure
  • Amazon Web Services (AWS)
  • Google Cloud Platform
  • SharePoint
  • Docker
  • etc.

If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below: