Pages

JFreeChart and PDFBox

In a previous post, I have created a pie chart with JFreeChart and I saved it as a file in PNG format. Let's now put it in a PDF file, using the Apache PDFBox library, version 2. And I stress version 2 because it is still young and has a few changes that also impact right in this area.

First thing, I have added a dependency to PDFBox in my POM file - it's a Maven project, as you have guessed:
<dependency>
 <groupId>org.apache.pdfbox</groupId>
 <artifactId>pdfbox</artifactId>
 <version>2.0.2</version>
</dependency>
For Gradle fueled project, your build.gradle should have this line among its dependencies:
compile group: 'org.apache.pdfbox', name: 'pdfbox', version: '2.0.2'
I suggest you to check the current version on the Apache PDFBox web site. Actually, this post is already slightly outdated since version 2.0.4 has already been released.

Since large part of the code I am about to use here has been already written, I have extracted the JFreeChart creation to a method, createPiePlotSimple(), that would return the object as seen before, without saving it to file. Then I created a createSimpleOnPdf() method that does the more interesting stuff.

Firstly, it creates a PDF document, and add a page to it.
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
Then I call the createPiePlotSimple() to get the JFreeChart object, and create from it a buffered image.
JFreeChart chart = createPiePlotSimple();
BufferedImage bi = chart.createBufferedImage(500, 500);
Finally, in a try-catch block, since there are lot of IOException that could be thrown around in this piece of code, I convert the buffered image to a PDImageXObject, specific for the PDF format, using a specialized factory class. The image is drawn passing through a PDPageContentStream object, and then I can finally save my PDF file.
PDPageContentStream cs = new PDPageContentStream(doc, page);
PDImageXObject ximage = LosslessFactory.createFromImage(doc, bi);
cs.drawImage(ximage, 100, 100);
cs.close();
doc.save(new File("dump/pie.pdf"));
Pay attention that PDImageXObject and LosslessFactory are new in version 2. Before that we had PDXObjectImage and PDJpeg, PDPixelMap, and PDCCitt. I suggest to have a look at the migration page if you need more information.

I pushed the changes to GitHub.

No comments:

Post a Comment