How to create SVG using JFreeChart?

The JFreeChart website says the library can output a chart in vector format.

From the JFreeChart website:

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

But how can I output in SVG format?

There is a way to use the Apache Batik library, but from the above statement, I would have thought that JFreeChart could do this without Batik.

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

+5
source share
3 answers

, JFreeChart SVG , Batik JFreeSVG, . :

: Object Refinery Limited; .

+7
+1

, jFreeChart SVG 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 SVG elements to a PDF file, you can use the following code to generate byte [] from 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();
}
0
source

All Articles