iText is a wonderful library if you want to generate PDFs in Java. It comes with a huge set of API to create/manage a PDF file. We already saw in our previous tutorial how to generate a pdf file in itext and also how to merge two pdf files using itext.
In this tutorial we will see how to generate Pie charts and Bar charts in Java using iText and jFreeChart library. First a brief note about jFreeChart.
JFreeChart is a free 100% Java chart library that makes it easy for developers to display professional quality charts in their applications. It gives a wide range of API to generate charts and graphs in Java.
Step 1: Download required Jar files
For this example we will need following jar files.
In above code, we have created two methods that returns JFreeChart object. These methods creates charts using jFreeChart API. Note that we have used dummy data. In real example these values must be dynamically fetched from database or other data source.
Also note that the main method is still empty. We haven’t added yet the code to generate actual PDF file using iText API.
Step 3: Generate PDF with Charts/Graphs in Java using iText
Now its time to generate the actual PDF files. For this we will use iText library and pass it the graphs generated by jFreeChart library. Add following code in your java class.
In above code we have created a method writeChartToPDF() which take few arguments like jFreeChart object, width, height and filename and write a PDF files in that file.
This is ofcourse very preliminary example of adding pie charts in PDF using Java iText/jFreeChart. But atleast it gives basic idea of how to achieve this. Feel free to modify the above code and play around to generate different charts/graphs in PDF.