Sunday, April 13, 2008

Writing PDF charts with iText in less than 2 minutes

If you didnt already know, iText is an API through which you can write dynamic PDF content from a java application. iText is strong contender for being a solution that can be applied across different environments. Given the increase in the number of applications using PDF these days, an API like iText makes life a lot simpler for developers.

iText is also integrated with other libraries out there like the JFreeChart API. This means that you can create a JFreeChart object and pass it to an iText method and expect PDF content to be returned as a result. That is pretty neat and the solution can be applied over a number of places. Given below is a brief overview of charts that can be created and converted to PDF format.

To begin with lets create some JFreeChart objects that resemble a piechart and a barchart given some random data. The code snippet below would do the trick to accomplish this. Its not rocket science really. The code is self explanatory. You add a couple of name value pairs and mention how much of the chart area each value is allowed to occupy. Once the JFreeChart objects are constructed we can go ahead and convert the objects to PDF format.

Get a bar chart:

Get a pie chart:

To convert these objects to PDF, first declare a Document from the iText API within a defined Rectangle. Use a PdfWriter object to write the contents of the PDF. The iText API is capable of creating a java AWT Graphics2D object based on a given PdfTemplate. Use the JFreeChart API to draw on the Graphics2D object and that is pretty much it ! Here is some code

Converting JFreeChart objects to PDF:

Run the program by calling the appropriate methods:


Bar PDF:

Pie PDF:

Besides you can integrate this solution with java SWING if you wanted to since it supports AWT objects. You could also write to a browser by getting hold of a response output stream instead of a file and thereby allowing your users to experience rich dynamic PDF content on the fly. iText is capable of much more, like

  • Working with tables
  • Image support
  • Fonts
  • Indenting and nesting
  • Interactive forms with PDF
  • RTF Documents
  • Digitally signing a PDF

There is much more to the API than the list mentioned above. If you are to work with this API I would recommend that you buy the iText in Action book from Manning. The example in this post is based on examples from the book and it really does deliver details of the API in a short and sweet format.

iText in Action: