import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGeneratorContext;
import org.apache.batik.svggen.SVGGraphics2D;
import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;
import org.scilab.forge.jlatexmath.TeXFormula.TeXIconBuilder;
import org.scilab.forge.jlatexmath.TeXIcon;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
public class jlatexmath {
private final static String SVG_NS = "http://www.w3.org/2000/svg";
private final static String SVG_ROOT = "svg";
private final static float FONT_SIZE = 20;
private String renderLatex(String source) {
DOMImplementation DOMImpl = GenericDOMImplementation.getDOMImplementation();
Document document = DOMImpl.createDocument(SVG_NS, SVG_ROOT, null);
SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
SVGGraphics2D g = new SVGGraphics2D(ctx, true);
TeXFormula formula = new TeXFormula(source);
TeXFormula.TeXIconBuilder builder = formula.new TeXIconBuilder();
builder.setStyle(TeXConstants.STYLE_DISPLAY);
builder.setSize(FONT_SIZE);
TeXIcon icon = builder.build();
icon.setInsets(new Insets(0, 0, 0, 0));
g.setSVGCanvasSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));
g.setColor(new Color(0, 0, 0, 0));
g.fillRect(0, 0, icon.getIconWidth(), icon.getIconHeight());
icon.paintIcon(null, g, 0, 0);
StringWriter out = new StringWriter();
try {
g.stream(out, true);
out.flush();
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return out.toString();
}
public static void main(String[] args) throws IOException {
String latex = "(a+b)^{2}=a^{2}+2ab+b^{2}";
jlatexmath j = new jlatexmath();
String svgString = j.renderLatex(latex);
Files.write(Paths.get("D:/latex.svg"), svgString.getBytes());
System.out.println(svgString);
}
}
I am using jlatexmath-1.0.7 for generating latex images that works fine. but i need svg out so i use apache batik for the same and above code is generating ~17KB file. Some online tool like codecogs.com generating svg of ~7KB for same latex input. how can i remove un-necessary information from svg in java so it can generate less size image.
Have you tried passing false
in the constructor SVGGraphics2D(ctx, true)?
It uses text rather than graphics and so the resulting file size is also smaller.