PDF Add Chart iText Example JFreeChart Java Tutorial

In this blog tutorial, we will provide a simple Java example that will explain how to create a 2D (2 Dimensional) chart inside a PDF file using iText library. To create a chart inside a PDF file, we will be using JFreeChart API as well. So, when you run this example you will need the JFreeChart Jar files in your class path. The files of our interest would be the following;
jfreechart-1.0.13.jar
jcommon-1.0.16.jar
Apart from this, you will also need the iText Jar file in your classpath. A fully commented and working example of a Java code, that will create a 2D bar chart inside a PDF file is shown below. As we move along with this tutorial, we will explain each and every method and provide more examples covering both JFreeChart and iText. Refer to the code below for a 2D vertical bar chart example;
/* This example tutorial demonstrates how to draw a chart in a PDF document using iText Java API, and JFreeChart Java API */
import java.io.*;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
public class PDFChartExample {  
     public static void main(String[] args){
        try {
                /* Begin with Drawing a 2D Bar Chart using JFreeChart */
                DefaultCategoryDataset mychartData=new DefaultCategoryDataset();
                mychartData.setValue(90,"Marks","English"); /* Specify Values for 2D Chart */
                mychartData.setValue(78,"Marks","Maths"); /* Specify X Axis and Y Axis Values for Chart */
                mychartData.setValue(40,"Marks","Science");
                mychartData.setValue(89,"Marks","History");
                /* We now create a bar chart using the ChartFactory object's createBarChart Method, and pass the values gathered earlier*/
                /* This method returns a JFreeChart object back to us */
                /* We specify the chart title, X-Axis Title and Y-Axis heading in this method */
                JFreeChart my2DChart=ChartFactory.createBarChart("Mark Details","Subject","Marks",mychartData,PlotOrientation.VERTICAL,false,true,false);
                /* 2D Chart created till this point, this can be moved into iText PDF */
                int width=640; /* Width of our chart */
                int height=480; /* Height of our chart */
                Document document=new Document(new Rectangle(width,height)); /* Create a New Document Object */
                /* Create PDF Writer Object that will write the chart information for us */
                PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream("Insert_2d_Chart_in_PDF.pdf"));
                /* Open the Document Object for adding contents */
                document.open();
                /* Get Direct Content of the PDF document for writing */
                PdfContentByte Add_Chart_Content= writer.getDirectContent();
                /* Create a template using the PdfContent Byte object */
                PdfTemplate template_Chart_Holder=Add_Chart_Content.createTemplate(width,height);
                /* Create a 2D graphics object to write on the template */
                Graphics2D Graphics_Chart=template_Chart_Holder.createGraphics(width,height,new DefaultFontMapper());
                /* Create a Rectangle object */
                Rectangle2D Chart_Region=new Rectangle2D.Double(0,0,540,380);
                /* Invoke the draw method passing the Graphics and Rectangle 2D object to draw the chart */
                my2DChart.draw(Graphics_Chart,Chart_Region);            
                Graphics_Chart.dispose();
                /* Add template to PdfContentByte and then to the PDF document */
                Add_Chart_Content.addTemplate(template_Chart_Holder,0,0);
                /* Close the Document, writer will create a beautiful 2D chart inside the PDF document */
                document.close();
        }
        catch (Exception i)
        {
            System.out.println(i);
        }
    }
}
When you run this code example, you will get a nice bar chart inside your PDF document. A screenshot of this bar chart is shown below;
2D Bar Chart Example - iText JFreeChart
2D bar Chart created inside a PDF document using iText and JFreeChart
In the upcoming tutorials we will discuss more options provided by JFreeChart to create different type of charts in a PDF file using iText.

6 comments:

  1. Hi,

    Excellent Example I got the following error when I tried this

    com.itextpdf.text.exceptions.IllegalPdfSyntaxException: Unbalanced save/restore state operators.

    What do you think could be the reason

    Sripradha

    ReplyDelete
  2. Hi,

    I'm getting the following exception

    Exception in thread "main" java.lang.NoClassDefFoundError: org/jfree/util/PublicCloneable
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at PDFChartExample.main(PDFChartExample.java:14)
    Caused by: java.lang.ClassNotFoundException: org.jfree.util.PublicCloneable
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    ... 13 more

    Please help me..

    Mithun

    ReplyDelete
  3. @Sripradha,

    You are getting this exception because, you would not have invoked the dispose() method of java.awt.Graphics2D. Try calling the dispose() method and let us know.

    ReplyDelete
  4. @Mithun,

    As I specified in the post, you would need to have all the Jar files in your classpath to run this example. You are getting this exception as you are missing jcommon-1.0.16.jar file in your classpath.

    ReplyDelete
  5. I have added above code in jsp,but getting ERROR.....

    javax.servlet.ServletException: java.lang.NoClassDefFoundError: org/jfree/ui/Drawable
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:268)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:820)


    I have added jchart and jcommon jars,but still it gives error.

    Pls help me...

    ReplyDelete
  6. Exception in thread "main" java.lang.NoClassDefFoundError: org/jfree/util/PublicCloneable
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at org.jfree.data.category.DefaultCategoryDataset.(DefaultCategoryDataset.java:74)
    at com.melosys.testfiles.Productchart.createDataset(Productchart.java:82)
    at com.melosys.testfiles.Productchart.(Productchart.java:57)
    at com.melosys.testfiles.Productchart.main(Productchart.java:182)
    Caused by: java.lang.ClassNotFoundException: org.jfree.util.PublicCloneable
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 16 more

    ReplyDelete