Java - Add or Read Math Equations in Word Documents
Tags: java, word, equations, formulas
Published: 2023-04-26 03:44:22

An equation is a mathematical formula or expression that represents a particular concept, principle, or calculation. It is an essential element in scientific papers and mathematics books. By incorporating equations in your document, you can effectively communicate complex mathematical concepts and calculations to your readers in a clear and professional manner. In this article, we will describe how to **add or read math equations in Word documents in Java** using [Spire.Doc for Java](https://www.e-iceblue.com/Introduce/doc-for-java.html) library.

- [Add Math Equations to Word Documents in Java](#add-math-equations-to-word-documents-in-java)
- [Read Math Equations in Word Documents in Java](#read-math-equations-in-word-documents-in-java)

## Add Dependencies

Before coding, you need to add needed dependencies for including Spire.Doc for Java into your Java project. There are two ways to do that.

**Method 1:** If you are using maven, you can easily import the JAR file of Spire.Doc for Java into your application by adding the following code to your project’s pom.xml file.
```java
<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 </artifactId>
        <version>11.4.2</version>
    </dependency>
</dependencies>
```
**Method 2:** If you are not using maven, you can download Spire.Doc for Java from [this link](https://www.e-iceblue.com/Download/doc-for-java.html), extract the zip file and then import the Spire.Doc.jar file under the lib folder into your project as a dependency.

## Add Math Equations to Word Documents in Java
With Spire.Doc, you can easily create math equations by specifying their LateX code or MathML code using the **OfficeMath.fromLatexMathCode(String latexMathCode)** or **OfficeMath.fromMathMLCode(String mathMLCode)** method. After that, you can add the equations to specific paragraphs of your Word document using the **Paragraph.getItems().add(IDocumentObject entity)** method.

The following steps explain how to create and add math equations to a Word document:

- Put the LateX code into a **String** array.
- Put the MathML code into a **String** array.
- Initialize an instance of the **Document** class and load a Word document using the **Document.loadFromFile(String fileName)** method.
- Get a specific section using the **Document.getSections().get(int index)** method.
- Iterate through all the LateX code in the String array.
- Add a paragraph to the section using the **Section.addParagraph()** method.
- Initialize an instance of the **OfficeMath** class, then convert the current LateX code to a math equation using the **OfficeMath.fromLatexMathCode(String latexMathCode)** method.
- Add the math equation to the paragraph using the **Paragraph.getItems().add(IDocumentObject entity)** method.
- Iterate through all the MathML code in the string array.
- Add a paragraph to the section using the **Section.addParagraph()** method.
- Initialize an instance of the **OfficeMath** class, then convert the current MathML code to a math equation using the **OfficeMath.fromMathMLCode(String mathMLCode)** method.
- Add the math equation to the paragraph using the **Paragraph.getItems().add(IDocumentObject entity)** method.
- Save the result document using the **Document.saveToFile(String filename, FileFormat fileFormat)** method.
```java
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.omath.OfficeMath;

public class AddMathEquations {
    public static void main(String[] args) {
        //Put the LateX code into a String array
        String[] latexMathCode = {
                "\\left(a+\\frac{b}{c}\\right)",
                "\\rect{\\frac{a}{b}}",
                "\\frac{a}{b+c}",
                "\\sqrt[5]{a^2}",
        };

        //Put the MathML code into a String array
        String[] mathMLCode = {
                "<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>",
                "<mml:math xmlns:mml=\"http://www.w3.org/1998/Math/MathML\" xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\"><mml:mn>2</mml:mn><mml:mi>α</mml:mi><mml:mo>-</mml:mo><mml:mi>s</mml:mi><mml:mi>i</mml:mi><mml:mi>n</mml:mi><mml:mi>y</mml:mi><mml:mo>+</mml:mo><mml:mi>x</mml:mi></mml:math>",
                "<mml:math xmlns:mml=\"http://www.w3.org/1998/Math/MathML\" xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\"><mml:mfrac><mml:mrow><mml:mn>1</mml:mn></mml:mrow><mml:mrow><mml:mn>2</mml:mn><mml:mo>+</mml:mo><mml:mi>x</mml:mi></mml:mrow></mml:mfrac></mml:math>",
                "<mml:math xmlns:mml=\"http://www.w3.org/1998/Math/MathML\" xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\"><mml:mfenced><mml:mrow><mml:mn>1</mml:mn><mml:mo>+</mml:mo><mml:mo>|</mml:mo><mml:mi>x</mml:mi><mml:mo>-</mml:mo><mml:mfenced open=\"[\" close=\"]\"><mml:mrow><mml:mi>a</mml:mi><mml:mo>-</mml:mo><mml:mi>b</mml:mi></mml:mrow></mml:mfenced><mml:mo>|</mml:mo></mml:mrow></mml:mfenced></mml:math>",
        };

        //Initialize an instance of the Document class.
        Document doc = new Document();
        //Load a Word document
        doc.loadFromFile("Sample.docx");

        //Get the first section of the document
        Section section = doc.getSections().get(0);

        Paragraph paragraph = null;
        OfficeMath officeMath;

        //Add math equations to the section by specifying their LaTeX code
        for (int i = 0; i < latexMathCode.length; i++) {
            paragraph = section.addParagraph();
            officeMath = new OfficeMath(doc);
            officeMath.fromLatexMathCode(latexMathCode[i]);
            paragraph.getItems().add(officeMath);
        }

        //Add math equations to the section by specifying their MathML code
        for (int i = 0; i < mathMLCode.length; i++) {
            paragraph = section.addParagraph();
            officeMath = new OfficeMath(doc);
            officeMath.fromMathMLCode(mathMLCode[i]);
            paragraph.getItems().add(officeMath);
        }

        //Save the result document
        String result = "AddMathEquations.docx";
        doc.saveToFile(result, FileFormat.Docx_2013);
    }
}
```

![Add math equations or formulas to Word Documents in Java](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4j85pozxge4d6x6fs5qf.png) 

## Read Math Equations in Word Documents in Java
You can read the math equations in a Word document back to MathML code by iterating through the elements in the document, then finding the elements that are of the **OfficeMath** type and converting them to MathML code using the **OfficeMath.toMathMLCode()** method.

The following steps explain how to read the math equations in a Word document back to MathML code:

- Initialize an instance of the **Document** class and load a Word document using the **Document.loadFromFile(String fileName)** method.
- Initialize an instance of the **StringBuilder** class.
- Iterate through all the sections in the document.
- Iterate through all the paragraphs in each section.
- Iterate through all the child objects in each paragraph.
- Check if the objects are of the **OfficeMath** type.
- If the result is true, typecast the objects to OfficeMath type, then convert them to MathML code using the **OfficeMath.toMathMLCode()** method and append the result to the **StringBuilder** instance.
- Write the content of the **StringBuilder** instance into a TXT file.
```java
import com.spire.doc.*;
import com.spire.doc.fields.omath.OfficeMath;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class ReadMathEquations {
    public static void main(String[] args) {        
        //Initialize an instance of the Document class
        Document doc = new Document();
        //Load a Word document
        doc.loadFromFile("AddMathEquations.docx");

        //Initialize an instance of the StringBuilder class
        StringBuilder stringBuilder = new StringBuilder();

        //Iterate through all the sections in the document
        for(int i = 0; i < doc.getSections().getCount(); i++){
            //Iterate through all the paragraphs in each section
            for(int j = 0; j < doc.getSections().get(i).getParagraphs().getCount(); j++){
                //Iterate through all the child objects in each paragraph
                for(int k = 0;k < doc.getSections().get(i).getParagraphs().get(j).getChildObjects().getCount(); k++){
                    DocumentObject obj =doc.getSections().get(i).getParagraphs().get(j).getChildObjects().get(k);
                    //Check if the objects are of OfficeMath type
                    if (obj instanceof OfficeMath) {
                        OfficeMath math=(OfficeMath)doc.getSections().get(i).getParagraphs().get(j).getChildObjects().get(k);
                        //Read the math equations back to MathML code and append the result to the StringBuilder
                        stringBuilder.append(math.toMathMLCode()+"\n");
                    }
                }
            }
        }
        
        //Write the content of the StringBuilder into a TXT file
        File file = new File("ReadMathEquations.txt");
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            writer.append(stringBuilder);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }        
    }
}
```

![Read Math Equations or Formulas in Word Document in Java](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vqrsy0fugwll6q47ih57.png)