5/14/10

Simple example of using iText and Jfreechart

Hi all,

This is a simple example using itext and jfreechart. You will need itext and jfreechart jar files for executing this example.


/**
 *
 * @author Raghu
 */
import com.lowagie.text.Document;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.FileOutputStream;
import org.jfree.chart.ChartFactory;


import org.jfree.chart.JFreeChart;






import org.jfree.data.general.DefaultPieDataset;


public class ItextAndChart {


// this method is used to create a simple pie chart using Jfreechart.
    public static JFreeChart generateChart() {
        DefaultPieDataset pieDataset = new DefaultPieDataset();
        pieDataset.setValue("One", new Integer(10));
        pieDataset.setValue("Two", new Integer(20));
        pieDataset.setValue("Three", new Integer(30));
        pieDataset.setValue("Four", new Integer(10));
        pieDataset.setValue("Five", new Integer(20));
        pieDataset.setValue("Six", new Integer(10));
        JFreeChart chart = ChartFactory.createPieChart("Pie Chart using JFreeChart", pieDataset, true, true, true);
        return chart;
    }


 // this method will create a pdf file along with a chart using itext and jfreechart.
    public static void charInPDF(JFreeChart chart,int width, int height, String fileName) {
        PdfWriter writer = null;
        Document document = new Document();
        try {
            writer = PdfWriter.getInstance(document, new FileOutputStream(
                    fileName));
            document.open();
            PdfContentByte contentByte = writer.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphics2d = template.createGraphics(width, height,
                    new DefaultFontMapper());
            Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width,
                    height);


            chart.draw(graphics2d, rectangle2d);


            graphics2d.dispose();
            contentByte.addTemplate(template, 0, 0);


        } catch (Exception e) {
            e.printStackTrace();
        }
        document.close();


    }
       public static void main(String[] args) {
        // TODO code application logic here
        


        ItextAndChart.charInPDF(ItextAndChart.generateChart(), 500, 500, "testpdf.pdf");
    }
}

No comments:

Post a Comment

Popular Posts