DEV Community


Posted on • Updated on

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

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.

Enter fullscreen mode Exit fullscreen mode

Sample Code

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);
        officeMath1.fromLatexMathCode("$f(x, y) = 100 * \\lbrace[(x + y) * 3] - 5\\rbrace$");

        Paragraph paragraph2 = section.addParagraph();
        OfficeMath officeMath2 = new OfficeMath(doc);

        //Add another paragraph and then add MathMLCode to it
        Paragraph paragraph3 = section.addParagraph();
        OfficeMath officeMath3 = new OfficeMath(doc);
        officeMath3.fromMathMLCode("<mml:math xmlns:mml=\"\" xmlns:m=\"\"><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);
Enter fullscreen mode Exit fullscreen mode

The output Word document


Learn more about the free API:

Discussion (0)