JFreeSVG
| Language | Java (Java 11+) |
|---|---|
| License | GPL-3.0 (copyleft: your program must be GPL-compatible to distribute it) |
| Repository | github.com/jfree/jfreesvg |
| Documentation | jfree.org/jfreesvg, Javadoc |
| Depends on | nothing |
| Read / write | no / yes (generates SVG from Graphics2D calls) |
JFreeSVG provides SVGGraphics2D, an implementation of java.awt.Graphics2D that turns drawing calls into SVG elements. Any code that draws with Java2D (charts, diagrams, reports) can produce SVG by drawing on it instead of on an image. It’s a small single JAR, with no dependencies, and faster than Batik’s SVGGraphics2D. It’s often used with JFreeChart.
The license is GPL-3.0: if you distribute software that uses it, that software must be under a GPL-compatible license. For a permissively licensed alternative use Batik’s SVGGraphics2D.
Installation#
Maven:
XML
<dependency>
<groupId>org.jfree</groupId>
<artifactId>org.jfree.svg</artifactId>
<version>5.0.7</version>
</dependency>
Gradle: implementation("org.jfree:org.jfree.svg:5.0.7").
Basic usage: draw and save an SVG file#
Java
import org.jfree.svg.SVGGraphics2D;
import org.jfree.svg.SVGUtils;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.geom.Ellipse2D;
import java.io.File;
import java.io.IOException;
public class MakeSvg {
public static void main(String[] args) throws IOException {
SVGGraphics2D g = new SVGGraphics2D(300, 200);
g.setPaint(Color.WHITE);
g.fillRect(0, 0, 300, 200);
g.setPaint(Color.ORANGE);
g.fill(new Ellipse2D.Double(100, 50, 100, 100));
g.setPaint(Color.BLACK);
g.setStroke(new BasicStroke(2f));
g.draw(new Ellipse2D.Double(100, 50, 100, 100));
g.setFont(new Font("SansSerif", Font.BOLD, 18));
g.drawString("Hello, SVG", 105, 180);
SVGUtils.writeToSVG(new File("out.svg"), g.getSVGElement());
}
}
How to get the SVG as a string#
Java
String element = g.getSVGElement(); // <svg ...>...</svg>, for embedding in HTML
String document = g.getSVGDocument(); // with <?xml ?> declaration and DOCTYPE
String withId = g.getSVGElement("chart1"); // sets the id attribute of the root
How to write a compressed SVGZ file#
Java
SVGUtils.writeToSVG(new File("out.svgz"), g.getSVGElement(), true); // true = gzip
How to set the size in millimeters#
Java
import org.jfree.svg.SVGUnits;
SVGGraphics2D page = new SVGGraphics2D(210, 297, SVGUnits.MM); // A4
page.drawRect(10, 10, 190, 277);
How to export a JFreeChart chart to SVG#
Java
import org.jfree.chart.JFreeChart;
import java.awt.Rectangle;
JFreeChart chart = /* create your chart */;
SVGGraphics2D g = new SVGGraphics2D(600, 400);
chart.draw(g, new Rectangle(0, 0, 600, 400));
SVGUtils.writeToSVG(new File("chart.svg"), g.getSVGElement());
Tips#
SVGUtils.writeToHTML(file, title, svgElement)writes an HTML page with the SVG inline.- Gradients, clipping, transforms and images (as embedded PNG data) are supported; text is written as
<text>elements by default, so viewers need the same fonts.