News Category

Document Operation

Document Operation (24)

Reading content from a Word document is crucial for many work and study tasks. Reading a page from a Word document helps in quickly browsing and summarizing key information, reading a section from a Word document aids in gaining a deeper understanding of a specific topic or section, while reading the entire document from a Word document allows for a comprehensive grasp of the overall information, facilitating comprehensive analysis and understanding. This article will introduce how to use Spire.Doc for .NET to read a page, a section, and the entire content of a Word document in a C# project.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Read a Page from a Word Document in C#

By using the FixedLayoutDocument class and FixedLayoutPage class, you can easily retrieve the content of a specified page. To facilitate viewing the extracted content, this sample code will store the read content in a new Word document. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.LoadFromFile() method.
  • Create a FixedLayoutDocument object.
  • Retrieve the FixedLayoutPage object of a page in the document.
  • Access the Section where the page is located through the FixedLayoutPage.Section property.
  • Get the index position of the first paragraph on the page within the section.
  • Get the index position of the last paragraph on the page within the section.
  • Create another Document object.
  • Add a new section using Document.AddSection().
  • Clone the properties of the original section to the new section using the Section.CloneSectionPropertiesTo(newSection) method.
  • Copy the content of the page from the original document to the new document.
  • Save the resulting document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Pages;
using Spire.Doc.Documents;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a new document object
            Document document = new Document();

            // Load document content from the specified file
            document.LoadFromFile("Sample.docx");

            // Create a fixed layout document object
            FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document);

            // Get the first page
            FixedLayoutPage page = layoutDoc.Pages[0];

            // Get the section where the page is located
            Section section = page.Section;

            // Get the first paragraph of the page
            Paragraph paragraphStart = page.Columns[0].Lines[0].Paragraph;
            int startIndex = 0;
            if (paragraphStart != null)
            {
                // Get the index of the paragraph in the section
                startIndex = section.Body.ChildObjects.IndexOf(paragraphStart);
            }

            // Get the last paragraph of the page
            Paragraph paragraphEnd = page.Columns[0].Lines[page.Columns[0].Lines.Count - 1].Paragraph;

            int endIndex = 0;
            if (paragraphEnd != null)
            {
                // Get the index of the paragraph in the section
                endIndex = section.Body.ChildObjects.IndexOf(paragraphEnd);
            }

            // Create a new document object
            Document newdoc = new Document();

            // Add a new section
            Section newSection = newdoc.AddSection();

            // Clone the properties of the original section to the new section
            section.CloneSectionPropertiesTo(newSection);

            // Copy the content of the page from the original document to the new document
            for (int i = startIndex; i <= endIndex ; i++)
            {
                newSection.Body.ChildObjects.Add(section.Body.ChildObjects[i].Clone());
            }

            // Save the new document to a specified file
            newdoc.SaveToFile("ReadOnePageContent.docx", Spire.Doc.FileFormat.Docx);

            // Close and release the new document
            newdoc.Close();
            newdoc.Dispose();

            // Close and release the original document
            document.Close();
            document.Dispose();
        }
    }
}

C# Read Content from a Word Document

Read a Section from a Word Document in C#

By using Document.Sections[index], you can retrieve a specific Section object that contains the header, footer, and body content. This example provides a simple way to copy all content of a section to another document. The detailed steps are as follows:

  • Create a Document object.
  • Use the Document.LoadFromFile() method to load a Word document.
  • Use Document.Sections[1] to retrieve the second section of the document.
  • Create another new Document object.
  • Use the Document.CloneDefaultStyleTo(newdoc) method to clone the default style of the original document to the new document.
  • Use newdoc.Sections.Add(section.Clone()) to clone the content of the second section of the original document into the new document.
  • Use the Document.SaveToFile() method to save the resulting document.
  • C#
using Spire.Doc;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
             // Create a new document object
            Document document = new Document();

            // Load a Word document from a file
            document.LoadFromFile("Sample.docx");

            // Get the second section of the document
            Section section = document.Sections[1];

            // Create a new document object
            Document newdoc = new Document();

            // Clone the default style to the new document
            document.CloneDefaultStyleTo(newdoc);

            // Clone the second section to the new document
            newdoc.Sections.Add(section.Clone());

            // Save the new document to a file
            newdoc.SaveToFile("ReadOneSectionContent.docx", Spire.Doc.FileFormat.Docx);

            // Close and release the new document object
            newdoc.Close();
            newdoc.Dispose();

            // Close and release the original document object
            document.Close();
            document.Dispose();
        }
    }
}

C# Read Content from a Word Document

Read the Entire Content from a Word Document in C#

This example demonstrates reading the entire content of a document by iterating through each section of the original document and cloning each section into a new document. The detailed steps are as follows:

  • Create a Document object.
  • Use the Document.LoadFromFile() method to load a Word document.
  • Create another new Document object.
  • Use the Document.CloneDefaultStyleTo(newdoc) method to clone the default style of the original document to the new document.
  • Iterate through each section of the original document using a foreach loop and clone each section into the new document.
  • Use the Document.SaveToFile() method to save the resulting document.
  • C#
using Spire.Doc;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
           // Create a new document object
            Document document = new Document();

            // Load a Word document from a file
            document.LoadFromFile("Sample.docx");

            // Create a new document object
            Document newdoc = new Document();

            // Clone the default style to the new document
            document.CloneDefaultStyleTo(newdoc);

            // Iterate through each section in the original document and clone it to the new document
            foreach (Section sourceSection in document.Sections)
            {
                newdoc.Sections.Add(sourceSection.Clone());
            }

            // Save the new document to a file
            newdoc.SaveToFile("ReadEntireDocumentContent.docx", Spire.Doc.FileFormat.Docx);

            // Close and release the new document object
            newdoc.Close();
            newdoc.Dispose();

            // Close and release the original document object
            document.Close();
            document.Dispose();
        }
    }
}

C# Read Content from a Word Document

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.

Adding, inserting, and deleting pages in a Word document is crucial for managing and presenting content. By adding or inserting a new page in Word, you can expand the document to accommodate more content, making it more structured and readable. Deleting pages can help streamline the document by removing unnecessary information or erroneous content. This article will explain how to use Spire.Doc for .NET to add, insert, or delete a page in a Word document within a C# project.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Add a Page in a Word Document using C#

The steps to add a new page at the end of a Word document involve first obtaining the last section, then inserting a page break at the end of the last paragraph of that section to ensure that subsequently added content appears on a new page. Here are the detailed steps:

  • Create a Document object.
  • Load a Word document using the Document.LoadFromFile() method.
  • Get the body of the last section of the document using Document.LastSection.Body.
  • Add a page break by calling Paragraph.AppendBreak(BreakType.PageBreak) method.
  • Create a new ParagraphStyle object.
  • Add the new paragraph style to the document's style collection using Document.Styles.Add() method.
  • Create a new Paragraph object and set the text content.
  • Apply the previously created paragraph style to the new paragraph using Paragraph.ApplyStyle(ParagraphStyle.Name) method.
  • Add the new paragraph to the document using Body.ChildObjects.Add(Paragraph) method.
  • Save the resulting document using the Document.SaveToFile() method.
  • C#
// Create a new document object
Document document = new Document();

// Load a document
document.LoadFromFile("Sample.docx");

// Get the body of the last section of the document
Body body = document.LastSection.Body;

// Insert a page break after the last paragraph in the body
body.LastParagraph.AppendBreak(BreakType.PageBreak);

// Create a new paragraph style
ParagraphStyle paragraphStyle = new ParagraphStyle(document);
paragraphStyle.Name = "CustomParagraphStyle1";
paragraphStyle.ParagraphFormat.LineSpacing = 12;
paragraphStyle.ParagraphFormat.AfterSpacing = 8;
paragraphStyle.CharacterFormat.FontName = "Microsoft YaHei";
paragraphStyle.CharacterFormat.FontSize = 12;

// Add the paragraph style to the document's style collection
document.Styles.Add(paragraphStyle);

// Create a new paragraph and set the text content
Paragraph paragraph = new Paragraph(document);
paragraph.AppendText("Thank you for using our Spire.Doc for .NET product. The trial version will add a red watermark to the generated document and only supports converting the first 10 pages to other formats. Upon purchasing and applying a license, these watermarks will be removed, and the functionality restrictions will be lifted.");

// Apply the paragraph style
paragraph.ApplyStyle(paragraphStyle.Name);

// Add the paragraph to the body's content collection
body.ChildObjects.Add(paragraph);

// Create another new paragraph and set the text content
paragraph = new Paragraph(document);
paragraph.AppendText("To experience our product more fully, we provide a one-month temporary license free of charge to each of our customers. Please send an email to sales@e-iceblue.com, and we will send the license to you within one working day.");

// Apply the paragraph style
paragraph.ApplyStyle(paragraphStyle.Name);

// Add the paragraph to the body's content collection
body.ChildObjects.Add(paragraph);

// Save the document to the specified path
document.SaveToFile("Add a Page.docx", FileFormat.Docx);

// Close the document
document.Close();

// Release the resources of the document object
document.Dispose();

C#: Add, Insert, or Delete Pgaes in Word Documents

Insert a Page in a Word Document using C#

Before inserting a new page, it is necessary to determine the ending position index of the specified page content within the section. Subsequently, add the content of the new page to the document one by one after this position. Finally, to separate the content from the following pages, adding a page break is essential. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.LoadFromFile() method.
  • Create a FixedLayoutDocument object.
  • Obtain the FixedLayoutPage object of a page in the document.
  • Determine the index position of the last paragraph on the page within the section.
  • Create a new ParagraphStyle object.
  • Add the new paragraph style to the document's style collection using Document.Styles.Add() method.
  • Create a new Paragraph object and set the text content.
  • Apply the previously created paragraph style to the new paragraph using the Paragraph.ApplyStyle(ParagraphStyle.Name) method.
  • Insert the new paragraph at the specified using the Body.ChildObjects.Insert(index, Paragraph) method.
  • Create another new paragraph object, set its text content, add a page break by calling the Paragraph.AppendBreak(BreakType.PageBreak) method, apply the previously created paragraph style, and then insert this paragraph into the document.
  • Save the resulting document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Pages;
using Spire.Doc.Documents;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
           // Create a new document object
            Document document = new Document();

            // Load the sample document from a file
            document.LoadFromFile("Sample.docx");

            // Create a fixed layout document object
            FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document);

            // Get the first page
            FixedLayoutPage page = layoutDoc.Pages[0];

            // Get the body of the document
            Body body = page.Section.Body;

            // Get the last paragraph of the current page
            Paragraph paragraphEnd = page.Columns[0].Lines[page.Columns[0].Lines.Count - 1].Paragraph;

            // Initialize the end index
            int endIndex = 0;
            if (paragraphEnd != null)
            {
                // Get the index of the last paragraph
                endIndex = body.ChildObjects.IndexOf(paragraphEnd);
            }

            // Create a new paragraph style
            ParagraphStyle paragraphStyle = new ParagraphStyle(document);
            paragraphStyle.Name = "CustomParagraphStyle1";
            paragraphStyle.ParagraphFormat.LineSpacing = 12;
            paragraphStyle.ParagraphFormat.AfterSpacing = 8;
            paragraphStyle.CharacterFormat.FontName = "Microsoft YaHei";
            paragraphStyle.CharacterFormat.FontSize = 12;

            // Add the paragraph style to the document's style collection
            document.Styles.Add(paragraphStyle);

            // Create a new paragraph and set the text content
            Paragraph paragraph = new Paragraph(document);
            paragraph.AppendText("Thank you for using our Spire.Doc for .NET product. The trial version will add a red watermark to the generated document and only supports converting the first 10 pages to other formats. Upon purchasing and applying a license, these watermarks will be removed, and the functionality restrictions will be lifted.");

            // Apply the paragraph style
            paragraph.ApplyStyle(paragraphStyle.Name);

            // Insert the paragraph at the specified position
            body.ChildObjects.Insert(endIndex + 1, paragraph);

            // Create another new paragraph
            paragraph = new Paragraph(document);
            paragraph.AppendText("To experience our product more fully, we provide a one-month temporary license free of charge to each of our customers. Please send an email to sales@e-iceblue.com, and we will send the license to you within one working day.");

            // Apply the paragraph style
            paragraph.ApplyStyle(paragraphStyle.Name);

            // Add a page break
            paragraph.AppendBreak(BreakType.PageBreak);

            // Insert the paragraph at the specified position
            body.ChildObjects.Insert(endIndex + 2, paragraph);

            // Save the document to the specified path
            document.SaveToFile("Insert a Page.docx", Spire.Doc.FileFormat.Docx);

            // Close and release the original document
            document.Close();
            document.Dispose();
        }
    }
}

C#: Add, Insert, or Delete Pgaes in Word Documents

Delete a Page from a Word Document using C#

To delete the content of a page, first determine the index positions of the starting and ending elements of that page in the document. Then, you can utilize a loop to systematically remove these elements one by one. The detailed steps are as follows:

  • Create a Document object.
  • Load a Word document using the Document.LoadFromFile() method.
  • Create a FixedLayoutDocument object.
  • Obtain the FixedLayoutPage object of the first page in the document.
  • Use the FixedLayoutPage.Section property to get the section where the page is located.
  • Determine the index position of the first paragraph on the page within the section.
  • Determine the index position of the last paragraph on the page within the section.
  • Use a for loop to remove the content of the page one by one.
  • Save the resulting document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Pages;
using Spire.Doc.Documents;

namespace SpireDocDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
           // Create a new document object
            Document document = new Document();

            // Load the sample document from a file
            document.LoadFromFile("Sample.docx");

            // Create a fixed layout document object
            FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document);

            // Get the second page
            FixedLayoutPage page = layoutDoc.Pages[1];

            // Get the section of the page
            Section section = page.Section;

            // Get the first paragraph on the first page
            Paragraph paragraphStart = page.Columns[0].Lines[0].Paragraph;
            int startIndex = 0;
            if (paragraphStart != null)
            {
                // Get the index of the starting paragraph
                startIndex = section.Body.ChildObjects.IndexOf(paragraphStart);
            }

            // Get the last paragraph on the last page
            Paragraph paragraphEnd = page.Columns[0].Lines[page.Columns[0].Lines.Count - 1].Paragraph;

            int endIndex = 0;
            if (paragraphEnd != null)
            {
                // Get the index of the ending paragraph
                endIndex = section.Body.ChildObjects.IndexOf(paragraphEnd);
            }

            // Delete all content within the specified range
            for (int i = 0; i <= (endIndex - startIndex); i++)
            {
                section.Body.ChildObjects.RemoveAt(startIndex);
            }

            // Save the document to the specified path
            document.SaveToFile("Delete a Page.docx", Spire.Doc.FileFormat.Docx);

            // Close and release the original document
            document.Close();
            document.Dispose();
        }
    }
}

C#: Add, Insert, or Delete Pgaes in Word Documents

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.

We have introduced how to compare two Word documents in C# and VB.NET. From Spire.Doc V8.12.14, it supports to get the differences between two Word documents in a structure list. This article will show you how to use Spire.Doc to get the differences by comparing two Word documents.

C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting.Revisions;
using System;

namespace GetWordDifferences
    {
    class Program
    {
        static void Main(string[] args)

        {
            //Load the first Word document
            Document doc1 = new Document();
            doc1.LoadFromFile("Sample1.docx");

            //Load the second Word document
            Document doc2 = new Document();
            doc2.LoadFromFile("Sample2.docx");

            //Compare the two Word documents
            doc1.Compare(doc2, "Author");

            foreach (Section sec in doc1.Sections)
            {
                foreach (DocumentObject docItem in sec.Body.ChildObjects)
                {
                    if (docItem is Paragraph)
{
                        Paragraph para = docItem as Paragraph;
                        if (para.IsInsertRevision)
                        { 
                            EditRevision insRevison = para.InsertRevision;
                            EditRevisionType insType = insRevison.Type; 
                            string insAuthor = insRevison.Author; 
                            DateTime insDateTime = insRevison.DateTime; 
                        }

                        else if (para.IsDeleteRevision)
                        { 
                            EditRevision delRevison = para.DeleteRevision; 
                            EditRevisionType delType = delRevison.Type; 
                            string delAuthor = delRevison.Author; 
                            DateTime delDateTime = delRevison.DateTime; 
                        }

                        foreach (ParagraphBase paraItem in para.ChildObjects)
                        {
                            if (paraItem.IsInsertRevision)
                            { 
                                EditRevision insRevison = paraItem.InsertRevision; 
                                EditRevisionType insType = insRevison.Type; 
                                string insAuthor = insRevison.Author; 
                                DateTime insDateTime = insRevison.DateTime; 
                            }

                            else if (paraItem.IsDeleteRevision)
                            { 
                                EditRevision delRevison = paraItem.DeleteRevision; 
                                EditRevisionType delType = delRevison.Type; 
                                string delAuthor = delRevison.Author; 
                                DateTime delDateTime = delRevison.DateTime; 
                            }

                        }
                    }
                }
            }

            //Get the difference about revisions
            DifferRevisions differRevisions = new DifferRevisions(doc1);
            var insetRevisionsList = differRevisions.InsertRevisions;
            var deletRevisionsList = differRevisions.DeleteRevisions;      
        }
    }
 }
VB.NET
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports Spire.Doc.Formatting.Revisions
Imports System

Namespace GetWordDifferences
    
    Class Program
        
        Private Shared Sub Main(ByVal args() As String)
            'Load the first Word document
            Dim doc1 As Document = New Document
            doc1.LoadFromFile("Sample1.docx")
            'Load the second Word document
            Dim doc2 As Document = New Document
            doc2.LoadFromFile("Sample2.docx")
            'Compare the two Word documents
            doc1.Compare(doc2, "Author")
            For Each sec As Section In doc1.Sections
                For Each docItem As DocumentObject In sec.Body.ChildObjects
                    If (TypeOf docItem Is Paragraph) Then
                        Dim para As Paragraph = CType(docItem,Paragraph)
                        If para.IsInsertRevision Then
                            Dim insRevison As EditRevision = para.InsertRevision
                            Dim insType As EditRevisionType = insRevison.Type
                            Dim insAuthor As String = insRevison.Author
                            Dim insDateTime As DateTime = insRevison.DateTime
                        ElseIf para.IsDeleteRevision Then
                            Dim delRevison As EditRevision = para.DeleteRevision
                            Dim delType As EditRevisionType = delRevison.Type
                            Dim delAuthor As String = delRevison.Author
                            Dim delDateTime As DateTime = delRevison.DateTime
                        End If
                        
                        For Each paraItem As ParagraphBase In para.ChildObjects
                            If paraItem.IsInsertRevision Then
                                Dim insRevison As EditRevision = paraItem.InsertRevision
                                Dim insType As EditRevisionType = insRevison.Type
                                Dim insAuthor As String = insRevison.Author
                                Dim insDateTime As DateTime = insRevison.DateTime
                            ElseIf paraItem.IsDeleteRevision Then
                                Dim delRevison As EditRevision = paraItem.DeleteRevision
                                Dim delType As EditRevisionType = delRevison.Type
                                Dim delAuthor As String = delRevison.Author
                                Dim delDateTime As DateTime = delRevison.DateTime
                            End If
                            
                        Next
                    End If
                    
                Next
            Next
            'Get the difference about revisions
            Dim differRevisions As DifferRevisions = New DifferRevisions(doc1)
            Dim insetRevisionsList = differRevisions.InsertRevisions
            Dim deletRevisionsList = differRevisions.DeleteRevisions
        End Sub
    End Class
End Namespace

It is not uncommon at work that we may receive two versions of a Word document and face the need to find the differences between them. Document comparison is particularly important and popular in the fields of laws, regulations and education. In this article, you will learn how to compare two Word documents in C# and VB.NET by using Spire.Doc for .NET.

Below is a screenshot of the two Word documents that’ll be compared.

C#/VB.NET: Compare Two Word Documents

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Compare Two Documents and Save Result in a Third Word Document

Saving the comparison result in a separate Word document allows us to see all the changes made to the original document, including insertions, deletions as well as modifications on formatting. The following are the steps to compare two documents and save the result in a third Word document using Spire.Doc for .NET.

  • Load two Word documents separately while initialing the Document objects.
  • Compare these two documents using Document.Compare() method.
  • Save the result in a third Word document using ;Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;

namespace CompareDocuments
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load one Word document
            Document doc1 = new Document("C:\\Users\\Administrator\\Desktop\\original.docx");

            //Load the other Word document
            Document doc2 = new Document("C:\\Users\\Administrator\\Desktop\\revised.docx");

            //Compare two documents
            doc1.Compare(doc2, "John");

            //Save the differences in a third document
            doc1.SaveToFile("Differences.docx", FileFormat.Docx2013);
            doc1.Dispose();
        }
    }
}

C#/VB.NET: Compare Two Word Documents

Compare Two Documents and Return Insertions and Deletions in Lists

Developers may only want to obtain the insertions and deletions instead of the whole differences. The following are the steps to get insertions and deletions in two separate lists.

  • Load two Word documents separately while initialing the Document objects.
  • Compare two documents using Document.Compare() method.
  • Get the revisions using the constructor function of the DifferRevisions ;class.
  • Get a list of insertions through DifferRevisions.InsertRevisions property.
  • Get a list of deletions through DifferRevisions.DeleteRevisions property.
  • Loop through the elements in the two lists to get the specific insertion and deletion.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Fields;
using System;

namespace GetDifferencesInList
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load one Word document
            Document doc1 = new Document("C:\\Users\\Administrator\\Desktop\\original.docx");

            //Load the other Word document
            Document doc2 = new Document("C:\\Users\\Administrator\\Desktop\\revised.docx");

            //Compare the two Word documents
            doc1.Compare(doc2, "Author");

            //Get the revisions
            DifferRevisions differRevisions = new DifferRevisions(doc1);

            //Return the insertion revisions in a list
            var insetRevisionsList = differRevisions.InsertRevisions;

            //Return the deletion revisions in a list
            var deletRevisionsList = differRevisions.DeleteRevisions;

            //Create two int variables
            int m = 0;
            int n = 0;

            //Loop through the insertion revision list 
            for (int i = 0; i < insetRevisionsList.Count; i++)
            {
                if (insetRevisionsList[i] is TextRange)
                {
                    m += 1;
                    //Get the specific revision and get its content
                    TextRange textRange = insetRevisionsList[i] as TextRange;
                    Console.WriteLine("Insertion #" + m + ":" + textRange.Text);
                }
            }
            Console.WriteLine("=====================");

            //Loop through the deletion revision list 
            for (int i = 0; i < deletRevisionsList.Count; i++)
            {
                if (deletRevisionsList[i] is TextRange)
                {
                    n += 1;
                    //Get the specific revision and get its content
                    TextRange textRange = deletRevisionsList[i] as TextRange;
                    Console.WriteLine("Deletion #" + n + ":" + textRange.Text);
                }
            }
            Console.ReadKey();
        }
    }
}

C#/VB.NET: Compare Two Word Documents

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.

Math equations in Word documents are essential tools for expressing mathematical concepts and relationships. Whether you are writing an academic paper, a scientific report, or any other document involving mathematical content, incorporating math equations can greatly enhance your ability to convey complex mathematical concepts and improve the visual appeal and professionalism of your document. In this article, we will explain how to insert math equations into Word documents in C# and VB.NET using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

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

Spire.Doc for .NET allows generating math equations from LaTeX code and MathML code using OfficeMath.FromLatexMathCode(string latexMathCode) and OfficeMath.FromMathMLCode(string mathMLCode) methods. The detailed steps are as follows:

  • 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.
  • C#
  • VB.NET
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();
        }
    }
}

C#/VB.NET: Insert Math Equations into Word Documents

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.

Besides the Combo Box, Text, Date Picker and Drop-Down List content controls, Checkbox and picture content control also are the mostly used content control in word document. Spire.Doc supports to add many kinds of content controls to the word document. This article will show you how to add checkbox and picture content control to word document by Spire.Doc for .NET.

Code snippets of how to add checkbox and picture content control:

using System;
using System.Drawing;
namespace AddCheckbox
{

    class Program
    {

        static void Main(string[] args)
        {
            //Create a new word document
            Document document = new Document();

            //Add a section to the document
            Section section = document.AddSection();

            //Add a document to the section
            Paragraph paragraph = section.AddParagraph();

            //Add checkbox content control
            StructureDocumentTagInline sdt = new StructureDocumentTagInline(document);
            paragraph = section.AddParagraph();
            sdt = new StructureDocumentTagInline(document);
            sdt.CharacterFormat.FontSize = 20;
            paragraph.ChildObjects.Add(sdt);
            sdt.SDTProperties.SDTType = SdtType.CheckBox;
            SdtCheckBox scb = new SdtCheckBox();
            sdt.SDTProperties.ControlProperties = scb;
            TextRange tr = new TextRange(document);
            tr.CharacterFormat.FontName = "MS Gothic";
            tr.CharacterFormat.FontSize = 20;
            sdt.ChildObjects.Add(tr);
            scb.Checked = true;

            sdt.SDTProperties.Alias = "CheckoBox";
            sdt.SDTProperties.Tag = "Checkbox";

            //Add picture content control
            paragraph = section.AddParagraph();
            sdt = new StructureDocumentTagInline(document);
            paragraph.ChildObjects.Add(sdt);
            sdt.SDTProperties.ControlProperties = new SdtPicture();

            sdt.SDTProperties.Alias = "Picture";
            sdt.SDTProperties.Tag = "Picture";

            DocPicture pic = new DocPicture(document) { Width = 10, Height = 10 };
            pic.LoadImage(Image.FromFile("Logo.jpg"));
            sdt.SDTContent.ChildObjects.Add(pic);

            document.SaveToFile("Sample.docx", FileFormat.Docx2013);

        }
    }
}

Effective screenshot after adding checkbox and picture content control to word document:

Add checkbox and picture content control to word document in C#

VBA (Visual Basic for Applications) macros are small programs that can be embedded within Microsoft Word documents to automate repetitive tasks, add interactivity to documents, and perform other useful functions. While macros can be beneficial in many situations, they can also pose a security risk if the code is malicious or contains malware. By removing VBA macros from Word documents, you can reduce the risk of security breaches and malware infections. In this article, you will learn how to detect and remove VBA macros from Word documents in C# and VB.NET using Spire.Doc for .NET library.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Detect and Remove VBA Macros from Word Documents in C# and VB.NET

You can use the Document.IsContainMacro property to detect whether a Word document contains VBA macros. If any macros are detected, you can use the Document.ClearMacros() method to easily remove them from the document.

The following steps show how to detect and remove VBA macros from a Word document using Spire.Doc for .NET:

  • Initialize an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile(string fileName) method.
  • Detect if the document contains VBA macros using the Document.IsContainMacro property.
  • If any macros are detected, remove them from the document using Document.ClearMacros() method.
  • Save the result document using Document.SaveToFile(string fileName, FileFormat fileFormat) method.
  • C#
  • VB.NET
using Spire.Doc;

namespace RemoveVBAMacros
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile("Input.docm");

            //Detect if the document contains macros
            if (document.IsContainMacro)
            {
                //Remove the macros from the document
                document.ClearMacros();
            }

            //Save the result document
            document.SaveToFile("RemoveMacros.docm", FileFormat.Docm);
            document.Close();
        }
    }
}

C#/VB.NET: Detect and Remove VBA Macros from Word Documents

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.

With Spire.Doc, we can copy the content from one word document to another word document in C#. When we need to generate a large amount of documents from a single document, clone the document will be much easier. The clone method speeds up the generation of the word documents and developers only need one single line of code to get the copy of the word document.

Now we will show the code snippet of how to clone a word document in C#.

Step 1: Create a new instance of Document and load the document from file.

Document doc = new Document();
doc.LoadFromFile("Sample.docx",FileFormat.Docx2010);

Step 2: Clone the word document.

doc.Clone();

Step 3: Save the document to file.

doc.SaveToFile("Cloneword.docx", FileFormat.Docx2010);

Effective screenshot of clone the word document:

How to clone a word document in C#

Full codes of clone a word document:

using Spire.Doc;
namespace CloneWord
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("Sample.docx", FileFormat.Docx2010);
            doc.Clone();
            doc.SaveToFile("Cloneword.docx", FileFormat.Docx2010);
        }
    }
}

Document variables are used to preserve macro settings in between macro sessions. Spire.Doc allows adding variables, counting the number of variables, retrieving the name and value of variables, and removing specific variables in a Word document.

Add a Variable

Use the Add method to add a variable to a document. The following example adds a document variable named "A1" with a value of 12 to the document.

using Spire.Doc;
using Spire.Doc.Documents;
namespace ADDVARIABLE
{
    class Program
    {

        static void Main(string[] args)
        {
            //Instantiate a document object
            Document document = new Document();
            //Add a section
            Section section = document.AddSection();
            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();
            //Add a DocVariable Filed
            paragraph.AppendField("A1", FieldType.FieldDocVariable);
            //Add a document variable to the DocVariable Filed
            document.Variables.Add("A1", "12");
            //Update fields
            document.IsUpdateFields = true;
            //Save and close the document object
            document.SaveToFile("AddVariable.docx", FileFormat.Docx2013);
            document.Close();
        }
    }
}

Add, Count, Retrieve and Remove Variables in a Word document Using C#

Count the number of Variables

Use the Count property to return the number of variables in a document.

//Load the document
Document document = new Document("AddVariable.docx");
//Get the number of variables in the document
int number = document.Variables.Count;

Console.WriteLine(number);

Add, Count, Retrieve and Remove Variables in a Word document Using C#

Retrieve Name and Value of a Variable

Use the GetNameByIndex and GetValueByIndex methods to retrieve the name and value of the variable by index, and the Variables[String Name] to retrieve or set the value of the variable by name.

using Spire.Doc;
using Spire.Doc.Documents;
using System;
namespace COUNTVARIABLE
{

    class Program
    {

        static void Main(string[] args)
        {
            //Load the document
            Document document = new Document("AddVariable.docx");
            //Get the number of variables in the document
            int number = document.Variables.Count;

            Console.WriteLine(number);

        }
    }
}

Add, Count, Retrieve and Remove Variables in a Word document Using C#

Remove a specific Variable

Use the Remove method to remove the variable from the document.

using Spire.Doc;
using System;
namespace RETRIEVEVARIABLE
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the document
            Document document = new Document("AddVariable.docx");

            // Retrieve name of the variable by index
            string s1 = document.Variables.GetNameByIndex(0);

            // Retrieve value of the variable by index
            string s2 = document.Variables.GetValueByIndex(0);

            // Retrieve or set value of the variable by name
            string s3 = document.Variables["A1"];

            Console.WriteLine("{0} {1} {2}", s1, s2, s3);
        }
    }
}

The track changes has been used to keep track of the every changes that made to the Word document. It helps to record every edit, insertion, deletion, or modification in a word document. We have demonstrated how to accept/reject the tracked changes on word document in C#. This article will show you how to enable track changes of the document.

Step 1: Create a new word document and load the document from file.

Document document = new Document();
document.LoadFromFile("Sample.docx", FileFormat.Docx2010);

Step 2: Enable the track changes.

document.TrackChanges = true;

Step 3: Save the document to file.

document.SaveToFile("Enable Trackchanges.docx", FileFormat.Docx2010);

Effective screenshot:

How to enable track changes of the word document

Full codes:

using Spire.Doc;
namespace EnableTrack
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("Sample.docx", FileFormat.Docx2010);
            document.TrackChanges = true;
         document.SaveToFile("Enable Trackchanges.docx", FileFormat.Docx2010);

        }
    }
}
Page 1 of 2