在 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