maven依赖:
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-transcoder</artifactId>
<version>1.8</version>
</dependency>
代码:
private String transfromSvgString(String latex) throws IOException {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
String svgNS = "http://www.w3.org/2000/svg";
org.w3c.dom.Document document = domImpl.createDocument(svgNS, "svg", null);
SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
SVGGraphics2D g2 = new SVGGraphics2D(ctx, true);
DefaultTeXFont.registerAlphabet(new CyrillicRegistration());
DefaultTeXFont.registerAlphabet(new GreekRegistration());
TeXFormula formula = null;
try {
formula = new TeXFormula(latex);
} catch (Exception e) {
System.err.println(latex);
}
TeXIcon icon = null;
try {
icon = formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, 20);
} catch (Exception e) {
System.err.println(latex);
}
icon.setInsets(new Insets(0, 0, 0, 0));
g2.setSVGCanvasSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));
g2.setColor(Color.white);
g2.fillRect(0, 0, icon.getIconWidth(), icon.getIconHeight());
JLabel jl = new JLabel();
jl.setForeground(new Color(0, 0, 0));
icon.paintIcon(jl, g2, 0, 0);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(outputStream, "UTF-8");
g2.stream(writer, true);
return outputStream.toString();
}