Insert Math Equation (Latex/MathML) and Symbols into Word in Java

·

2 min read

When compiling the mathematics test papers or making mechanical design drawings, you may often need to add some mathematical equations to the documents. This article will share how to add Latex Math equation and MathMLCode to a Word document using a free Java API.

Import JAR Dependency

Method 1: Download the free API (Free Spire.Doc for Java) and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.
Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
   <repository>
      <id>com.e-iceblue</id>
      <name>e-iceblue</name>
      <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
   </repository>
</repositories>
<dependencies>
   <dependency>
      <groupId>e-iceblue</groupId>
      <artifactId>spire.doc.free</artifactId>
      <version>5.2.0</version>
   </dependency>
</dependencies>

Sample Code

The OfficeMath.fromLatexMathCode() and OfficeMath.fromMathMLCode() methods allows you to add Latex Math equation and MathMLCode to a Word document. The complete sample code is shown as below.

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.omath.OfficeMath;

public class AddEquation {
    public static void main(String[] args) {
        //Create a Document instance
        Document doc = new Document();

        //Add a section
        Section section = doc.addSection();

        //Add 2 paragraphs and then add Latex Math code to them
        Paragraph paragraph1 = section.addParagraph();
        OfficeMath officeMath1 = new OfficeMath(doc);
        paragraph1.getItems().add(officeMath1);
        officeMath1.fromLatexMathCode("$f(x, y) = 100 * \\lbrace[(x + y) * 3] - 5\\rbrace$");

        Paragraph paragraph2 = section.addParagraph();
        OfficeMath officeMath2 = new OfficeMath(doc);
        paragraph2.getItems().add(officeMath2);
        officeMath2.fromLatexMathCode("$S=a_{1}^2+a_{2}^2+a_{3}^2$");

        //Add another paragraph and then add MathMLCode to it
        Paragraph paragraph3 = section.addParagraph();
        OfficeMath officeMath3 = new OfficeMath(doc);
        paragraph3.getItems().add(officeMath3);
        officeMath3.fromMathMLCode("<mml:math xmlns:mml=\"http://www.w3.org/1998/Math/MathML\" xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\"><mml:msup><mml:mrow><mml:mi>x</mml:mi></mml:mrow><mml:mrow><mml:mn>2</mml:mn></mml:mrow></mml:msup><mml:mo>+</mml:mo><mml:msqrt><mml:msup><mml:mrow><mml:mi>x</mml:mi></mml:mrow><mml:mrow><mml:mn>2</mml:mn></mml:mrow></mml:msup><mml:mo>+</mml:mo><mml:mn>1</mml:mn></mml:msqrt><mml:mo>+</mml:mo><mml:mn>1</mml:mn></mml:math>");

        //Save the document
        doc.saveToFile("addMathEquation.docx", FileFormat.Docx_2013);
        doc.dispose();
    }
}