How to create an SVG with JFreeChart?

Solution 1:

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:

  • The JFreeChart Developer Guide.

  • The JFreeChart forum.

  • Saving JFreeChart as SVG vector images using Batik.

  • JFreeSVG, which can "generate content in SVG format using the standard Java2D drawing API, Graphics2D." Demonstration programs may be found here, including this SVGBarChartDemo1 excerpt:

      JFreeChart chart = createChart(createDataset());
      SVGGraphics2D g2 = new SVGGraphics2D(600, 400);
      Rectangle r = new Rectangle(0, 0, 600, 400);
      chart.draw(g2, r);
      File f = new File("SVGBarChartDemo1.svg");
      SVGUtils.writeToSVG(f, g2.getSVGElement());
    

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

Solution 2:

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();
}

Solution 3:

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