export chart as PDF,SVG or EPS

A discussion forum for JFreeChart (a 2D chart library for the Java platform).
Locked
thabe
Posts: 4
Joined: Tue Jun 06, 2006 12:40 pm

export chart as PDF,SVG or EPS

Post by thabe » Tue Jun 06, 2006 12:46 pm

I have a small problem with the export features of JFreeChart.

The frontpage states that JFreeChart can export charts to PNG, JPEG, PDF, SVG and EPS format.
support for many output types, including Swing components, image files (including PNG and JPEG), and vector graphics file formats (including PDF, EPS and SVG);
The PNG and JPEG part I figured out, but I can't find a way to export my chart to PDF or SVG.

My question:
How do I export a chart from JFreeChart to PDF, EPS or SVG? Can someone give some sample code how to do it?

thanks in advance

pmarsollier
Posts: 49
Joined: Thu Jul 08, 2004 8:54 am
Location: France

Post by pmarsollier » Tue Jun 06, 2006 2:37 pm

a generic way to export your chart using ImageIO supported graphic format : (sample as PNG)

public void writeAsPNG( JFreeChart chart, OutputStream out, int width, int height )
{
try
{
BufferedImage chartImage = chart.createBufferedImage( width, height, null);
ImageIO.write( chartImage, "png", out );
}
catch (Exception e)
{
LOG.error( e );
}
}


a sample to create PDF using iText (http://www.lowagie.com/iText)

public void writeAsPDF( JFreeChart chart, OutputStream out, int width, int height )
{
try
{
Rectangle pagesize = new Rectangle( width, height );
Document document = new Document( pagesize, 50, 50, 50, 50 );
PdfWriter writer = PdfWriter.getInstance( document, out );
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate( width, height );
Graphics2D g2 = tp.createGraphics( width, height, new DefaultFontMapper() );
Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height );
chart.draw(g2, r2D);
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
}
catch (Exception e)
{
LOG.error( e );
}
}

thabe
Posts: 4
Joined: Tue Jun 06, 2006 12:40 pm

Post by thabe » Tue Jun 06, 2006 3:10 pm

Thanks a lot.

I tried the pdf code and it works like a charm. Now I'm going to test the ImageIO to export jpeg, png and tiff.

For the SVG export I'm using Batik http://xmlgraphics.apache.org/#batik.

Now only the EPS export will give me some headaches but I think Jibble (http://www.jibble.org/epsgraphics/) will do what I want.

thabe
Posts: 4
Joined: Tue Jun 06, 2006 12:40 pm

Post by thabe » Tue Jun 06, 2006 4:20 pm

On second thought, Jibble is a commercial package.

But I found a free package with all kind of graphic export stuff: VectorGraphics http://java.freehep.org/vectorgraphics/index.html

david.gilbert
JFreeChart Project Leader
Posts: 11734
Joined: Fri Mar 14, 2003 10:29 am
antibot: No, of course not.
Contact:

Post by david.gilbert » Wed Jun 07, 2006 8:52 am

thabe wrote:On second thought, Jibble is a commercial package.
The EpsGraphics2D class at jibble.org is GPLed, and you can purchase a commercial licence if you want to incoporate the code into non-free software.

I've used this class, and it works well for most applications.
David Gilbert
JFreeChart Project Leader

:idea: Read my blog
:idea: Support JFree via the Github sponsorship program

pmarsollier
Posts: 49
Joined: Thu Jul 08, 2004 8:54 am
Location: France

Post by pmarsollier » Wed Jun 07, 2006 10:57 am

nice of you to post sample when you achieve to make it work ! :D

thabe
Posts: 4
Joined: Tue Jun 06, 2006 12:40 pm

Post by thabe » Wed Jun 07, 2006 12:25 pm

Some code snippets for the various export formats:

SVG export using Batik:

Code: Select all

 public void export(File name, JFreeChart chart, int x, int y) {
//      Get a DOMImplementation
        DOMImplementation domImpl =
            SVGDOMImplementation.getDOMImplementation();
        Document document = domImpl.createDocument(null, "svg", null);
        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
        chart.draw(svgGenerator,new Rectangle(x,y));
              

       boolean useCSS = true; // we want to use CSS style attribute
        
            Writer out = new OutputStreamWriter(new    FileOutputStream(name), "UTF-8");
            svgGenerator.stream(out, useCSS);
            out.close();
       

    }
PNG output using build-in support from JFreeChart:

Code: Select all

 public void export(File name, JFreeChart chart, int x, int y) {
            ChartUtilities.saveChartAsPNG(name,chart,x,y);
    }
JPEG output using build-in support from JFreeChart:

Code: Select all

 public void export(File name, JFreeChart chart, int x, int y) {
            ChartUtilities.saveChartAsJPEG(name,chart,x,y);
    }
PDF output using the code from earlier this thread:

Code: Select all

public void export(File name, JFreeChart chart, int x, int y) {
        Rectangle pagesize = new Rectangle( x, y );
        Document document = new Document( pagesize, 50, 50, 50, 50 );
            PdfWriter writer = PdfWriter.getInstance( document, new FileOutputStream(name) );
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate( x, y );
            Graphics2D g2 = tp.createGraphics( x, y, new DefaultFontMapper() );
            chart.draw(g2, new Rectangle(x,y));
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
            document.close(); 
  }
EPS export using EpsGraphics2D

Code: Select all

public void export(File name, JFreeChart chart, int x, int y) {
        Graphics2D g = new EpsGraphics2D();
        chart.draw(g,new Rectangle(x,y));
         Writer out=new FileWriter(name);
           out.write(g.toString());
           out.close();
    }

parthadebnath
Posts: 3
Joined: Mon Jun 12, 2006 2:04 pm

PDF

Post by parthadebnath » Mon Jun 12, 2006 2:10 pm

Hi friend.. I have tried the method suggested by this thread for creating pdf files from a JFreeChart..
:D
But the problem I am facing is that when I try to append the chart on to an existing pdf, its not working... :cry:
I see that the size of the file is getting increased, which suggests that the chart may be getting appended but I cant see the chart in the document....
Can any one help me... Its very urgent...
Thanks in advance.. Partha

hookumsnivy
Posts: 13
Joined: Mon Aug 14, 2006 9:14 pm

Post by hookumsnivy » Mon Aug 14, 2006 9:17 pm

When exporting to SVG don't forget this VERY important line:

Code: Select all

svgGenerator.setSVGCanvasSize(new Dimension(width, height));
Otherwise renderers will not know the size of the image. It will be drawn to the correct rectangle, but the image will not have a correct default size.

maheshkadtan
Posts: 4
Joined: Thu Jul 24, 2014 6:27 pm
antibot: No, of course not.

Re: export chart as PDF,SVG or EPS

Post by maheshkadtan » Thu Jul 24, 2014 6:41 pm

hi can any one properly elaborate with step by step how to export chart as PDF because i am very new jfreechart actually im fresher and my TL force me to do that so please help me i follow u r above code but i still doesn't get it ...



thanks in advance

maheshkadtan
Posts: 4
Joined: Thu Jul 24, 2014 6:27 pm
antibot: No, of course not.

Re: can u please explain step by step because im fresher

Post by maheshkadtan » Thu Jul 24, 2014 6:43 pm

pmarsollier wrote:a generic way to export your chart using ImageIO supported graphic format : (sample as PNG)

public void writeAsPNG( JFreeChart chart, OutputStream out, int width, int height )
{
try
{
BufferedImage chartImage = chart.createBufferedImage( width, height, null);
ImageIO.write( chartImage, "png", out );
}
catch (Exception e)
{
LOG.error( e );
}
}

Re: can u please explain step by step because im fresher
a sample to create PDF using iText (http://www.lowagie.com/iText)

public void writeAsPDF( JFreeChart chart, OutputStream out, int width, int height )
{
try
{
Rectangle pagesize = new Rectangle( width, height );
Document document = new Document( pagesize, 50, 50, 50, 50 );
PdfWriter writer = PdfWriter.getInstance( document, out );
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate( width, height );
Graphics2D g2 = tp.createGraphics( width, height, new DefaultFontMapper() );
Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height );
chart.draw(g2, r2D);
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
}
catch (Exception e)
{
LOG.error( e );
}
}

david.gilbert
JFreeChart Project Leader
Posts: 11734
Joined: Fri Mar 14, 2003 10:29 am
antibot: No, of course not.
Contact:

Re: export chart as PDF,SVG or EPS

Post by david.gilbert » Thu Jul 24, 2014 6:57 pm

maheshkadtan wrote:hi can any one properly elaborate with step by step how to export chart as PDF because i am very new jfreechart actually im fresher and my TL force me to do that so please help me i follow u r above code but i still doesn't get it ...



thanks in advance
I developed OrsonPDF as a convenient lightweight library for exporting charts to PDF. The evaluation download includes several JFreeChart examples:

Code: Select all

/* =====================================================================
 * OrsonPDF : a fast, light-weight PDF library for the Java(tm) platform
 * =====================================================================
 * 
 * (C)opyright 2013, 2014, by Object Refinery Limited.  All rights reserved.
 *
 * Project Info:  http://www.object-refinery.com/orsonpdf/index.html
 * 
 */

package com.orsonpdf.demo;

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.StatisticalBarRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.statistics.DefaultStatisticalCategoryDataset;
import org.jfree.ui.TextAnchor;
import com.orsonpdf.PDFDocument;
import com.orsonpdf.PDFGraphics2D;
import com.orsonpdf.Page;

/**
 * A demo for PDF output of a bar chart.
 */
public class PDFBarChartDemo1 {

    /**
     * Creates a sample dataset.
     *
     * @return The dataset.
     */
    private static CategoryDataset createDataset() {
        DefaultStatisticalCategoryDataset dataset
            = new DefaultStatisticalCategoryDataset();
        dataset.add(10.0, 2.4, "Row 1", "Column 1");
        dataset.add(15.0, 4.4, "Row 1", "Column 2");
        dataset.add(13.0, 2.1, "Row 1", "Column 3");
        dataset.add(7.0, 1.3, "Row 1", "Column 4");
        dataset.add(22.0, 2.4, "Row 2", "Column 1");
        dataset.add(18.0, 4.4, "Row 2", "Column 2");
        dataset.add(28.0, 2.1, "Row 2", "Column 3");
        dataset.add(17.0, 1.3, "Row 2", "Column 4");
        return dataset;
    }

    /**
     * Creates a sample chart.
     *
     * @param dataset  a dataset.
     *
     * @return The chart.
     */
    private static JFreeChart createChart(CategoryDataset dataset) {

        // create the chart...
        JFreeChart chart = ChartFactory.createLineChart(
            "Statistical Bar Chart Demo 1", "Type", "Value", dataset, 
            PlotOrientation.VERTICAL, true, false, false);

        CategoryPlot plot = (CategoryPlot) chart.getPlot();

        // customise the range axis...
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        rangeAxis.setAutoRangeIncludesZero(false);

        // customise the renderer...
        StatisticalBarRenderer renderer = new StatisticalBarRenderer();
        renderer.setDrawBarOutline(false);
        renderer.setErrorIndicatorPaint(Color.black);
        renderer.setIncludeBaseInRange(false);
        plot.setRenderer(renderer);

        // ensure the current theme is applied to the renderer just added
        ChartUtilities.applyCurrentTheme(chart);

        renderer.setBaseItemLabelGenerator(
                new StandardCategoryItemLabelGenerator());
        renderer.setBaseItemLabelsVisible(true);
        renderer.setBaseItemLabelPaint(Color.yellow);
        renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
                ItemLabelAnchor.INSIDE6, TextAnchor.BOTTOM_CENTER));

        // set up gradient paints for series...
        GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue,
                0.0f, 0.0f, new Color(0, 0, 64));
        GradientPaint gp1 = new GradientPaint(0.0f, 0.0f, Color.green,
                0.0f, 0.0f, new Color(0, 64, 0));
        renderer.setSeriesPaint(0, gp0);
        renderer.setSeriesPaint(1, gp1);
        return chart;
    }
 
    /**
     * Starting point for the demo.
     * 
     * @param args  ignored.
     * 
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        JFreeChart chart = createChart(createDataset());
        PDFDocument pdfDoc = new PDFDocument();
        pdfDoc.setTitle("PDFBarChartDemo1");
        pdfDoc.setAuthor("Object Refinery Limited");
        Page page = pdfDoc.createPage(new Rectangle(612, 468));
        PDFGraphics2D g2 = page.getGraphics2D();
        chart.draw(g2, new Rectangle(0, 0, 612, 468));
        pdfDoc.writeToFile(new File("PDFBarChartDemo1.pdf"));
    }

}
You can, of course, still use iText if you prefer.
David Gilbert
JFreeChart Project Leader

:idea: Read my blog
:idea: Support JFree via the Github sponsorship program

maheshkadtan
Posts: 4
Joined: Thu Jul 24, 2014 6:27 pm
antibot: No, of course not.

Re: export chart as PDF,SVG or EPS

Post by maheshkadtan » Mon Jul 28, 2014 7:33 am

hi buddy ur code work super thanks for u r help, but OrsonPdf.jar has a water mark because i download orsonpdf.jar as a trial version can u help me again because my company doesn't ready to buy orsonpdf.jar so do u have some another alternative

maheshkadtan
Posts: 4
Joined: Thu Jul 24, 2014 6:27 pm
antibot: No, of course not.

Re: export chart as PDF,SVG or EPS

Post by maheshkadtan » Mon Jul 28, 2014 7:35 am

hi buddy ur code work super thanks for u r help, but OrsonPdf.jar has a water mark because i download orsonpdf.jar as a trial version can u help me again because my company doesn't ready to buy orsonpdf.jar so do u have some another alternative ..




thanks in advance...

david.gilbert
JFreeChart Project Leader
Posts: 11734
Joined: Fri Mar 14, 2003 10:29 am
antibot: No, of course not.
Contact:

Re: export chart as PDF,SVG or EPS

Post by david.gilbert » Mon Jul 28, 2014 8:44 am

maheshkadtan wrote:so do u have some another alternative ..
Yes. I'm going to go work on something else to pay my bills.
David Gilbert
JFreeChart Project Leader

:idea: Read my blog
:idea: Support JFree via the Github sponsorship program

Locked