How to use and not use iText and jFreeChart

Introduction

In this blog, I will talk about, iText, a Java API used in creating/manipulating PDFs and, jFreeChart, a Java API used in creating charts/graphs. I will make some suggestions based on my experience with iText and jFreeChart on how to use AND not use these APIs for generating PDFs with charts/graphs. I really wanted to write about topic because I found a lot of examples showing how to use iText and jFreeChart that resulted in unacceptable quality for professional use or display. On the other hand, I did see one example that showed how to generate high quality charts/graphs using iText and jFreeChart, however, I considered it incomplete as I was left wonder about “what-ifs.”

Before we proceed, you will need iText v5.0.1 and jFreeChart v1.0.13 to get the examples following to compile and execute. You may download iText at http://itextpdf.com/ and jFreeChart at http://www.jfree.org/.

UglyDemo, basic code example, not very professional results

The following code below is a basic code example I have seen over and over again. It is quick and dirty, straight to the point, but for the speed, you sacrifice control and quality. Pay close attention to the UglyDemo.create(OutputStream) method. In this method, we get an instance of JFreeChart, create a BufferedImage from the chart, and then convert this BufferedImage into iText’s own Image class. If you compile and execute this program, you can see that the generated PDF has an image that exhibits the stair-case effect.

/**
 * Copyright 2010 Jee Vang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package demo.itjfc;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * Ugly demo of how to use jFreeChart
 * with iText. The output will have
 * the stair-case effect.
 * 
 * @author Jee Vang
 *
 */
public class UglyDemo {

	/**
	 * Gets a {@link JFreeChart}.
	 * @return {@link JFreeChart}.
	 */
	public JFreeChart getChart() {
		//create dummy data
		//taken from http://www.java2s.com/Code/Java/Chart/JFreeChartPieChartDemo1.htm
		DefaultPieDataset dataset = new DefaultPieDataset();
		dataset.setValue("One", new Double(43.2));
        dataset.setValue("Two", new Double(10.0));
        dataset.setValue("Three", new Double(27.5));
        dataset.setValue("Four", new Double(17.5));
        dataset.setValue("Five", new Double(11.0));
        dataset.setValue("Six", new Double(19.4));
		
        //use the ChartFactory to create a pie chart
		JFreeChart chart = 
			ChartFactory.createPieChart(
					"Dummy Data", dataset, true, true, false);
		return chart;
	}
	
	/**
	 * Creates PDf file.
	 * @param outputStream {@link OutputStream}.
	 * @throws DocumentException
	 * @throws IOException
	 */
	public void create(OutputStream outputStream) throws DocumentException, IOException {
		Document document = null;
		PdfWriter writer = null;
		
		try {
			//instantiate document and writer
			document = new Document();
			writer = PdfWriter.getInstance(document, outputStream);
			
			//open document
			document.open();
			
			//add image
			int width = 300;
			int height = 300;
			JFreeChart chart = getChart();
			BufferedImage bufferedImage = chart.createBufferedImage(width, height);
			Image image = Image.getInstance(writer, bufferedImage, 1.0f);
			document.add(image);
			
			//release resources
			document.close();
			document = null;
			
			writer.close();
			writer = null;
		} catch(DocumentException de) {
			throw de;
		} catch (IOException ioe) {
			throw ioe;
		} finally {
			//release resources
			if(null != document) {
				try { document.close(); }
				catch(Exception ex) { }
			}
			
			if(null != writer) {
				try { writer.close(); }
				catch(Exception ex) { }
			}
		}
	}
	
	/**
	 * Main method.
	 * @param args No args required.
	 * @throws FileNotFoundException
	 * @throws DocumentException
	 * @throws IOException
	 */
	public static void main(String[] args) throws FileNotFoundException, DocumentException, IOException {
		(new UglyDemo()).create(
				new FileOutputStream(
						new File("ugly-demo.pdf")));
	}
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s