在 Java 中渲染 LaTeX

Sheeraz Gul 2024年2月15日
在 Java 中渲染 LaTeX

本教程将演示如何在 Java 中执行 TeX 并获取输出。

在 Java 中使用 JLaTeXMath 渲染 LaTeX

jlatexmath 作为 Eclipse 或 IDE 中的 maven 项目导入,并使用示例并在 Java 中运行 LaTeX。确保 Maven 依赖项已安装在你的 IDE 中。

例子:

package org.scilab.forge.jlatexmath.examples.export;

import java.io.IOException;

// This Class is used to render the latex
public class JAVA_TEX {
  public static void main(String[] args) {
    String demo_latex = "\\begin{array}{|c|l|||r|c|}";
    demo_latex += "\\hline";
    demo_latex +=
        "\\text{Matrix}&\\multicolumn{2}{|c|}{\\text{Multicolumns}}&\\text{Font sizes commands}\\cr";
    demo_latex += "\\hline";
    demo_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";
    demo_latex += "\\hline";
    demo_latex += "\\multicolumn{4}{|c|}{\\Huge \\text{Huge Multicolumns}}\\cr";
    demo_latex += "\\hline";
    demo_latex += "\\end{array}";

    try {
      Convert.toSVG(demo_latex, "demo_latex.svg", false);
      Convert.toSVG(demo_latex, "demo_latex_shaped.svg", true);
      Convert.SVGTo("demo_latex.svg", "demo_latex.pdf", Convert.PDF);
      Convert.SVGTo("demo_latex_shaped.svg", "demo_latex_shaped.pdf", Convert.PDF);
      Convert.SVGTo("demo_latex.svg", "demo_latex.ps", Convert.PS);
      Convert.SVGTo("demo_latex.svg", "demo_latex.eps", Convert.EPS);
    } catch (IOException exception) {
      throw new RuntimeException(exception);
    }
  }
}

控制台输出:

transcoding target/demo_latex.svg
Mar 08, 2022 12:36:46 PM org.apache.fop.fonts.truetype.TTFFile guessVerticalMetricsFromGlyphBBox
WARNING: capHeight value could not be determined. The font may not work as expected.
Mar 08, 2022 12:36:46 PM org.apache.fop.fonts.truetype.TTFFile guessVerticalMetricsFromGlyphBBox
WARNING: xHeight value could not be determined. The font may not work as expected.
transcoding target/demo_latex_shaped.svg
transcoding target/demo_latex.svg
transcoding target/demo_latex.svg

上面的代码将执行 LaTeX 数组语法并生成 .ps.svg.pdf 格式的输出。

可能会出现一些警告,但可以忽略。

文件输出:

LaTeX 数组代码执行后生成的文件

.ps.svg.pdf 文件在下面具有相同的书面输出。

文件中的书面输出

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook