Saving JFreeChart as SVG vector images using Batik

JFreeChart is a free Java class library for generating charts. After creating a nice graph you might want to use it in a report. JFreeChart already allows you to save your graph to PNG and JPEG, but obviously you would rather have it in vector format, so the chart can be scaled to any size.

Just to save you the effort here's the Java code to export your chart to SVG (Scalable Vector Graphics) format.

First download the Batik SVG toolkit. Batik comes in a large number of jar files. You only need the following ones:

Create a JFreeChart as you normally do. Use the following function to save the graph to a file.
	 * Exports a JFreeChart to a SVG file.
	 * @param chart JFreeChart to export
	 * @param bounds the dimensions of the viewport
	 * @param svgFile the output file.
	 * @throws IOException if writing the svgFile fails.
	void exportChartAsSVG(JFreeChart chart, Rectangle bounds, File svgFile) throws IOException {
        // Get a DOMImplementation and create an XML document
        DOMImplementation domImpl =
        Document document = domImpl.createDocument(null, "svg", null);

        // Create an instance of the SVG Generator
        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

        // draw the chart in the SVG generator
        chart.draw(svgGenerator, bounds);

        // Write svg file
        OutputStream outputStream = new FileOutputStream(svgFile);
        Writer out = new OutputStreamWriter(outputStream, "UTF-8");, true /* use css */);						

One small tip if you want to use the SVG in your LaTeX document: You can convert the SVG file to EPS using Inkscape.

If you don't know how to use this code, you can also download a zip file containing a runnable version of the code (including the required batik and jfreechart libraries) here (compiled with Java SDK 1.5).