C#/VB.NET: Change the Font Style in a Word Document

Changing the font style in a Word document is an effective way to customize the appearance of your text. By applying different font styles, you can add visual interest and create a clear hierarchy within your content. This not only improves the overall quality of your document but also enhances the effectiveness of your communication. This article will demonstrate how to programmatically change the font style in a Word document using C# and VB.NET.

The following topics will be discussed:

  • Change the Font Style of a Specific Word in a Word Document
  • Change the Font Style of a Specific Paragraph in a Word Document
  • Change the Font Style of an Entire Word Document

Installation

To change the font style in a Word document, this article uses Free Spire.Doc for .NET. You can install Free Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package FreeSpire.Doc

Alternatively, you can also download the DLL files of Free Spire.Doc for .NET from its official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Change the Font Style of a Specific Word in a Word Document in C# and VB.NET

To change the font style of a specific word in a Word document, you need to search for the word in the document, then change the font style of all its occurrences.

The following steps explain how to change the font style of a specific word in a Word document:

  • Initialize an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile(string fileName) method.
  • Search for the word that you want to change the font color for using the Document.FindAllString(string matchString, bool caseSensitive, bool wholeWord) method.
  • Iterate through all the occurrences of the searched text.
  • Get the current occurrence as a single text range using the TextSelection.GetAsOneRange() method.
  • Change the font color of the text range using the TextRange.CharacterFormat.TextColor property.
  • Make the text of the text range bold using the TextRange.CharacterFormat.Bold property.
  • Save the result document using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace ChangeFontStyleForWord
{
    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("Sample.docx");

            //Search for the text that you want to change the font style for
            TextSelection[] text = document.FindAllString("Information", false, true);

            //Iterate through all the occurrences of the searched text
            foreach (TextSelection seletion in text)
            {
                //Get the current occurrence as a single text range
                TextRange range = seletion.GetAsOneRange();
                //Change the font color of the text range
                range.CharacterFormat.TextColor = Color.Red;
                //Make the text of the text range bold
                range.CharacterFormat.Bold = true;
            }

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

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports System.Drawing

Namespace ChangeFontStyleForWord
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document()
            'Load a Word document
            document.LoadFromFile("Sample.docx")

            'Search for the text that you want to change the font style for
            Dim text As TextSelection() = document.FindAllString("Information", False, True)

            'Iterate through all the occurrences of the searched text
            For Each seletion As TextSelection In text
                'Get the current occurrence as a single text range
                Dim range As TextRange = seletion.GetAsOneRange()
                'Change the font color of the text range
                range.CharacterFormat.TextColor = Color.Red
                'Make the text of the text range bold
                range.CharacterFormat.Bold = True
            Next

            'Save the result document
            document.SaveToFile("ChangeFontStyleForSpecificWord.docx", FileFormat.Docx2013)
            document.Dispose()
        End Sub
    End Class
End Namespace
Change the Font Style of Specific Word in Word Document using C# or VB.NET

Change the Font Style of a Specific Paragraph in a Word Document in C# and VB.NET

You can change the font style of a paragraph by creating a new paragraph style with a specific font style, then applying the new paragraph style to the paragraph you want to modify.

The following steps explain how to change the font style of a specific paragraph in a Word document:

  • Initialize an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile(string fileName) method.
  • Get a specific section of the document using the Document.Sections[int index] property.
  • Get a specific paragraph of the section using the Section.Paragraphs[int index] property.
  • Initialize an instance of the ParagraphStyle class to create a new paragraph style.
  • Set the name and font style for the paragraph style.
  • Add the paragraph style to the document using the Document.Styles.Add(IStyle style) method.
  • Apply the paragraph style to the specific paragraph using the Paragraph.ApplyStyle(string styleName) method.
  • Save the result document using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace ChangeFontStyleForParagraph
{
    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("Sample.docx");

            //Get the first section
            Section section = document.Sections[0];

            //Get the second paragraph
            Paragraph p1 = section.Paragraphs[1];

            //Create a new paragraph style with a specific font style
            ParagraphStyle paragraphStyle = new ParagraphStyle(document);
            paragraphStyle.Name = "ParaStyle";
            paragraphStyle.CharacterFormat.TextColor = Color.ForestGreen;
            paragraphStyle.CharacterFormat.UnderlineStyle = UnderlineStyle.Single;

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

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

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

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing

Namespace ChangeFontStyleForParagraph
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document()
            'Load a Word document
            document.LoadFromFile("Sample.docx")

            'Get the first section
            Dim section As Section = document.Sections(0)

            'Get the second paragraph
            Dim p1 As Paragraph = section.Paragraphs(1)

            'Create a new paragraph style with a specific font style
            Dim paragraphStyle As ParagraphStyle = New ParagraphStyle(document)
            paragraphStyle.Name = "ParaStyle"
            paragraphStyle.CharacterFormat.TextColor = Color.ForestGreen
            paragraphStyle.CharacterFormat.UnderlineStyle = UnderlineStyle.[Single]

            'Add the paragraph style to the document
            document.Styles.Add(paragraphStyle)

            'Apply the paragraph style to the second paragraph
            p1.ApplyStyle(paragraphStyle.Name)

            'Save the result document
            document.SaveToFile("ChangeFontStyleForParagraph.docx", FileFormat.Docx2013)
            document.Dispose()
        End Sub
    End Class
End Namespace
Change the Font Style of Specific Paragraph in Word Document using C# or VB.NET

Change the Font Style of an Entire Word Document in C# and VB.NET

To change the font style of an entire Word document, you need to create a new paragraph style with a specific font style, then iterate through all the paragraphs in the document and apply the new paragraph style to them.

The following steps explain how to change the font style of an entire Word document:

  • Initialize an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile(string fileName) method.
  • Initialize an instance of the ParagraphStyle class to create a new paragraph style.
  • Set the name and font style for the paragraph style.
  • Add the paragraph style to the document using the Document.Styles.Add(IStyle style) method.
  • Iterate through all the sections in the document.
  • Iterate through all the paragraphs in each section.
  • Apply the paragraph style to each paragraph using the Paragraph.ApplyStyle(string styleName) method.
  • Save the result document using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace ChangeFontStyleForDocument
{
    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("Sample.docx");

            //Create a new paragraph style with specific font style
            ParagraphStyle paraStyle = new ParagraphStyle(document);
            paraStyle.Name = "ParaStyle";
            paraStyle.CharacterFormat.TextColor = Color.CornflowerBlue;
            paraStyle.CharacterFormat.Font = new Font("Arial", 12);
            paraStyle.CharacterFormat.Italic = true;

            //Add the paragraph style to the document
            document.Styles.Add(paraStyle);

            //Iterate through all the sections of the document
            foreach (Section section in document.Sections)
            {
                //Iterate through all the paragraphs of each section
                foreach (Paragraph para in section.Paragraphs)
                {
                    //Apply the paragraph style to each paragraph
                    para.ApplyStyle(paraStyle.Name);
                }
            }

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

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing

Namespace ChangeFontStyleForDocument
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document()
            'Load a Word document
            document.LoadFromFile("Sample.docx")

            'Create a new paragraph style with specific font style
            Dim paraStyle As ParagraphStyle = New ParagraphStyle(document)
            paraStyle.Name = "ParaStyle"
            paraStyle.CharacterFormat.TextColor = Color.CornflowerBlue
            paraStyle.CharacterFormat.Font = New Font("Arial", 12)
            paraStyle.CharacterFormat.Italic = True

            'Add the paragraph style to the document
            document.Styles.Add(paraStyle)

            'Iterate through all the sections of the document
            For Each section As Section In document.Sections
                'Iterate through all the paragraphs of each section
                For Each para As Paragraph In section.Paragraphs
                    'Apply the paragraph style to each paragraph
                    para.ApplyStyle(paraStyle.Name)
                Next
            Next

            'Save the result document
            document.SaveToFile("ChangeFontStyleForEntireDocument.docx", FileFormat.Docx2013)
            document.Dispose()
        End Sub
    End Class
End Namespace
Change the Font Style of Entire Word Document using C# or VB.NET

C#/VB.NET: Set or Remove Editable Ranges in Word Documents

Setting editable ranges is an effective way to control the editing permissions for specific areas of a Word document. This feature is particularly useful when working on collaborative documents or templates that require restricting changes to certain areas while granting users the ability to add or modify text in other sections. With editable ranges, you can ensure that only authorized users can make changes to selected parts of the document while maintaining the overall structure and formatting. This article will show how to set or remove editable ranges in Word documents using C# and VB.NET.

  • Set Editable Ranges in Word Documents in C# and VB.NET
  • Remove Editable Ranges from Word Documents in C# and VB.NET

Installation

To set or remove editable ranges in Word documents, this article uses Free Spire.Doc for .NET. You can install Free Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package FreeSpire.Doc

Alternatively, you can also download the DLL files of FreeSpire.Doc for .NET from its official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Set Editable Ranges in Word Documents in C# and VB.NET

You can set a specific area, for example, a paragraph or part of a paragraph, as an editable range by creating a permission start tag and a permission end tag using the PermissionStart and PermissionEnd classes, then adding these tags to specific positions of the paragraph. After that, you need to protect the document with a password to enable this setting.

The following steps explain how to set a paragraph as an editable range in a Word document:

  • Initialize an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile(string fileName) method.
  • Get a specific section of the document by its index using the Document.Sections[int index] property.
  • Get a specific paragraph of the section by its index using the Section.Paragraphs[int index] property.
  • Initialize an instance of the PermissionStart class to create a permission start tag.
  • Initialize an instance of the PermissionEnd class to create a permission end tag.
  • Add the permission start tag and permission end tag to specific positions of the paragraph.
  • Protect the document with a password using the Document.Protect(ProtectionType type, string password) method.
  • Save the result document to another file using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.

C#

using Spire.Doc;
using Spire.Doc.Documents;

namespace SetEditableRanges
{
    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(@"Sample.docx");
            
            //Get the first section of the document
            Section section= document.Sections[0];
            //Get the first paragraph of the section
            Paragraph paragraph = section.Paragraphs[0];

            //Create a permission start tag (note that the id of the start tag and its end tag must be the same)
            PermissionStart startTag = new PermissionStart(document, "Id");
            //Create a permission end tag
            PermissionEnd endTag = new PermissionEnd(document, "Id");

            //Set the first paragraph as an editable range
            //Add the permission start tag to the beginning of the paragraph
            paragraph.ChildObjects.Insert(0, startTag);
            //Add the permission end tag to the end of the paragraph
            paragraph.ChildObjects.Add(endTag);

            //Protect the document with a password and a specific protection type
            document.Protect(ProtectionType.AllowOnlyReading, "password");

            //Save the result document to another file
            document.SaveToFile("SetEditableRange.docx", FileFormat.Docx2013);
            document.Close();
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace SetEditableRanges
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document()
            'Load a Word document
            document.LoadFromFile("Sample.docx")

            'Get the first section of the document
            Dim section As Section = document.Sections(0)
            'Get the first paragraph of the section
            Dim paragraph As Paragraph = section.Paragraphs(0)

            'Create a permission start tag (note that the id of the start tag and its end tag must be the same)
            Dim startTag As PermissionStart = New PermissionStart(document, "Id")
            'Create a permission end tag
            Dim endTag As PermissionEnd = New PermissionEnd(document, "Id")

            'Set the first paragraph as an editable range
            'Add the permission start tag to the beginning of the paragraph
            paragraph.ChildObjects.Insert(0, startTag)
            'Add the permission end tag to the end of the paragraph
            paragraph.ChildObjects.Add(endTag)

            'Protect the document with a password and a specific protection type
            document.Protect(ProtectionType.AllowOnlyReading, "password")

            'Save the result document to another file
            document.SaveToFile("SetEditableRange.docx", FileFormat.Docx2013)
            document.Close()
        End Sub
    End Class
End Namespace

When you open the result document after setting editable ranges, Microsoft Word automatically highlights the editable regions for you:

Set Editable Ranges in Word Document in C# or VB.NET

Remove Editable Ranges from Word Documents in C# and VB.NET

If you no longer need the editable ranges in a Word document, you can remove them. To achieve this, you need to iterate through all the elements in the document, then find the elements that are of the PermissionStart or PermissionEnd type and remove them from the paragraphs of the document using the Paragraph.ChildObjects.Remove(IDocumentObject entity) method.

The following steps explain how to remove the editable ranges from a Word document:

  • Initialize an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile(string fileName) method.
  • 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 PermissionStart or PermissionEnd type.
  • If the result is true, remove them from the paragraph using the Paragraph.ChildObjects.Remove(IDocumentObject entity) method.
  • Save the result document to another file using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.

C#

using Spire.Doc;
using Spire.Doc.Documents;

namespace RemoveEditableRanges
{
    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(@"SetEditableRange.docx");

            //Iterate through all the sections in the document
            foreach (Section section in document.Sections)
            {
                //Iterate through all the paragraphs in each section
                foreach (Paragraph paragraph in section.Body.Paragraphs)
                {
                    //Iterate through all the child objects in each paragraph
                    for (int i = 0; i < paragraph.ChildObjects.Count;)
                    {
                        DocumentObject obj = paragraph.ChildObjects[i];
                        //Find the "PermissionStart" and "PermissionEnd" tags and remove them
                        if (obj is PermissionStart || obj is PermissionEnd)
                        {
                            paragraph.ChildObjects.Remove(obj);
                        }
                        else
                        {
                            i++;
                        }
                    }
                }
            }

            //Save the result document to another file
            document.SaveToFile("RemoveEditableRange.docx", FileFormat.Docx2013);
            document.Close();
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace RemoveEditableRanges
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document()
            'Load a Word document
            document.LoadFromFile("SetEditableRange.docx")

            'Iterate through all the sections in the document
            For Each section As Section In document.Sections
                'Iterate through all the paragraphs in each section
                For Each paragraph As Paragraph In section.Body.Paragraphs
                    'Iterate through all the child objects in each paragraph
                    Dim i = 0

                    While i < paragraph.ChildObjects.Count
                        Dim obj As DocumentObject = paragraph.ChildObjects(i)
                        'Find the "PermissionStart" and "PermissionEnd" tags and remove them
                        If TypeOf obj Is PermissionStart OrElse TypeOf obj Is PermissionEnd Then
                            paragraph.ChildObjects.Remove(obj)
                        Else
                            i += 1
                        End If
                    End While
                Next
            Next

            'Save the result document to another file
            document.SaveToFile("RemoveEditableRange.docx", FileFormat.Docx2013)
            document.Close()
        End Sub
    End Class
End Namespace

When you open the result document after removing editable ranges, you will find that none of the regions are highlighted, indicating that there are no any editable ranges in the document:

Remove Editable Ranges in Word Document in C# or VB.NET

Conclusion

This article described how to protect a Word document while allowing certain areas to be edited by setting editable ranges in C# and VB.NET. Furthermore, it also demonstrated how to remove existing editable ranges from a Word document in C# and VB.NET. In addition to that, the Free Spire.Doc for .NET library also supports protecting Word documents in many other ways, you can take a look at the article C#/VB.NET: Protect Word Documents if interested.

C#/VB.NET: Compare Word Documents for Differences

Working with multiple versions of a Word document can be a daunting task, especially when it comes to identifying differences between each version. Manually reviewing the files can be very time-consuming and error-prone. To simplify this process, Microsoft Word provides users with a valuable comparison feature. This feature highlights all the differences (including differences in text, formatting, layout, tables, images, and other elements) between different versions of a document, making it easier for users to spot variations and saving them a lot of effort and time. In this article, I will explain how to programmatically compare Word documents using C# and VB.NET.

The following topics will be covered:

  • Compare Word Documents and Show Changes in a New Document
  • Compare Word Documents with Customized Options
  • Compare Word Documents and Save the Insertions and Deletions in a TXT File

Installation

To compare Word documents, this article uses Spire.Doc for .NET. You can install Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.Doc

Alternatively, you can also download the DLL files of Spire.Doc for .NET from the official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Compare Word Documents and Show Changes in a New Document in C# and VB.NET

You can use the Document.Compare(Document document, string author) method to compare two Word documents. This method will highlight the changes between the two documents using “Track Changes”. After you have reviewed the changes, you can accept or reject them according to your needs.

The following steps demonstrate how to compare two Word documents and save the comparison result to a new document:

  • Initialize an instance of the Document class.
  • Load the first Word document using the Document.LoadFromFile(string fileName) method.
  • Initialize an instance of the Document class.
  • Load the second Word document using the Document.LoadFromFile(string fileName) method.
  • Compare the two Word documents using the Document.Compare(Document document, string author) method.
  • Save the comparison result to a new document using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.

C#

using Spire.Doc;

namespace CompareWordDocuments
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc1 = new Document();
            //Load the first Word document
            doc1.LoadFromFile("File1.docx");

            //Initialize an instance of the Document class
            Document doc2 = new Document();
            //Load the second Word document
            doc2.LoadFromFile("File2.docx");

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

            //Save the result document to another file
            doc1.SaveToFile("Compare.docx", FileFormat.Docx2016);
        }
    }
}

VB.NET

Imports Spire.Doc

Namespace CompareWordDocuments
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim doc1 As Document = New Document()
            'Load the first Word document
            doc1.LoadFromFile("File1.docx")

            'Initialize an instance of the Document class
            Dim doc2 As Document = New Document()
            'Load the second Word document
            doc2.LoadFromFile("File2.docx")

            'Compare the two Word documents
            doc1.Compare(doc2, "Aiden")

            'Save the result document to another file
            doc1.SaveToFile("Compare.docx", FileFormat.Docx2016)
        End Sub
    End Class
End Namespace

Compare Word Documents with Customized Options in C# and VB.NET

You can use the Document.Compare(Document document, string author, CompareOptions options) method to compare two Word documents with customized options, for example, ignore formatting changes during comparison.

The following steps demonstrate how to compare two Word documents while ignoring formatting changes:

  • Initialize an instance of the Document class.
  • Load the first Word document using the Document.LoadFromFile(string fileName) method.
  • Initialize an instance of the Document class.
  • Load the second Word document using the Document.LoadFromFile(string fileName) method.
  • Initialize an instance of the CompareOptions class.
  • Set the CompareOptions.IgnoreFormatting property as true to ignore formatting during comparison.
  • Compare the two Word documents with the specific compare option using the Document.Compare(Document document, string author, CompareOptions options) method.
  • Save the comparison result to a new document using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.

C#

using Spire.Doc;
using Spire.Doc.Documents.Comparison;

namespace CompareWordDocumentsWithOptions
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc1 = new Document();
            //Load the first Word document
            doc1.LoadFromFile("File1.docx");

            //Initialize an instance of the Document class
            Document doc2 = new Document();
            //Load the second Word document
            doc2.LoadFromFile("File2.docx");

            //Initialize an instance of the CompareOptions class
            CompareOptions compareOptions = new CompareOptions();
            //Set to ignore formatting changes during comparison
            compareOptions.IgnoreFormatting = true;

            //Compare the two Word documents with the specific compare options
            doc1.Compare(doc2, "Aiden", compareOptions);

            //Save the result document to another file
            doc1.SaveToFile("CompareWithOptions.docx", FileFormat.Docx2016);
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents.Comparison

Namespace CompareWordDocumentsWithOptions
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim doc1 As Document = New Document()
            'Load the first Word document
            doc1.LoadFromFile("File1.docx")

            'Initialize an instance of the Document class
            Dim doc2 As Document = New Document()
            'Load the second Word document
            doc2.LoadFromFile("File2.docx")

            'Initialize an instance of the CompareOptions class
            Dim compareOptions As CompareOptions = New CompareOptions()
            'Set to ignore formatting changes during comparison
            compareOptions.IgnoreFormatting = True

            'Compare the two Word documents with the specific compare options
            doc1.Compare(doc2, "Aiden", compareOptions)

            'Save the result document to another file
            doc1.SaveToFile("CompareWithOptions.docx", FileFormat.Docx2016)
        End Sub
    End Class
End Namespace

Compare Word Documents and Save the Insertions and Deletions in a TXT File in C# and VB.NET

In addition to saving the changes into a new document, you can also save the changes, such as insertions and deletions, into a TXT file.

The following steps demonstrate how to compare two Word documents and save the insertions and deletions in a TXT file:

  • Initialize an instance of the Document class.
  • Load the first Word document using the Document.LoadFromFile(string fileName) method.
  • Initialize an instance of the Document class.
  • Load the second Word document using the Document.LoadFromFile(string fileName) method.
  • Compare the two Word documents using the Document.Compare(Document document, string author) method.
  • Initialize an instance of the DifferRevisions class and pass the first Document instance to the constructor of the class to get the changes between the two Word documents.
  • Get the insertions from the changes using the DifferRevisions.InsertRevisions property.
  • Get the deletion revisions from the changes using the DifferRevisions.DeleteRevisions property.
  • Initialize an instance of the StringBuilder class for storing the insertions and deletions.
  • Iterate through all the insertions, and append the content of each insertion into the StringBuilder instance.
  • Iterate through all the deletions, and append the content of each deletion into the StringBuilder instance.
  • Save the content in the StringBuilder instance into a TXT file.

C#

using Spire.Doc;
using Spire.Doc.Fields;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ExtractInsertionsAndDeletions
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc1 = new Document();
            //Load the first Word document
            doc1.LoadFromFile("File1.docx");

            //Initialize an instance of the Document class
            Document doc2 = new Document();
            //Load the second Word document
            doc2.LoadFromFile("File2.docx");

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

            //Get the changes between the documents
            DifferRevisions revisions = new DifferRevisions(doc1);

            //Get the insertions from the changes and save them into a list
            List<DocumentObject> insertRevisionsList = revisions.InsertRevisions;

            //Get the deletions from the changes and save them into a list
            List<DocumentObject> deleteRevisionsList = revisions.DeleteRevisions;

            int m = 0;
            int n = 0;

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

            //Iterate through the insertion revision list
            for (int i = 0; i < insertRevisionsList.Count; i++)
            {
                if (insertRevisionsList[i] is TextRange)
                {
                    m += 1;
                    //Get the content of each insertion and save it to the string builder
                    TextRange textRange = (TextRange)insertRevisionsList[i];
                    sb.AppendLine("Insertion #" + m + ":" + textRange.Text);
                }
            }

            sb.AppendLine("=====================");

            //Iterate through the deletion revision list
            for (int i = 0; i < deleteRevisionsList.Count; i++)
            {
                if (deleteRevisionsList[i] is TextRange)
                {
                    n += 1;
                    //Get the content of each deletion and save it to the string builder
                    TextRange textRange = (TextRange)deleteRevisionsList[i];
                    sb.AppendLine("Deletion #" + n + ":" + textRange.Text);
                }
            }

            //Save the content in the string builder into a .txt file
            File.WriteAllText("InsertionsAndDeletions.txt", sb.ToString());
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Fields
Imports System.Collections.Generic
Imports System.IO
Imports System.Text

Namespace ExtractInsertionsAndDeletions
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim doc1 As Document = New Document()
            'Load the first Word document
            doc1.LoadFromFile("File1.docx")

            'Initialize an instance of the Document class
            Dim doc2 As Document = New Document()
            'Load the second Word document
            doc2.LoadFromFile("File2.docx")

            'Compare the two Word documents
            doc1.Compare(doc2, "Aiden")

            'Get the changes between the documents
            Dim revisions As DifferRevisions = New DifferRevisions(doc1)

            'Get the insertions from the changes and save them into a list
            Dim insertRevisionsList As List(Of DocumentObject) = revisions.InsertRevisions

            'Get the deletions from the changes and save them into a list
            Dim deleteRevisionsList As List(Of DocumentObject) = revisions.DeleteRevisions

            Dim m = 0
            Dim n = 0

            'Initialize an instance of the StringBuilder class
            Dim sb As StringBuilder = New StringBuilder()

            'Iterate through the insertion revision list
            For i = 0 To insertRevisionsList.Count - 1
                If TypeOf insertRevisionsList(i) Is TextRange Then
                    m += 1
                    'Get the content of each insertion and save it to the string builder
                    Dim textRange As TextRange = CType(insertRevisionsList(i), TextRange)
                    sb.AppendLine("Insertion #" & m.ToString() & ":" & textRange.Text.ToString())
                End If
            Next

            sb.AppendLine("=====================")

            'Iterate through the deletion revision list
            For i = 0 To deleteRevisionsList.Count - 1
                If TypeOf deleteRevisionsList(i) Is TextRange Then
                    n += 1
                    'Get the content of each deletion and save it to the string builder
                    Dim textRange As TextRange = CType(deleteRevisionsList(i), TextRange)
                    sb.AppendLine("Deletion #" & n.ToString() & ":" & textRange.Text.ToString())
                End If
            Next

            'Save the content in the string builder into a .txt file
            Call File.WriteAllText("InsertionsAndDeletions.txt", sb.ToString())
        End Sub
    End Class
End Namespace

C#/VB.NET: Extract or Read Text from Word Documents

Text is the main element of a Word document. In some cases, you might need to extract text content from Word documents to perform text analysis or to use it elsewhere. In this article, I will demonstrate how to extract text from Word documents in C# and VB.NET.

Installation

To extract text from Word documents, this article uses Spire.Doc for .NET. You can install Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.Doc

Alternatively, you can also download the DLL files of Spire.Doc for .NET from the official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Extract Text from Word Documents in C# and VB.NET

Spire.Doc mainly provides two approaches to extracting text from a Word document. One is to directly get the text from the document using the Document.GetText() method, and the other is to iterate through all sections and paragraphs in the document and then extract text from each paragraph through Paragraph.Text property. The latter approach is more flexible than the former one since it allows you to extract text from a specific section or paragraph.

Approach 1 – Extract Text from a Word Document using Document.GetText() Method

The steps are as follows:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the text content from the document using Document.GetText() method.
  • Write the text content into a txt file using File.WriteAllText() method.

C#

using Spire.Doc;

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

            //Get the text content from the document
            string content = doc.GetText();

            //Write the text content into a txt file
            File.WriteAllText("Extract1.txt", content);
        }
    }
}

VB.NET

Imports Spire.Doc

Namespace ExtractTextFromWord
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim doc As Document = New Document()
            'Load a Word document
            doc.LoadFromFile("Input.docx")

            'Get the text content from the document
            Dim content As String = doc.GetText()

            'Write the text content into a txt file
            File.WriteAllText("Extract1.txt", content)
        End Sub
    End Class
End Namespace

Approach 2 – Extract Text from a Word Document by Iterating Through Sections and Paragraphs

The steps are as follows:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Initialize an instance of the StringBuilder class.
  • Iterate through all sections in the document.
  • Iterate through all paragraphs in each section.
  • Get text from each paragraph through Paragraph.Text property and save it to the string builder.
  • Write the text content into a txt file using File.WriteAllText() method.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using System.Text;

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

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

            //Iterate through all sections in the document        
            for (int i = 0; i < doc.Sections.Count; i++)
            {
                Section section = doc.Sections[i];
                //Iterate through all paragraphs in each section    
                for (int j = 0; j < section.Paragraphs.Count; j++)
                {
                    Paragraph paragraph = section.Paragraphs[j];
                    //Get text from each paragraph and save it to the string builder
                    sb.AppendLine(paragraph.Text);
                }
            }

            //Write the text in the string builder into a txt file
            File.WriteAllText("Extract2.txt", sb.ToString());
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Text

Namespace ExtractTextFromWord
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim doc As Document = New Document()
            'Load a Word document
            doc.LoadFromFile("Input.docx")

            'Initialize an instance of the StringBuilder class
            Dim sb As StringBuilder = New StringBuilder()

            'Iterate through all sections in the document        
            For i As Integer = 0 To doc.Sections.Count - 1
                Dim section As Section = doc.Sections(i)
                'Iterate through all paragraphs in each section    
                For j As Integer = 0 To section.Paragraphs.Count - 1
                    Dim paragraph As Paragraph = section.Paragraphs(j)
                    'Get text from each paragraph and save it to the string builder
                    sb.AppendLine(paragraph.Text)
                Next
            Next

            'Write the text in the string builder into a txt file
            File.WriteAllText("Extract2.txt", sb.ToString())
        End Sub
    End Class
End Namespace

C#/VB.NET: Insert or Read Tables in Word Documents

Tables are very useful for presenting data. They can show complex information to readers in a way that is easy to read and understand. When generating a Word document, you may need to insert a table to organize your data. In certain cases, you may also want to read data from an existing table in a Word document. In this article, I will demonstrate how to insert or read tables in Word documents using C# and VB.NET.

Installation

To create or read tables in Word documents, this article uses Free Spire.Doc for .NET. You can install Free Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package FreeSpire.Doc

Alternatively, you can also download the DLL files of Free Spire.Doc for .NET from the official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Create Table in Word Document in C# and VB.NET

You can use the Section.AddTable() method to add a table to a specific section of a Word document. The following are the detailed steps:

  • Initialize an instance of the Document class.
  • Add a section to the document using Document.AddSection() method.
  • Define the data for the header row and the remaining rows of the table and store them in a one-dimensional string array and a two-dimensional string array respectively.
  • Add a table to the section using Section.AddTable() method and specify the number of table rows and columns using Table.ResetCells(int, int) method.
  • Get the first row of the table through Table.Rows[int] property and set it as the header row through TableRow.IsHeader property.
  • Iterate through the one-dimensional string array, assign the data in the array to the header row and set text formatting.
  • Iterate through the two-dimensional string array, assign the data in the array to the remaining rows and set text formatting.
  • Save the result document using Document.SaveToFile() method.

C#

using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace InsertTable
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc = new Document();

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

            //Set page margins for the section (top (1 in), bottom (1 in), left (1.25 in), right (1.25 in))
            section.PageSetup.Margins.Top = 72f;
            section.PageSetup.Margins.Bottom = 72f;
            section.PageSetup.Margins.Left = 90f;
            section.PageSetup.Margins.Right = 90f;

            //Add a paragraph to the section
            Paragraph para = section.AddParagraph();
            //Set text alignment
            para.Format.HorizontalAlignment = HorizontalAlignment.Center;
            //Add text to the paragraph
            TextRange txtRange = para.AppendText("Employee List");
            txtRange.CharacterFormat.FontName = "Calibri";
            txtRange.CharacterFormat.FontSize = 16;           
            txtRange.CharacterFormat.Bold = true;

            //Define table data
            string[] header = { "Employee#", "Name", "Department" };
            string[][] data =
                    {
                        new string[]{"93775", "John", "Finance"},
                        new string[]{"38295", "Jane", "IT"},
                        new string[]{"83864", "Brain", "Marketing"},
                        new string[]{"39801", "Sandra", "R&D"},
                };

            //Add a table to the section
            Table table = section.AddTable(true);
            //Specify the number of rows and columns for the table
            table.ResetCells(data.Length + 1, header.Length);

            //Set the first row as table header
            TableRow headerRow = table.Rows[0];
            headerRow.IsHeader = true;
            //Set the height and background color of the header row
            headerRow.Height = 23;
            headerRow.RowFormat.BackColor = Color.FromArgb(142, 170, 219);

            //Add data to the header row
            for (int i = 0; i < header.Length; i++)
            {
                //Add a paragraph to each cell of the header row
                para = headerRow.Cells[i].AddParagraph();
                //Set text alignment
                headerRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                para.Format.HorizontalAlignment = HorizontalAlignment.Center;
                //Add data to the paragraph and set text format
                txtRange = para.AppendText(header[i]);
                txtRange.CharacterFormat.FontName = "Calibri";
                txtRange.CharacterFormat.FontSize = 14;
                txtRange.CharacterFormat.TextColor = Color.White;
                txtRange.CharacterFormat.Bold = true;
            }

            //Add data to the remaining rows
            for (int r = 0; r < data.Length; r++)
            {
                TableRow dataRow = table.Rows[r + 1];
                dataRow.Height = 20;
                for (int c = 0; c < data[r].Length; c++)
                {
                    //Add a paragraph to each cell of the rest of the rows
                    para = dataRow.Cells[c].AddParagraph();
                    //Set text alignment
                    para.Format.HorizontalAlignment = HorizontalAlignment.Center;
                    dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    //Add data to the paragraph and set text format
                    txtRange = para.AppendText(data[r][c]);
                    txtRange.CharacterFormat.FontName = "Calibri";
                    txtRange.CharacterFormat.FontSize = 11;
                }
            }

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

VB.NET

Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields

Namespace InsertTable
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim doc As Document = New Document()

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

            'Set page margins for the section (top (1 in), bottom (1 in), left (1.25 in), right (1.25 in))
            section.PageSetup.Margins.Top = 72F
            section.PageSetup.Margins.Bottom = 72F
            section.PageSetup.Margins.Left = 90F
            section.PageSetup.Margins.Right = 90F

            'Add a paragraph to the section
            Dim para As Paragraph = section.AddParagraph()
            'Set text alignment
            para.Format.HorizontalAlignment = HorizontalAlignment.Center
            'Add text to the paragraph
            Dim txtRange As TextRange = para.AppendText("Employee List")
            txtRange.CharacterFormat.FontName = "Calibri"
            txtRange.CharacterFormat.FontSize = 16
            txtRange.CharacterFormat.Bold = True

            'Define table data
            Dim header = {"Employee#", "Name", "Department"}
            Dim data = {New String() {"93775", "John", "Finance"}, New String() {"38295", "Jane", "IT"}, New String() {"83864", "Brain", "Marketing"}, New String() {"39801", "Sandra", "R&D"}}

            'Add a table to the section
            Dim table As Table = section.AddTable(True)
            'Specify the number of rows and columns for the table
            table.ResetCells(data.Length + 1, header.Length)

            'Set the first row as table header
            Dim headerRow As TableRow = table.Rows(0)
            headerRow.IsHeader = True
            'Set the height and background color of the header row
            headerRow.Height = 23
            headerRow.RowFormat.BackColor = Color.FromArgb(142, 170, 219)

            'Add data to the header row
            For i = 0 To header.Length - 1
                'Add a paragraph to each cell of the header row
                para = headerRow.Cells(i).AddParagraph()
                'Set text alignment
                headerRow.Cells(i).CellFormat.VerticalAlignment = VerticalAlignment.Middle
                para.Format.HorizontalAlignment = HorizontalAlignment.Center
                'Add data to the paragraph and set text format
                txtRange = para.AppendText(header(i))
                txtRange.CharacterFormat.FontName = "Calibri"
                txtRange.CharacterFormat.FontSize = 14
                txtRange.CharacterFormat.TextColor = Color.White
                txtRange.CharacterFormat.Bold = True
            Next

            'Add data to the remaining rows
            For r = 0 To data.Length - 1
                Dim dataRow As TableRow = table.Rows(r + 1)
                dataRow.Height = 20
                For c = 0 To data(r).Length - 1
                    'Add a paragraph to each cell of the rest of the rows
                    para = dataRow.Cells(c).AddParagraph()
                    'Set text alignment
                    para.Format.HorizontalAlignment = HorizontalAlignment.Center
                    dataRow.Cells(c).CellFormat.VerticalAlignment = VerticalAlignment.Middle
                    'Add data to the paragraph and set text format
                    txtRange = para.AppendText(data(r)(c))
                    txtRange.CharacterFormat.FontName = "Calibri"
                    txtRange.CharacterFormat.FontSize = 11
                Next
            Next

            'Save the result document
            doc.SaveToFile("InsertTable.docx", FileFormat.Docx2013)
        End Sub
    End Class
End Namespace
Insert Table in Word using C# and VB.NET

The above example explains how to create a table with a predefined number of rows and columns. Besides that, you can also create a table by dynamically adding rows and cells as shown in the following example.

C#

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

namespace DynamicTable
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc = new Document();

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

            //Set page margins for the section (top(1 in), bottom(1 in), left(1.25 in), right(1.25 in))
            section.PageSetup.Margins.Top = 72f;
            section.PageSetup.Margins.Bottom = 72f;
            section.PageSetup.Margins.Left = 90f;
            section.PageSetup.Margins.Right = 90f;

            //Add a table to the section
            Table table = section.AddTable();

            //Dynamically add rows and cells to the table
            TableRow row = table.AddRow();
            TableCell cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            TextRange txtRange = cell.AddParagraph().AppendText("Product");
            txtRange.CharacterFormat.FontSize = 13;
            txtRange.CharacterFormat.Bold = true;
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            txtRange = cell.AddParagraph().AppendText("Unit Price");
            txtRange.CharacterFormat.FontSize = 13;
            txtRange.CharacterFormat.Bold = true;

            row = table.AddRow(true, false);
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("Monitor");
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("$500");

            row = table.AddRow(true, false);
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("Keyboard");
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("$80");

            row = table.AddRow(true, false);
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("CPU Coolers");
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("$20");

            row = table.AddRow(true, false);
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("Mice");
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("$120");

            //Apply table style
            table.ApplyStyle(DefaultTableStyle.MediumGrid1Accent5);

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

VB.NET

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

Namespace DynamicTable
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim doc As Document = New Document()

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

            'Set page margins for the section (top(1 in), bottom(1 in), left(1.25 in), right(1.25 in))
            section.PageSetup.Margins.Top = 72F
            section.PageSetup.Margins.Bottom = 72F
            section.PageSetup.Margins.Left = 90F
            section.PageSetup.Margins.Right = 90F

            'Add a table to the section
            Dim table As Table = section.AddTable()

            'Dynamically add rows and cells to the table
            Dim row As TableRow = table.AddRow()
            Dim cell As TableCell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            Dim txtRange As TextRange = cell.AddParagraph().AppendText("Product")
            txtRange.CharacterFormat.FontSize = 13
            txtRange.CharacterFormat.Bold = True
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            txtRange = cell.AddParagraph().AppendText("Unit Price")
            txtRange.CharacterFormat.FontSize = 13
            txtRange.CharacterFormat.Bold = True

            row = table.AddRow(True, False)
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("Monitor")
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("$500")

            row = table.AddRow(True, False)
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("Keyboard")
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("$80")

            row = table.AddRow(True, False)
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("CPU Coolers")
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("$20")

            row = table.AddRow(True, False)
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("Mice")
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("$120")

            'Apply table style
            table.ApplyStyle(DefaultTableStyle.MediumGrid1Accent5)

            'Save the result document
            doc.SaveToFile("DynamicTable.docx", FileFormat.Docx2013)
        End Sub
    End Class
End Namespace
Dynamically Create Table in Word using C# and VB.NET

Read Table in Word Document in C# and VB.NET

To read data from a table in a Word document, you need to iterate through all rows in the table, all cells in each row, then extract text from each cell. The following are the detailed steps:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get a specific section by its index through Document.Sections[int] property.
  • Get a specific table in the section by its index through Section.Tables[int] property.
  • Initialize an instance of the StringBuilder class.
  • Iterate through all rows in the table.
  • Iterate through all cells in each row.
  • Iterate through all paragraphs in each cell.
  • Get the text from each paragraph through Paragraph.Text property and save the result into the StringBuilder using StringBuilder.Append() method.
  • Write the text in the StringBuilder into a text file using File.WriteAllText() method.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using System.IO;
using System.Text;

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

            //Get the first section
            Section section = document.Sections[0];

            //Get the first table in the first section
            Table table = section.Tables[0] as Table;

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

            //Iterate through all rows in the table
            for (int i = 0; i < table.Rows.Count; i++)
            {
                TableRow row = table.Rows[i];
                //Iterate through all cells in each row
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    TableCell cell = row.Cells[j];
                    //Iterate through all paragraphs in each cell
                    for (int p = 0; p < cell.Paragraphs.Count; p++)
                    {
                        //Extract text from each paragraph
                        Paragraph paragraph = cell.Paragraphs[p];
                        string text = paragraph.Text;
                        //Append the text to the StringBuilder
                        sb.Append(text + " | ");
                    }
                }
                sb.Append("\r\n");
            }

            File.WriteAllText("ReadTable.txt", sb.ToString());
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.IO
Imports System.Text

Namespace ReadTable
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document()
            'Load a Word document
            document.LoadFromFile("InsertTable.docx")

            'Get the first section
            Dim section As Section = document.Sections(0)

            'Get the first table in the first section
            Dim table As Table = TryCast(section.Tables(0), Table)

            'Initialize an instance of the StringBuilder class
            Dim sb As StringBuilder = New StringBuilder()

            'Iterate through all rows in the table
            For i As Integer = 0 To table.Rows.Count - 1
                Dim row As TableRow = table.Rows(i)
                'Iterate through all cells in each row
                For j As Integer = 0 To row.Cells.Count - 1
                    Dim cell As TableCell = row.Cells(j)
                    'Iterate through all paragraphs in each cell
                    For p As Integer = 0 To cell.Paragraphs.Count - 1
                        'Extract text from each paragraph
                        Dim paragraph As Paragraph = cell.Paragraphs(p)
                        Dim text As String = paragraph.Text
                        'Append the text to the StringBuilder
                        sb.Append(text & " | ")
                    Next
                Next
                sb.Append(vbCrLf)
            Next

            Call File.WriteAllText("ReadTable.txt", sb.ToString())
        End Sub
    End Class
End Namespace
Read Table in Word using C# and VB.NET

C#/VB.NET: Convert Word Doc or Docx to PDF

Word and PDF are two of the most commonly used file formats today. In some cases, you may need to convert Word documents to PDF in order to preserve the document layout while opening them on different systems or devices. In this article, I will demonstrate how to convert Word documents to PDF, PDF/A and password protected PDF using C# and VB.NET.

Installation

To convert Word documents to PDF, this article uses Spire.Doc for .NET. You can install Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.Doc

Alternatively, you can also download the DLL files of Spire.Doc for .NET from the official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Convert Word to PDF in C# and VB.NET

Spire.Doc offers a Document.SaveToFile(string, FileFormat) method which allows you to convert a Word document to PDF along with lots of other popular file formats.  

The following steps demonstrate how to convert a Word document to PDF:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile(string) method.
  • Save the Word document to PDF using Document.SaveToFile(string, FileFormat) method.

C#

using Spire.Doc;

namespace ConvertWordToPDF
{
    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("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            //Save the document to PDF
            document.SaveToFile("WordToPdf.pdf", FileFormat.PDF);
        }
    }
}

VB.NET

Imports Spire.Doc

Namespace ConvertWordToPDF
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document()
            'Load a Word document
            document.LoadFromFile("C:\Users\Administrator\Desktop\Sample.docx")

            'Save the document to PDF
            document.SaveToFile("WordToPdf.pdf", FileFormat.PDF)
        End Sub
    End Class
End Namespace

Convert Word to PDF/A in C# and VB.NET

Sometimes, you may need to convert Word to PDF/A for long document archiving purposes. Spire.Doc allows you to covert a Word document to the following list of PDF/A documents:

  • PDF/A-1a
  • PDF/A-1b
  • PDF/A-2a
  • PDF/A-2b
  • PDF/A-3a
  • PDF/A-3b
  • PDF/X-1a:2001

The following steps demonstrate how to convert a Word document to PDF/A:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile(string) method.
  • Initialize an instance of the ToPdfParameterList class.
  • Specify the conformance level of the converted PDF through ToPdfParameterList.PdfConformanceLevel property.
  • Save the Word document to PDF/A using Document.SaveToFile(string, ToPdfParameterList) method.

C#

using Spire.Doc;

namespace ConvertWordToPDFA
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document document = new Document(false);
            //Load a Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            //Initialize an instance of the ToPdfParameterList class
            ToPdfParameterList parameterList = new ToPdfParameterList();
            //Specify the conformance level of the converted pdf
            parameterList.PdfConformanceLevel = Spire.Pdf.PdfConformanceLevel.Pdf_A1A;

            //Save the Word document to PDF/A
            document.SaveToFile("WordToPdfA.pdf", parameterList);
        }
    }
}

VB.NET

Imports Spire.Doc

Namespace ConvertWordToPDFA
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document(False)
            'Load a Word document
            document.LoadFromFile("C:\Users\Administrator\Desktop\Sample.docx")

            'Initialize an instance of the ToPdfParameterList class
            Dim parameterList As ToPdfParameterList = New ToPdfParameterList()
            'Specify the conformance level of the converted pdf
            parameterList.PdfConformanceLevel = Spire.Pdf.PdfConformanceLevel.Pdf_A1A

            'Save the Word document to PDF/A
            document.SaveToFile("WordToPdfA.pdf", parameterList)
        End Sub
    End Class
End Namespace

Convert Word to Password Protected PDF in C# and VB.NET

If you want to prevent the converted PDF document from unauthorized viewing, you can encrypt it with a password during the conversion. The following are the detailed steps:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile(string) method.
  • Initialize an instance of the ToPdfParameterList class.
  • Set open password for the converted PDF using ToPdfParameterList.PdfSecurity.Encrypt(string) method.
  • Save the Word document to password protected PDF using Document.SaveToFile(string, ToPdfParameterList) method.

C#

using Spire.Doc;

namespace ConvertWordToEncryptedPDF
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document document = new Document(false);
            //Load a Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            //Initialize an instance of the ToPdfParameterList class
            ToPdfParameterList parameterList = new ToPdfParameterList();
            //Set the open password of the converted pdf
            parameterList.PdfSecurity.Encrypt("password");

            //Save the Word document to password protected PDF
            document.SaveToFile("WordToPassWordProtectedPdf.pdf", parameterList);
        }
    }
}

VB.NET

Imports Spire.Doc

Namespace ConvertWordToEncryptedPDF
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document(False)
            'Load a Word document
            document.LoadFromFile("C:\Users\Administrator\Desktop\Sample.docx")

            'Initialize an instance of the ToPdfParameterList class
            Dim parameterList As ToPdfParameterList = New ToPdfParameterList()
            'Set the open password of the converted pdf
            parameterList.PdfSecurity.Encrypt("password")

            'Save the Word document to password protected PDF
            document.SaveToFile("WordToPassWordProtectedPdf.pdf", parameterList)
        End Sub
    End Class
End Namespace

C#/VB.NET: Highlight Text or Get Highlighted Text in Word Documents

Highlighting text is a great way to make certain text stand out in a document. If you want to quickly draw your readers’ attention to some important information in your Word document, you can highlight it with a bright color. Sometimes, you may also want to find the text highlighted with a specific color in a Word document. In this article, I will demonstrate how to highlight text or get highlighted text in Word documents using C# and VB.NET.

  • Highlight The First Occurrence of a Specific Text in a Word Document
  • Highlight All Occurrences of a Specific Text in a Word Document
  • Get Highlighted Text in a Word Document

Installation

To highlight or get highlighted text in Word documents, this article uses Free Spire.Doc for .NET. You can install Free Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package FreeSpire.Doc

Alternatively, you can also download the DLL files of Free Spire.Doc for .NET from the official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Highlight The First Occurrence of a Specific Text in a Word Document using C# and VB.NET

The following steps demonstrate how to highlight the first occurrence of a specific text in a Word document:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Find the first occurrence of a specific text using Document.FindString() method.
  • Get the found text as a single text range using TextSelection.GetAsOneRange() method.
  • Set a highlight color for the text range through TextRange.CharacterFormat.HighlightColor property.
  • Save the result document using Document.SaveToFile() method.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace HighlightText
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();
            //Load a Word document 
            document.LoadFromFile("Input1.docx");

            //Find the first occurrence of a specific text
            TextSelection seletion = document.FindString("World Cup", false, true);

            //Get the found text as a single text range
            TextRange textRange = seletion.GetAsOneRange();
            //Set a highlight color
            textRange.CharacterFormat.HighlightColor = Color.Yellow;

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

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports System.Drawing

Namespace HighlightText
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Document instance
            Dim document As Document = New Document()
            'Load a Word document 
            document.LoadFromFile("Input1.docx")

            'Find the first occurrence of a specific text
            Dim seletion As TextSelection = document.FindString("World Cup", False, True)

            'Get the found text as a single text range
            Dim textRange As TextRange = seletion.GetAsOneRange()
            'Set a highlight color
            textRange.CharacterFormat.HighlightColor = Color.Yellow

            'Save the result document
            document.SaveToFile("HighlightText.docx", FileFormat.Docx2013)
        End Sub
    End Class
End Namespace
Highlight the first occurrence of a specific text in Word using C# or VB.NET

Highlight All Occurrences of a Specific Text in a Word Document using C# and VB.NET

The following steps demonstrate how to highlight all the occurrences of a specific text in a Word document:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Find all the occurrences of a specific text using Document.FindAllString() method.
  • Loop through the found text.
  • Get each text as a single text range using TextSelection.GetAsOneRange() method.
  • Set a highlight color for the text range through TextRange.CharacterFormat.HighlightColor property.
  • Save the result document using Document.SaveToFile() method.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace HighlightAllMatchedText
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();
            //Load a Word document 
            document.LoadFromFile("Input1.docx");

            //Find all occurrences of a specific text
            TextSelection[] text = document.FindAllString("World Cup", false, true);

            //Loop through the found text
            foreach (TextSelection seletion in text)
            {
                //Get each text as a single text range
                TextRange textRange = seletion.GetAsOneRange();
                //Set a highlight color
                textRange.CharacterFormat.HighlightColor = Color.Yellow;
            }

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

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports System.Drawing

Namespace HighlightAllMatchedText
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Document instance
            Dim document As Document = New Document()
            'Load a Word document 
            document.LoadFromFile("Input1.docx")

            ' Find all occurrences of a specific text
            Dim text As TextSelection() = document.FindAllString("World Cup", False, True)

            'Loop through the found text
            For Each seletion As TextSelection In text
                'Get each text as a single text range
                Dim textRange As TextRange = seletion.GetAsOneRange()
                'Set a highlight color
                textRange.CharacterFormat.HighlightColor = Color.Yellow
            Next

            'Save the result document
            document.SaveToFile("HighlightAllMatchedText.docx", FileFormat.Docx2013)
        End Sub
    End Class
End Namespace
Highlight all occurrences of a specific text in Word using C# or VB.NET

Get Highlighted Text in a Word Document using C# and VB.NET

The following steps demonstrate how to get all the text highlighted with a specific color in a Word document:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Iterate through all sections in the document.
  • Iterate through all paragraphs in each section.
  • Iterate through all child objects in each paragraph.
  • Check if the current child object is of TextRange type.
  • If the result is true, typecast the child object as TextRange.
  • Check if the text range is highlighted with a specific color through TextRange.CharacterFormat.HighlightColor property.
  • If the result is true, get the text through TextRange.Text property.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;
using System.Drawing;

namespace GetHighlightedText
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile("Input2.docx");

            //Loop through all sections in the document
            foreach (Section section in document.Sections)
            {
                //Loop through all paragraphs in each section
                foreach (Paragraph paragraph in section.Body.Paragraphs)
                {
                    //Loop through all child objects in each paragraph
                    foreach (DocumentObject obj in paragraph.ChildObjects)
                    {
                        //Check if the current child object is of TextRange type
                        if (obj is TextRange)
                        {
                            TextRange textRange = obj as TextRange;
                            //Check if the text range is highlighted with a specific color
                            if (textRange.CharacterFormat.HighlightColor == Color.Yellow)
                            {
                                //Get the highlighted text
                                string highlightedText = textRange.Text;
                                Console.WriteLine(highlightedText+"\n");
                            }
                        }
                    }
                }
            }

            Console.ReadKey();
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports System.Drawing

Namespace GetHighlightedText
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Document instance
            Dim document As Document = New Document()
            'Load a Word document
            document.LoadFromFile("Input2.docx")

            'Loop through all sections in the document
            For Each section As Section In document.Sections
                'Loop through all paragraphs in each section
                For Each paragraph As Paragraph In section.Body.Paragraphs
                    'Loop through all child objects in each paragraph
                    For Each obj As DocumentObject In paragraph.ChildObjects
                        'Check if the current child object is of TextRange type
                        If TypeOf obj Is TextRange Then
                            Dim textRange As TextRange = TryCast(obj, TextRange)
                            'Check if the text range is highlighted with a specific color
                            If textRange.CharacterFormat.HighlightColor = Color.Yellow Then
                                'Get the highlighted text
                                Dim highlightedText As String = textRange.Text
                                Console.WriteLine(highlightedText & vbLf)
                            End If
                        End If
                    Next
                Next
            Next

            Console.ReadKey()
        End Sub
    End Class
End Namespace
Get highlighted text in Word using C# or VB.NET

C#/VB.NET: Add Background Color or Picture to Word Documents

Sometimes, a Word document with a blank background may look tedious to readers. Adding a background color or picture to the document can help you make it more vivid and appealing. In this article, I will demonstrate how to add background color or picture to Word documents in C# and VB.NET.

  • Add a Background Color to a Word Document
  • Add a Gradient Background to a Word Document
  • Add a Background Picture to a Word Document

Installation

To add background color or picture to Word documents, this article uses Free Spire.Doc for .NET. You can install Free Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package FreeSpire.Doc

Alternatively, you can also download the DLL files of Free Spire.Doc for .NET from the official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Add a Background Color to a Word Document in C# and VB.NET

The following are the steps to add a background color to a Word document:

  • Initialize an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Set the background type as color through Document.Background.Type property.
  • Set the background color through Document.Background.Color property.
  • Save the result document using Document.SaveToFile() method.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace SetBackgroundColor
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document doc = new Document();
            //Load a Word document
            doc.LoadFromFile("Sample.docx");

            //Set the background type as color
            doc.Background.Type = BackgroundType.Color;
            //Set the background color
            doc.Background.Color = Color.LightSeaGreen;

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

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing

Namespace SetBackgroundColor
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Document instance
            Dim doc As Document = New Document()
            'Load a Word document
            doc.LoadFromFile("Sample.docx")

            'Set the background type as color
            doc.Background.Type = BackgroundType.Color
            'Set the background color
            doc.Background.Color = Color.LightSeaGreen

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

Add a Gradient Background to a Word Document in C# and VB.NET

The following are the steps to add a gradient background to a Word document:

  • Initialize an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the document background through Document.Background property.
  • Set the background type as gradient through Background.Type property.
  • Set two gradient colors through Background.Gradient.Color1 and Background.Gradient.Color2 properties.
  • Set shading variant through Background.Gradient.ShadingVariant property.
  • Set shading style through Background.Gradient.ShadingStyle property.
  • Save the result document using Document.SaveToFile() method.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace SetGradientBackground
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document doc = new Document();
            //Load a Word document
            doc.LoadFromFile("Sample.docx");

            //Get the document background
            Background background = doc.Background;

            //Set the background type as Gradient
            background.Type = BackgroundType.Gradient;
            
            //Set two gradient colors
            background.Gradient.Color1 = Color.LightSkyBlue;
            background.Gradient.Color2 = Color.PaleGreen;

            //Set shading variant
            background.Gradient.ShadingVariant = GradientShadingVariant.ShadingMiddle;
            //Set shading style
            background.Gradient.ShadingStyle = GradientShadingStyle.FromCenter;

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

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing

Namespace SetGradientBackground
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Document instance
            Dim doc As Document = New Document()
            'Load a Word document
            doc.LoadFromFile("Sample.docx")

            'Get the document background
            Dim background As Background = doc.Background

            'Set the background type as Gradient
            background.Type = BackgroundType.Gradient

            'Set two gradient colors
            background.Gradient.Color1 = Color.LightSkyBlue
            background.Gradient.Color2 = Color.PaleGreen

            'Set shading variant
            background.Gradient.ShadingVariant = GradientShadingVariant.ShadingMiddle
            'Set shading style
            background.Gradient.ShadingStyle = GradientShadingStyle.FromCenter

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

Add a Background Picture to a Word Document in C# and VB.NET

The following are the steps to add a background picture to a Word document:

  • Initialize an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the document background through Document.Background property.
  • Set the background type as picture through Background.Type property.
  • Set the background picture through Background.Picture property.
  • Save the result document through Document.SaveToFile() method.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace SetBackgroundPicture
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document doc = new Document();
            //Load a Word document
            doc.LoadFromFile("Sample.docx");

            //Get the document background
            Background background = doc.Background;

            //Set the background type as picture
            background.Type = BackgroundType.Picture;
            //Set background picture
            background.Picture = Image.FromFile("bgd.png");

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

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace SetBackgroundPicture
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Document instance
            Dim doc As Document = New Document()
            'Load a Word document
            doc.LoadFromFile("Sample.docx")

            'Get the document background
            Dim background As Background = doc.Background

            'Set the background type as picture
            background.Type = BackgroundType.Picture
            'Set background picture
            background.Picture = Image.FromFile("bgd.png")

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

C#/VB.NET: Count the Number of Pages, Words, Characters, Paragraphs and Lines in Word Documents

When writing an academic document, you might want to check the number of words in the document to make sure it meets a certain length requirement. Microsoft Word includes a built-in function to count words within a document, and it also provides the ability to count other elements like pages, characters, paragraphs and lines. In this article, I will explain how to programmatically count the number of pages, words, characters, paragraphs and lines in Word documents using C# and VB.NET.

Installation

To count the pages, words, characters, paragraphs and lines in Word documents, this article uses Spire.Doc for .NET, which is a multi-functional library designed for generating, editing, converting and printing Word documents within .NET applications.

You can install Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.Doc

Alternatively, you can also download the DLL files of Spire.Doc for .NET from the official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Count the Number of Pages, Words, Characters, Paragraphs and Lines in Word Documents using C# and VB.NET

The following are the main steps to count the number of pages, words, characters, paragraphs and lines in a Word document:

  • Create an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Create an instance of StringBuilder class.
  • Use Document.BuiltinDocumentProperties.PageCount, Document.BuiltinDocumentProperties.WordCount, Document.BuiltinDocumentProperties.CharCount, Document.BuiltinDocumentProperties.CharCountWithSpace, Document.BuiltinDocumentProperties.ParagraphCount, and Document.BuiltinDocumentProperties.LinesCount properties to get the count of pages, words, characters, paragraphs and lines in the document, and append the results to the string builder.
  • Save the data in the string builder to a .txt file using File.WriteAllText() method.

C#

using Spire.Doc;
using System.IO;
using System.Text;

namespace CountWordsInWord
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create an instance of Document class
            Document doc = new Document();
            //Load a Word document
            doc.LoadFromFile("Sample.docx");

            //Create an instance of StringBuilder class
            StringBuilder sb = new StringBuilder();

            //Count the number of pages, words, characters, paragraphs and lines in the document, and append the results to the string builder
            sb.AppendLine("Pages: " + doc.BuiltinDocumentProperties.PageCount);
            sb.AppendLine("Words: " + doc.BuiltinDocumentProperties.WordCount);
            sb.AppendLine("Characters with No Spaces: " + doc.BuiltinDocumentProperties.CharCount);
            sb.AppendLine("Characters with Spaces: " + doc.BuiltinDocumentProperties.CharCountWithSpace);          
            sb.AppendLine("Paragraphs: " + doc.BuiltinDocumentProperties.ParagraphCount);
            sb.AppendLine("Lines: " + doc.BuiltinDocumentProperties.LinesCount);


            //Save the data in the string builder to a .txt file
            File.WriteAllText("WordCount.txt", sb.ToString());
        }
    }
}

VB.NET

Imports Spire.Doc
Imports System.IO
Imports System.Text

Namespace CountWordsInWord
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create an instance of Document class
            Dim doc As Document = New Document()
            'Load a Word document
            doc.LoadFromFile("Sample.docx")

            'Create an instance of StringBuilder class
            Dim sb As StringBuilder = New StringBuilder()

            'Count the number of pages, words, characters, paragraphs and lines in the document, and append the results to the string builder
            sb.AppendLine("Pages: " & doc.BuiltinDocumentProperties.PageCount)
            sb.AppendLine("Words: " & doc.BuiltinDocumentProperties.WordCount)
            sb.AppendLine("Characters with No Spaces: " & doc.BuiltinDocumentProperties.CharCount)
            sb.AppendLine("Characters with Spaces: " & doc.BuiltinDocumentProperties.CharCountWithSpace)
            sb.AppendLine("Paragraphs: " & doc.BuiltinDocumentProperties.ParagraphCount)
            sb.AppendLine("Lines: " & doc.BuiltinDocumentProperties.LinesCount)

            'Save the data in the string builder to a .txt file
            Call File.WriteAllText("WordCount.txt", sb.ToString())
        End Sub
    End Class
End Namespace
Count the Number of Pages, Words, Characters, Paragraphs and Lines in Word Documents using C# and VB.NET

C# and VB.NET – Remove Macros from Word Documents

A macro is a series of commands that can be used to automate repetitive tasks. You can create and run macros in Word documents to make your document-processing tasks more efficient. However, in some other cases, you may need to remove macros from Word documents. For example, when you need to send a Word document with macros to someone who requires a macro-free file. In this article, I will demonstrate how to remove macros from Word documents in C# and VB.NET.

Installation

To remove macros from Word documents, this article uses Free Spire.Doc for .NET. You can install it via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package FreeSpire.Doc

Alternatively, you can also download the API from this website and install it, then add the DLL files under the Bin folder to your project as references.

Remove Macros from a Word Document in C# and VB.NET

Free Spire.Doc provides a Document.IsContainMacro property to detect if a Word document contains macros, if the result is true, you can use the Document.ClearMacros() method to remove them. Here are the detailed steps:

  • Initialize an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Detect if the document contains macros through Document.IsContainMacro property.
  • If the result is true, remove the macros from the Word document using Document.ClearMacros() method.
  • Save the result document using Document.SaveToFile() method.

C#

using Spire.Doc;

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

            bool hasMacros = false;
            //Detect if the document contains macros
            hasMacros = document.IsContainMacro;

            //If the result is true, remove the macros from the document
            if (hasMacros)
            {
                document.ClearMacros();
            }
            
            //Save the document
            document.SaveToFile("Output.docm", FileFormat.Docm);            
        }
    }
}

VB.NET

Imports Spire.Doc

Namespace RemoveMacrosFromWord
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize a Document object
            Dim document As Document = New Document()
            'Load the Word document
            document.LoadFromFile("Input.docm")

            Dim hasMacros = False
            'Detect if the document contains macros
            hasMacros = document.IsContainMacro

            'If the result is true, remove the macros from the document
            If hasMacros Then
                document.ClearMacros()
            End If

            'Save the document
            document.SaveToFile("Output.docm", FileFormat.Docm)
        End Sub
    End Class
End Namespace
Design a site like this with WordPress.com
Get started