Tuesday, July 12, 2011

CREATING PDF FROM A TEMPLATE USING iTEXT

iText is a freely available Java library from Lowagie.com. The iText library is powerful and supports the generation of PDFs. iText can also be used to generate PDF from a predefined template. This document will describe the various steps that need to follow to create PDF dynamically from a pre defined template.
Creating the template:
A template can be created using several tools like open office, Adobe Acrobat writer etc. In our example we have used open office.
   1. Open a new document in open office and create a new document. Go to “view” and make the “Form Design” mode on (as shown in the screenshot below).

 2. Enter the text which will represent the static portion of the template.
 3.  Once the “Form Design” mode is turned on, the corresponding toolbar will be added as highlighted in the screenshot above. Now click the “Text Box” and insert a text box in the document. Double click the text box and insert the required inputs there. The pop up will look like the screenshot below


 4.  Once the template document is created, save and the export the document as PDF and this document will be used as the template for the PDF creation (As highlighted in the above screenshot).




Fill up the template using iText
The next step is to read the template and populate the template to generate PDF dynamically.
iText provides a PdfReader to read PDF files and PdfStamper to modify or add content to a PDF document. Since the template is a PDF file, the PdfReader will read the template and PdfStamper will populate the fields dynamically with real time data. Following are the steps

   1.       Read the PDF template using the iText PdfReader. The template can be put anywhere in the file system. But in a real life project scenario, it should be placed inside the project folder.

   2.       Create a PdfStamper with the PdfReader and a ByteArrayOutputStream as parameter. Following are the code snippets.

   3.       Populate the template fields using the instance of the PdfStamper object. The setField () method takes the key and the value as argument. The “key” should be the “Name” of the text box that was given during the template creation. Please make sure that the “key” is same as the “Name” field. Otherwise the field will not be populated.



          

   4.       After populating the required fields, close the PdfStamper with the PdfReader objects.