kuujinbo_dot_info

Filling in PDF Forms with iTextSharp

Posted 2007-01, updated 2012-01-18.

Haven't had much time lately to work on web stuff, but iText is quickly becoming a favorite. Finally gave in and bought the book, iText in Action. Read parts of two chapters so far and am extremely satisfied. Before buying the book I played around with a simple PDF generation example, and then another example that added an image to a PDF's page header. So after reading less than two chapters, it literally only took a few minutes to create the following example that fills a PDF form with input from a user visiting the web site. A couple of real-world applications immediately come to mind: you could create printable training certificates for users, or generate reports using a PDF template and records from a database.

Code

The code to get you started is ridiculously short and sweet - we retrieve the TextBox control values, (see the Demo tab above) then fill in all the values in the PDF form template:

  private void _streamPdf() {
    Response.ContentType = "application/pdf";
    Response.AppendHeader(
      "Content-Disposition",
      "attachment;filename=itext_fill.pdf"
    );
    PdfReader r = new PdfReader(
      new RandomAccessFileOrArray(Request.MapPath("test_fill.pdf")), null
    );
    using (PdfStamper ps = new PdfStamper(r, Response.OutputStream)) {
      AcroFields af = ps.AcroFields;
      af.SetField("lname", lname.Text);
      af.SetField("fname", fname.Text);
      af.SetField("address", address.Text);
      af.SetField("zip", zip.Text);
      ps.FormFlattening = true;
    }
    Response.End();
  }

Notes

  • PdfStamper is used to add content to a PDF document. In the example we're filling in form fields, but you can just as easily add arbitrary content to the document by absolute position, either on top of or below (like a watermark) existing content.
  • Passing RandomAccessFileOrArray, then null to the PdfReader constructor is memory-friendly.
  • To fill the individual form fields in the PDF document/template, you call SetField(). The first parameter is the PDF form's text field name, and the second paramter is the value you want to fill in.
  • setFormFlattening (C# property named FormFlattening) is ideal for tasks such as printing certificates, where you don't want an average end-user modifying the document.
  • Since this example is implemented using ASP.NET web forms, specifically handling the Button control's OnCommand event, you must call Response.End(). Otherwise the web form continues through it's life cycle and appends all of the page's HTML markup to the PDF. I've lost count of the number of time I've seen questions from people having problems creating PDFs because they're omitting this step.
Last Name  
First Name  
Address  
Zip Code