6
votes

On the JFreeChart web site it says that the library can output the chart in vector format.

From the JFreeChart site:

  • support for many output types, including Swing components, image files (including PNG and JPEG), and vector graphics file formats (including PDF, EPS and SVG);

But how can I actually output in SVG format?

There is a way using the Apache Batik library, but from the statement above I would think JFreeChart can do it without Batik.

I could figure out the output for PNG and JPG in the ChartUtilities class, but there seems to be no class for vector graphics output.

3
There is a thread about this here: jfree.org/phpBB2/viewtopic.php?f=3&t=24365assylias
@assylias That link is dead by now, do you recall what the conclusion of the thread was?Omnibyte

3 Answers

12
votes

No, JFreeChart supports SVG in the sense that it can be used in conjunction with Batik or JFreeSVG, which are required. Related resources include these:

Disclaimer: Not affiliated with Object Refinery Limited; just a satisfied customer and very minor contributor.

2
votes

To just make it simple for other readers, the following code converts a jFreeChart to a SVG by using jFreeSVG:

import org.jfree.graphics2d.svg.SVGGraphics2D;
import org.jfree.chart.JFreeChart;
import java.awt.geom.Rectangle2D;

public String getSvgXML(){
    final int widthOfSVG = 200;
    final int heightOfSVG = 200;
    final SVGGraphics2D svg2d = new SVGGraphics2D(widthOfSVG, heightOfSVG);

    final JFreeChart chart = createYourChart();
    chart.draw(svg2d,new Rectangle2D.Double(0, 0, widthOfSVG, heightOfSVG));

    final String svgElement = svg2d.getSVGElement();
    return svgElement;
}

To write the SVG elements to a PDF file, you can use the following code to generate a byte[] out of your SVG and then write it to a file. For this case I use apache batic :

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import org.apache.batik.transcoder.Transcoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.fop.svg.PDFTranscoder;

public byte[] getSVGInPDF(){ 
     final Transcoder transcoder = new PDFTranscoder();
     final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
     final TranscoderInput transcoderInput = new TranscoderInput(
     new ByteArrayInputStream(getSvgXML().getBytes()));
     final TranscoderOutput transcoderOutput = new TranscoderOutput(outputStream);
     transcoder.transcode(transcoderInput, transcoderOutput);
     return outputStream.toByteArray();
}
1
votes

In addition to trashgod 's answer

It seems that JFreeSVG is far more efficient than Batik : http://www.object-refinery.com/blog/blog-20140423.html