The heading said parsing and google lead me to here. Thus, I also include an example of JLaTeXMath
and hints on other parsers.
SnuggleTeX
SnuggleTeX BSD License - has a good parser, too.
/* Create vanilla SnuggleEngine and new SnuggleSession */
SnuggleEngine engine = new SnuggleEngine();
SnuggleSession session = engine.createSession();
/* Parse some very basic Math Mode input */
SnuggleInput input = new SnuggleInput("$$ x+2=3 $$");
session.parseInput(input);
/* Convert the results to an XML String, which in this case will
* be a single MathML <math>...</math> element. */
String xmlString = session.buildXMLString();
Source: https://github.com/davemckain/snuggletex/blob/development_1_2_x/snuggletex-core/src/main/java/uk/ac/ed/ph/snuggletex/samples/MinimalExample.java.
It can even do \newcommand
:
\newcommand{\test}[1]{Hello #1}\test{There} more text afterwards
Hello There more text afterwards
Source: https://github.com/davemckain/snuggletex/blob/development_1_2_x/snuggletex-core/src/test/resources/line-tests.txt
JLaTeXMath
I would use JLaTeXMath if GPL license is OK:
"JLaTeXMath is the best Java library to display LaTeX code."
import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;
public class Example5 {
public static void main(String[] args) {
String latex = "\\begin{array}{|c|l|||r|c|}";
latex += "\\hline";
latex += "\\text{Matrix}&\\multicolumn{2}{|c|}{\\text{Multicolumns}}&\\text{Font sizes commands}\\cr";
latex += "\\hline";
latex += "\\begin{pmatrix}\\alpha_{11}&\\cdots&\\alpha_{1n}\\cr\\hdotsfor{3}\\cr\\alpha_{n1}&\\cdots&\\alpha_{nn}\\end{pmatrix}&\\Large \\text{Large Right}&\\small \\text{small Left}&\\tiny \\text{tiny Tiny}\\cr";
latex += "\\hline";
latex += "\\multicolumn{4}{|c|}{\\Huge \\text{Huge Multicolumns}}\\cr";
latex += "\\hline";
latex += "\\end{array}";
TeXFormula formula = new TeXFormula(latex);
formula.createPNG(TeXConstants.STYLE_DISPLAY, 20, "target/Example5.png", Color.white, Color.black);
}
}
Source for TeXFormula: https://github.com/opencollab/jlatexmath/blob/7995ce52b2699c9a3a8428a94c1f3762cdcb0284/jlatexmath/src/main/java/org/scilab/forge/jlatexmath/TeXFormula.java#L244
Other solutions
(partially based on https://tex.stackexchange.com/q/41609/9075)