Step 1: Create PDF templates

I find it easy to create a document with form fields that can be used to fill in a database result set. If you don't have Adobe Acrobat to create the template, no problem. Using the OpenOffice.org Writer word processor you can create the document without spending any of your hard-earned cash. That's how the first page and continuation page PDF templates for this example were created.

Step 2: Get form fields coordidates for each template

Since each template has form fields, all we need to do is:
  1. Instantiate a PdfReader object for each template.
  2. Iterate over the reader's AcroFields and get each field's coordinates.

IMPORTANT (2010-05-21): see inline comments regarding iTextSharp versions 5.0.2.0 and higher, and how to get each field's coordinates for older versions.

string[] PDF_TEMPLATE = {
"/cs/itext/bill_template.pdf", "/cs/itext/bill_template2.pdf"
};
var c = HttpContext.Current;
var burl = c.Request.Url.GetLeftPart(UriPartial.Authority);
PdfReader reader = null;
foreach (string s in PDF_TEMPLATE) {
  reader = new PdfReader(c.Server.MapPath(s));
  var sb = new StringBuilder(
    "<h3>PDF Template Form Field Coordinates</h3>"
  );
  sb.AppendFormat(
    "<div><a href='{0}{1}'>{1}</a></div>", burl, s
  );      
  var fields = reader.AcroFields;
  foreach (string k in fields.Fields.Keys) {
/*
 * iTextSharp >= 5.0.2.0 GetFieldPositions() returns IList<FieldPosition>,
 * prior versions returned float[]  
*/
    var f = fields.GetFieldPositions(k)[0];
    sb.AppendFormat("<div><strong>{0}</strong>: ", k);
    sb.AppendFormat("llx: {0}f, lly: {1}f, urx: {2}f, ury: {3}f</div>",
      f.position.Left.ToString(), f.position.Bottom.ToString(),
      f.position.Right.ToString(), f.position.Top.ToString()
    );
/*
 * use this block for iTextSharp < 5.0.2.0
    var positions = fields.GetFieldPositions(k);
    sb.AppendFormat("<div><strong>{0}</strong>: ", k);
    sb.AppendFormat("llx: {0}f, lly: {1}f, urx: {2}f, ury: {3}f</div>",
      positions[1].ToString(), positions[2].ToString(),
      positions[3].ToString(), positions[4].ToString()
    );
*/
  }      
  c.Response.Write(sb.ToString());      
}

If you can't guess from looking, the coordinate system for each form field is as follows:

  • llx: lower left x-coordinate
  • lly: lower left y-coordinate
  • urx: upper right x-coordinate
  • ury: upper right y-coordinate

View form field coordinates of PDF template files

In Part 2 we'll see how to use the PDF template's form field coordinates to create simple and flexible multi-page billing statement.

More kuujinbo.info iText examples

iText References