Unlock the Power of Math: Effortlessly Embed Equations in Word Documents at Zero Cost!

Carina ThorneCarina Thorne
5 min read

Mathematical equations play a vital role in expressing mathematical concepts and relationships. They significantly enhance your capacity to communicate complex ideas and elevate the visual appeal and professionalism of academic papers, scientific reports, or any document involving mathematics. This article provides a detailed explanation on utilizing Free Spire.Doc for .NET to seamlessly insert math equations into Word documents.

Programming Environment

In this test, Free Spire.Doc for .NET is introduced into the program. The Spire.Doc.dll file can be referenced by:

Method 1: Download Free Spire.Doc for .NET locally, unzip it, and install it. After the installation is complete, find Spire.Doc.dll in the BIN folder under the installation path. Then open the "Solution Explorer" in Visual Studio, right-click "References", "Add Reference", and add a reference to the dll file in the BIN folder of the local path to the program.

Method 2: Install via NuGet. It can be installed by the following 2 methods:

(1) You can open the "Solution Explorer" in Visual Studio, right-click "References", "Manage NuGet Packages", then search for "Free Spire.Doc", and click "Install". Wait for the program installation to complete.

(2) Copy the following content to the PM console installation.

Install-Package FreeSpire.Doc -Version 11.6.0

Insert Math Equations into a Word Document in C# and VB.NET

  • 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(string latexMathCode) method.

  • Add a paragraph to the section, then add the math equation to the paragraph using Paragraph.Items.Add() method.

  • Iterate through each MathML code in the string array.

  • Create a math equation from the MathML code using OfficeMath.FromMathMLCode(string mathMLCode) method.

  • Add a paragraph to the section, then add the math equation to the paragraph using Paragraph.Items.Add() method.

  • Save the result document using Document.SaveToFile() method.

Full Code

C#

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields.OMath;

namespace AddMathEquations
{
    internal class Program
    {
        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.Heading1);
            textPara.Format.HorizontalAlignment = 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.Items.Add(officeMath);
                section.AddParagraph();
            }

            section.AddParagraph();

            //Add a paragraph to the section
            textPara = section.AddParagraph();
            textPara.AppendText("Creating Equations from MathML Code");
            textPara.ApplyStyle(BuiltinStyle.Heading1);
            textPara.Format.HorizontalAlignment = 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.Items.Add(officeMath);
                section.AddParagraph();
            }

            //Save the result document    
            doc.SaveToFile("AddMathEquations.docx", FileFormat.Docx2013);
            doc.Dispose();
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields.OMath

Namespace AddMathEquations
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a string array from LaTeX code
            Dim 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
            Dim 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
            Dim doc As Document = New Document()

            'Add a section
            Dim section As Section = doc.AddSection()

            'Add a paragraph to the section
            Dim textPara As Paragraph = section.AddParagraph()
            textPara.AppendText("Creating Equations from LaTeX Code")
            textPara.ApplyStyle(BuiltinStyle.Heading1)
            textPara.Format.HorizontalAlignment = HorizontalAlignment.Center

            'Iterate through each LaTeX code in the string array
            For i = 0 To latexMathCode.Length - 1
                'Create a math equation from the LaTeX code
                Dim officeMath As OfficeMath = New OfficeMath(doc)
                officeMath.FromLatexMathCode(latexMathCode(i))
                'Add the math equation to the section
                Dim paragraph As Paragraph = section.AddParagraph()
                paragraph.Items.Add(officeMath)
                section.AddParagraph()
            Next

            section.AddParagraph()

            'Add a paragraph to the section
            textPara = section.AddParagraph()
            textPara.AppendText("Creating Equations from MathML Code")
            textPara.ApplyStyle(BuiltinStyle.Heading1)
            textPara.Format.HorizontalAlignment = HorizontalAlignment.Center

            'Iterate through each MathML code in the string array
            For j = 0 To mathMLCode.Length - 1
                'Create a math equation from the MathML code
                Dim officeMath As OfficeMath = New OfficeMath(doc)
                officeMath.FromMathMLCode(mathMLCode(j))
                'Add the math equation to the section
                Dim paragraph As Paragraph = section.AddParagraph()
                paragraph.Items.Add(officeMath)
                section.AddParagraph()
            Next

            'Save the result document    
            doc.SaveToFile("AddMathEquations.docx", FileFormat.Docx2013)
            doc.Dispose()
        End Sub
    End Class
End Namespace

Effective Shot

Conclusion:

In addition to insert math equations into Word documents, Spire.Doc for .NET also offers many other useful features. For example, you can use Spire.Doc to Compare Two Word Documents, Accept or Reject Tracked Changes in Word, Split Word Documents and so on. Apart from that, if you'd like to learn more, you can visit this link to explore more about for Spire.Doc for .NET.

1
Subscribe to my newsletter

Read articles from Carina Thorne directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Carina Thorne
Carina Thorne