Generate PDF files using iText and apache velocity template(.vm)

TechnoCrat picture TechnoCrat · Feb 18, 2014 · Viewed 18.8k times · Source

What is the general workflow to generate a PDF using iText and an Apache Velocity template file (.vm) in Java?

I am interested in knowing steps like: parse template file, put Java object in context and steps to be performed to generate pdf etc.

I know this is a very basic question. But I am not able to find even a single example of this type on the web. I found XDocReport, but I am interested to know other alternatives as well.

Please help me with some sample project link or at least the steps to get started.

Answer

Prasad Paravatha picture Prasad Paravatha · Feb 19, 2014

Yes, you can. It all depends on how complex you want the PDFs to be.

Here are the steps for basic functionality

  1. Generate a HTML file using Apache Velocity template file (.vm).
  2. Use com.itextpdf.text.html.simpleparser.HTMLWorker (deprecated) to parse/convert that HTML file into a PDF.
  3. Additionally, you can use com.itextpdf.text.pdf.PdfCopy.PageStamp to add content (borders, stamps, notes, annotations etc) to an existing PDF.

There is also com.itextpdf.tool.xml.XMLWorker for more advanced HTML conversion (adding style sheets etc)