Fill PDF Form Fields from an ASP.NET page using iTextSharp

Download the source code: PDFTest.zip

For a project I’m working on I needed to be able to generate PDF’s containing data from my page.  I came across a library called iTextSharp which is a C# port of the Java library iText.  Using this library allows you to generate PDF files on the fly.  You can download the library here, and need to add it as a reference in your project.

In Adobe Acrobat I created a rather crude looking PDF with two Form Fields for Forename and Surname, named txtForename and txtSurname respectively.

I have created a new web form which contains two text boxes for Forename and Surname, and two buttons to generate PDF files:

PDF Form

When clicking the Create button I am creating a new PdfReader object using my template PDF, then creating a new PdfStamper using a FileStream so that the new PDF is saved to disk. 

Using the PdfStamper.AcroFields object it is possible to use the SetField method to set the value of the field in the PDF, which I am getting from the form’s text boxes.

I have set the PdfStamper.FormFlattening property to true so that the fields won’t be editable in the newly created PDF.

Finally I am using some JavaScript to show the newly generated PDF in a popup window:


protected void btnCreate_Click(object sender, EventArgs e)
{
    try
    {
        string filename = string.Concat(Guid.NewGuid().ToString(), ".pdf");
        PdfReader pdfReader = new PdfReader(Server.MapPath("~/pdf/Template.pdf"));

        using(FileStream stream = new FileStream(string.Concat(Server.MapPath("~/export/"), filename), FileMode.Create))
        {
            PdfStamper pdfStamper = new PdfStamper(pdfReader, stream);

            AcroFields formFields = pdfStamper.AcroFields;
            formFields.SetField("txtForename", txtForename.Text.Trim());
            formFields.SetField("txtSurname", txtSurname.Text.Trim());

            pdfStamper.FormFlattening = true;
            pdfStamper.Close();

            string script = string.Format("window.open('{0}');", string.Concat("/export/", filename));
            ClientScript.RegisterClientScriptBlock(this.GetType(), "newPDF", script, true);
        }
    }
    catch(Exception ex)
    {
        lblMessage.Text = ex.Message;
    }
}

For the Generate button I am using similar code, but instead of using a FileStream to save the PDF to disk on the server, I am using a MemoryStream and outputting the contents of the stream to the page response so that the PDF can be downloaded by the user:


protected void btnGenerate_Click(object sender, EventArgs e)
{
    try
    {
        string filename = string.Concat(Guid.NewGuid().ToString(), ".pdf");
        PdfReader pdfReader = new PdfReader(Server.MapPath("~/pdf/Template.pdf"));

        using (MemoryStream stream = new MemoryStream())
        {
            PdfStamper pdfStamper = new PdfStamper(pdfReader, stream);

            AcroFields formFields = pdfStamper.AcroFields;
            formFields.SetField("txtForename", txtForename.Text.Trim());
            formFields.SetField("txtSurname", txtSurname.Text.Trim());

            pdfStamper.FormFlattening = true;
            pdfStamper.Writer.CloseStream = false;
            pdfStamper.Close();

            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-disposition", string.Format("attachment; filename={0};", filename));
            stream.WriteTo(Response.OutputStream);
        }
    }
    catch (Exception ex)
    {
        lblMessage.Text = ex.Message;
    }
}

Download the source code: PDFTest.zip

Posted on by Joe in ASP.NET, C#

2 Responses to Fill PDF Form Fields from an ASP.NET page using iTextSharp

  1. HarteraFestival

    Congratulations, your idea is great

  2. x10b

    Brilliant – your source code was very simple, and worked first time. Thank you!

Add a Comment