Java: Insert Math Equations in Word

2023-11-06 03:38:00 Written by Koohji

Math equations are mathematical expressions commonly used in physics, engineering, computer science, and economics fields. When creating a professional Word document, you may sometimes need to include math equations to explain complex concepts, solve problems, or support specific arguments. In this article, you will learn how to insert math equations into Word documents in Java using Spire.Doc for Java.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<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>14.1.3</version>
    </dependency>
</dependencies>

Insert Math Equations into a Word Document in Java

Spire.Doc for Java allows generating math equations from LaTeX code and MathML code using OfficeMath.fromLatexMathCode(String latexMathCode) and OfficeMath.fromMathMLCode(String mathMLCode) methods. The following are the detailed steps.

  • Create two string arrays from LaTeX code and MathML code.
  • Create a Document instance and add a section to it using Document.addSection() method.
  • Iterate through each LaTeX code in the string array.
  • Create a math equation from the LaTeX code using OfficeMath.fromLatexMathCode() method.
  • Add a paragraph to the section, then add the math equation to the paragraph using Paragraph.getItems().add() method.
  • Iterate through each MathML code in the string array.
  • Create a math equation from the MathML code using OfficeMath.fromMathMLCode() method.
  • Add a paragraph to the section, then add the math equation to the paragraph using Paragraph.getItems().add() method.
  • Save the result document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.omath.*;

public class AddMathEquations {
    public static void main(String[] args){

        //Create a string array from LaTeX code
        String[] latexMathCode = {
                "x^{2}+\\sqrt{x^{2}+1}=2",
                "\\cos (2\\theta) = \\cos^2 \\theta - \\sin^2 \\theta",
                "k_{n+1} = n^2 + k_n^2 - k_{n-1}",
                "\\frac {\\frac {1}{x}+ \\frac {1}{y}}{y-z}",
                "\\int_0^ \\infty \\mathrm {e}^{-x} \\, \\mathrm {d}x",
                "\\forall x \\in X, \\quad \\exists y \\leq \\epsilon",
                "\\alpha, \\beta, \\gamma, \\Gamma, \\pi, \\Pi, \\phi, \\varphi, \\mu, \\Phi",
                "A_{m,n} = \\begin{pmatrix} a_{1,1} & a_{1,2} & \\cdots & a_{1,n} \\\\ a_{2,1} & a_{2,2} & \\cdots & a_{2,n} \\\\ \\vdots  & \\vdots  & \\ddots & \\vdots  \\\\ a_{m,1} & a_{m,2} & \\cdots & a_{m,n} \\end{pmatrix}",
        };

        //Create a string array from MathML code
        String[] mathMLCode = {
                "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>a</mi><mo>≠</mo><mn>0</mn></math>",
                "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>a</mi><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mi>b</mi><mi>x</mi><mo>+</mo><mi>c</mi><mo>=</mo><mn>0</mn></math>",
                "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>x</mi><mo>=</mo><mrow><mfrac><mrow><mo>−</mo><mi>b</mi><mo>±</mo><msqrt><msup><mi>b</mi><mn>2</mn></msup><mo>−</mo><mn>4</mn><mi>a</mi><mi>c</mi></msqrt></mrow><mrow><mn>2</mn><mi>a</mi></mrow></mfrac></mrow></math>",
        };

        //Create a Document instance
        Document doc = new Document();

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

        //Add a paragraph to the section
        Paragraph textPara = section.addParagraph();
        textPara.appendText("Creating Equations from LaTeX Code");
        textPara.applyStyle(BuiltinStyle.Heading_1);
        textPara.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //Iterate through each LaTeX code in the string array
        for (int i = 0; i < latexMathCode.length; i++)
        {
            //Create a math equation from the LaTeX code
            OfficeMath officeMath = new OfficeMath(doc);
            officeMath.fromLatexMathCode(latexMathCode[i]);
            
            //Add the math equation to the section
            Paragraph paragraph = section.addParagraph();
            paragraph.getItems().add(officeMath);
            section.addParagraph();
        }
        
        //Add a paragraph to the section
        textPara = section.addParagraph();
        textPara.appendText("Creating Equations from MathML Code");
        textPara.applyStyle(BuiltinStyle.Heading_1);
        textPara.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //Iterate through each MathML code in the string array
        for (int j = 0; j < mathMLCode.length; j++)
        {
            //Create a math equation from the MathML code
            OfficeMath officeMath = new OfficeMath(doc);
            officeMath.fromMathMLCode(mathMLCode[j]);
            
            //Add the math equation to the section
            Paragraph paragraph = section.addParagraph();
            paragraph.getItems().add(officeMath);
            section.addParagraph();
        }

        //Save the result document
        doc.saveToFile("AddMathEquations.docx", FileFormat.Docx_2016);
        doc.dispose();
    }
}

Java: Insert Math Equations in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Create a Multi-Level List in PDF in Java

2021-05-17 02:35:28 Written by Koohji

This article shows you how to create a multi-level list in a PDF document using Spire.PDF for Java.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfNumberStyle;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.PdfPageSize;
import com.spire.pdf.graphics.*;
import com.spire.pdf.lists.PdfListItem;
import com.spire.pdf.lists.PdfOrderedMarker;
import com.spire.pdf.lists.PdfSortedList;

import java.awt.*;
import java.awt.geom.Point2D;

public class CreateMultiLevelList {

    public static void main(String[] args) {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Set the margin
        PdfMargins margin = new PdfMargins(60, 60, 40, 40);

        //Create one page
        PdfPageBase page = doc.getPages().add(PdfPageSize.A4, margin);

        //Specify the initial coordinate
        float x = 0;
        float y = 15;

        //Create two brushed
        PdfBrush blackBrush = PdfBrushes.getBlack();
        PdfBrush purpleBrush = PdfBrushes.getPurple();

        //Create two fonts
        PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new java.awt.Font("Times New Roman", Font.BOLD, 12));
        PdfTrueTypeFont listFont = new PdfTrueTypeFont(new java.awt.Font("Calibri Light", Font.PLAIN, 12));

        //Draw title
        String title = "XHTML Tutorials/FAQs:";
        page.getCanvas().drawString(title, titleFont, blackBrush, x, y);
        y = y + (float) titleFont.measureString(title).getHeight();
        y = y + 5;

        //Create two ordered makers, which are used to define the number style of sorted list
        PdfOrderedMarker marker1 = new PdfOrderedMarker(PdfNumberStyle.Upper_Roman, listFont);
        PdfOrderedMarker marker2 = new PdfOrderedMarker(PdfNumberStyle.Numeric, listFont);

        //Create a parent list
        String parentListContent = "Introduction To XHTML 1.0\n"
                + "Introduction To Tag and Attribute Syntax";
        PdfSortedList parentList = new PdfSortedList(parentListContent);
        parentList.setFont(listFont);
        parentList.setIndent(8);
        parentList.setBrush(purpleBrush);
        parentList.setMarker(marker1);

        //Create a sub list - "subList_1"
        String subListContent_1 = "What Is XHTML?\n"
                + "What Does an XHMTL Document Look Like?\n"
                + "What Is the Relation between XHTML and HTML?\n"
                + "What Is the Relation between XHTML and XML?";
        PdfSortedList subList_1 = new PdfSortedList(subListContent_1);
        subList_1.setIndent(16);
        subList_1.setFont(listFont);
        subList_1.setBrush(purpleBrush);
        subList_1.setMarker(marker2);

        //Create another sub list -"subList_2"
        String subListContent_2 = "What Is an XHTML Element?\n"
                + "How To Enter Comments into XHTML Documents?\n"
                + "How To Write the Opening Tag of an XHTML Element?";
        PdfSortedList subList_2 = new PdfSortedList(subListContent_2);
        subList_2.setIndent(16);
        subList_2.setFont(listFont);
        subList_2.setBrush(purpleBrush);
        subList_2.setMarker(marker2);

        //Set subList_1 as sub list of the first item of parent list
        PdfListItem item_1 = parentList.getItems().get(0);
        item_1.setSubList(subList_1);

        //Set subList_2 as sub list of the second item of parent list
        PdfListItem item_2 = parentList.getItems().get(1);
        item_2.setSubList(subList_2);

        //Draw parent list
        PdfTextLayout textLayout = new PdfTextLayout();
        textLayout.setBreak(PdfLayoutBreakType.Fit_Page);
        textLayout.setLayout(PdfLayoutType.Paginate);
        parentList.draw(page,new Point2D.Float(x,y),textLayout);

        //Save to file
        doc.saveToFile("MultiLevelList.pdf");
    }
}

Create a Multi-Level List in PDF in Java

This article will show you how to use Spire.Doc for Java to set the character spacing and paragraph spacing on Word.

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;

import java.awt.*;
import java.io.*;

public class setSpacing {
    public static void main(String[] args)throws IOException {
        //Load the sample document
        Document document= new Document("Sample1.docx");

        //Add a new paragraph and append the text
        Paragraph para = new Paragraph(document);
        TextRange textRange1 = para.appendText("Newly added paragraph and set the paragraph spacing and character spacing");
        textRange1.getCharacterFormat().setTextColor(Color.blue);
        textRange1.getCharacterFormat().setFontSize(14);

        //Set the spacing before and after paragraph
        para.getFormat().setBeforeAutoSpacing(false);
        para.getFormat().setBeforeSpacing(10);
        para.getFormat().setAfterAutoSpacing(false);
        para.getFormat().setAfterSpacing(10);

        //Set the character spacing
        for (DocumentObject object :(Iterable<DocumentObject>)para.getChildObjects())
        {
            TextRange textRange= (TextRange) object;
            textRange.getCharacterFormat().setCharacterSpacing(3f);
        }

        //Insert the paragraph
        document.getSections().get(0).getParagraphs().insert(2, para);

        //Save the document to file
        document.saveToFile("Result.docx", FileFormat.Docx);

    }
}

Output:

Java set the character spacing and paragraph spacing on Word document

page 31