Populating PDF Forms with ColdFusion and iText

For several years our products have populated PDF forms with data from a database. This has worked very well with our implementation of a modified cfpdfform custom tag similar to Ben Forta's.

However, one problem that we could not solve was the need to flatten the PDF forms after they've been populated. Essentially, we needed to remove the fields but leave the values in the same place. This was not possible with the cfpdfform. This is possible with CF8, but I'm not going to tell my customers to run out and purchase CF8. Especially when some of them have Enterprise licenses.

Anyway, I found iText. An open source Java library specifically designed to manipulate PDF's. It's fantastic. It should be noted that the iText library is found in the CF7 lib directory! Which makes it easy to incorporate into your CF project. How interesting of Adobe (or was it Macromedia at the time?) to use the iText library instead of one of their own?

Well, I replaced the 500 lines of code in our cfpdfform tags with about 30 lines of code using iText. Its much more efficient and, for the most part, is very reliable. Here is a sample of the code we used:

//define path and file name of the PDF template with form
pdfFile=arguments.PDFTemplate;

//define the name of my output file
newFile=arguments.PDFOutput;

//create the output file
fileIO=createObject("java","java.io.FileOutputStream").init(newFile);

//load the template PDF with the iText PDF reader
reader = createObject("java","com.lowagie.text.pdf.PdfReader").init(pdfFile);

//load the template into the iText PDF stamper and specify the output file
pdfStamper = createObject("java","com.lowagie.text.pdf.PdfStamper").init(reader, fileIO);

//create a form object to reference
pdfForm = pdfStamper.getAcroFields();

//set the form fields
for (i = 1; i LT ArrayLen(aryValues); i = i + 1){
   pdfForm.setField(Trim(aryValues[i].name),aryValues[i].value);
}

// Flatten the form to remove text fields and replace with existing data.
pdfStamper.setFormFlattening(true);

// Close stamper.
pdfStamper.close();

I'm a big fan of iText. So much so that I purchase the book "iText In Action." It has been an invaluable resource for our dynamic PDF generation.

Comments
Contact Chris SchofieldBlogCFC was created by Raymond Camden. This blog is running version 5.9.001.