Adding, modifying, and removing Word table borders can enhance the readability, aesthetics, and organization of data. Adding borders makes the content of the table clearer, distinguishing between different cells, which helps readers quickly identify information. Modifying border styles (such as line thickness, color, or pattern) can emphasize key data, guide visual flow, or conform to specific document styles and design requirements. Removing borders, in some cases, reduces visual clutter, making the content more compact and minimalist, especially suitable for data presentation where strict divisions are not needed or when you wish to downplay structural visibility. This article will introduce how to add, modify, or remove Word table borders in C# projects using Spire.Doc for .NET.

Install Spire.Doc for .NET

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

PM> Install-Package Spire.Doc

C# Add Word Table Borders

To set borders for all cells in an entire Word table, you need to iterate over each cell and set its visual border properties. Here are the detailed steps:

  • Create a Document object.
  • Use the Document.LoadFromFile() method to load a document.
  • Retrieve the first section of the document using Document.Sections[0].
  • Get the first table in that section by using Section.Tables[0].
  • Use a for loop to iterate through all the cells in the table.
  • Set TableCell.CellFormat.Borders.BorderType to BorderStyle.Single, which sets the cell border to a single line style.
  • Set TableCell.CellFormat.Borders.LineWidth to 1.5, defining the border width to be 1.5 points.
  • Set TableCell.CellFormat.Borders.Color to Color.Black, setting the border color to black.
  • Save the changes to the Word document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;

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

            // Load the document from a file
            doc.LoadFromFile("TableExample1.docx");

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

            // Get the first table in that section
            Table table = (Table)section.Tables[0];

            // Declare TableRow and TableCell variables for use within loops
            TableRow tableRow;
            TableCell tableCell;

            // Iterate through all rows in the table
            for (int i = 0; i < table.Rows.Count; i++)
            {
                // Get the current row
                tableRow = table.Rows[i];

                // Iterate through all cells in the current row
                for (int j = 0; j < tableRow.Cells.Count; j++)
                {
                    // Get the current cell
                    tableCell = tableRow.Cells[j];

                    // Set the border style of the current cell to single line
                    tableCell.CellFormat.Borders.BorderType = Spire.Doc.Documents.BorderStyle.Single;
                }
            }

            // Save the modified document as a new file
            doc.SaveToFile("AddBorders.docx", FileFormat.Docx2016);

            // Close the document to release resources
            doc.Close();
        }
    }
}

C#: Add, Modify, or Remove Word Table Borders

C# Modify Word Table Borders

Spire.Doc offers a range of border properties such as the border style TableCell.CellFormat.Borders.BorderType, border width TableCell.CellFormat.Borders.LineWidth, and border color TableCell.CellFormat.Borders.Color, among others. You can customize these properties to achieve the desired effects. Below are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.LoadFromFile() method.
  • Retrieve the first section of the document using Document.Sections[0].
  • Get the first table in the section using Section.Tables[0].
  • Use a for loop to iterate over the cells in the table whose border styles you wish to change.
  • Change the bottom border color of the cell by setting TableCell.CellFormat.Borders.Bottom.Color to Color.PaleVioletRed.
  • Change the bottom border style of the cell by setting TableCell.CellFormat.Borders.Bottom.BorderType to BorderStyle.DotDash.
  • Change the bottom border width of the cell by setting TableCell.CellFormat.Borders.Bottom.LineWidth to 2 points.
  • Save the changes to the document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

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

            // Load the document from a file
            doc.LoadFromFile("TableExample2.docx");

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

            // Get the first table in that section
            Table table = (Table)section.Tables[0];

            // Declare a TableRow to use within the loop
            TableRow tableRow;

            // Iterate through all rows of the table
            for (int i = 1; i < table.Rows.Count - 1; i++)
            {
                tableRow = table.Rows[i];

                // Set the border color of the current cell
                tableRow.Cells[1].CellFormat.Borders.Bottom.Color = Color.PaleVioletRed;

                // Set the border style of the current cell to DotDash
                tableRow.Cells[1].CellFormat.Borders.Bottom.BorderType = Spire.Doc.Documents.BorderStyle.DotDash;

                // Set the width of the border
                tableRow.Cells[1].CellFormat.Borders.Bottom.LineWidth = 2;
            }

            // Save the modified document as a new file
            doc.SaveToFile("ModifiedBorders.docx", FileFormat.Docx2016);

            // Close the document and release resources
            doc.Close();
        }
    }
}

C#: Add, Modify, or Remove Word Table Borders

C# Remove Word Table Borders

During the process of handling Word documents, not only can border styles be applied to entire tables, but customization can also be extended to individual cells. To completely remove all borders from a table, it is recommended to follow a two-step strategy: First, apply border removal settings to the table itself; second, visit each cell within the table individually to clear their border styles. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.LoadFromFile() method.
  • Retrieve the first table in the section using Section.Tables[0].
  • Use a for loop to iterate over all cells in the table.
  • Set Table.TableFormat.Borders.BorderType = BorderStyle.None to remove borders from the table.
  • Set TableCell.CellFormat.Borders.BorderType = BorderStyle.None to remove borders from each cell.
  • Save the changes to the Word document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

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

            // Load the document from file
            doc.LoadFromFile("TableExample2.docx");

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

            // Get the first table in that section
            Table table = (Table)section.Tables[0];

            // Remove the borders set on the table
            table.Format.Borders.BorderType = BorderStyle.None;

            // Declare a TableRow to use in the loop
            TableRow tableRow;

            // Iterate through all rows in the table
            for (int i = 0; i < table.Rows.Count; i++)
            {
                tableRow = table.Rows[i];
                for (int j = 0; j < tableRow.Cells.Count; j++)
                {
                    // Remove all borders set on the cell
                    tableRow.Cells[j].CellFormat.Borders.BorderType = BorderStyle.None;
                }
            }

            // Save the modified document as a new file
            doc.SaveToFile("RemoveBorders.docx", FileFormat.Docx2016);

            // Close the document to release resources
            doc.Close();
        }
    }
}

C#: Add, Modify, or Remove Word Table Borders

Apply for a Temporary License

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

Displaying PowerPoint text box content in multiple columns significantly enhances the presentation of information and audience comprehension. It improves readability by shortening line lengths, making dense text more digestible; optimizes visual layout for an aesthetically pleasing and professional look; and utilizes space efficiently to ensure that information is abundant yet uncluttered. In this article, we will introduce how to add or remove columns in a PowerPoint text box using Spire.Presentation for .NET in C# projects.

Install Spire.Presentation for .NET

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

PM> Install-Package Spire.Presentation

Add Columns to a PowerPoint Text Box with C#

Spire.Presentation provides the Shape.TextFrame.ColumnCount property to set the number of columns for content and the Shape.TextFrame.ColumnSpacing property to set the spacing between columns. Below are the detailed steps:

  • Create a Presentation object.
  • Load a PowerPoint document using the Presentation.LoadFromFile() method.
  • Retrieve the first slide using Presentation.Slides[0].
  • Obtain the first text box object as IAutoShape.
  • Use the Shape.TextFrame.ColumnCount property to set the number of columns for the text box content.
  • Use the Shape.TextFrame.ColumnSpacing property to set the spacing between columns.
  • Save the document to a specified path using the Presentation.SaveToFile() method.
  • C#
using Spire.Presentation;

namespace Spire.PresentationDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {     
            // Create a Presentation object
            Presentation presentation = new Presentation();

            // Load the PPTX file
            presentation.LoadFromFile("Sample1.pptx");

            // Get the first slide
            ISlide slide = presentation.Slides[0];

            // Check if the first shape on the slide is of type IAutoShape
            if (slide.Shapes[0] is IAutoShape)
            {
                // Cast the first shape to an IAutoShape object
                IAutoShape shape = (IAutoShape)slide.Shapes[0];

                // Set the number of columns in the shape's text frame to 2
                shape.TextFrame.ColumnCount = 2;

                // Set the column spacing in the shape's text frame to 25 pt
                shape.TextFrame.ColumnSpacing = 25f;
            }

            // Save the modified presentation as a new PPTX file
            presentation.SaveToFile("SetColumns.pptx", Spire.Presentation.FileFormat.Pptx2016);

            // Dispose of the resources used by the Presentation object
            presentation.Dispose();
        }
    }
}

C#: Add or Remove Columns in A PowerPoint Text Box

Remove Columns from a PowerPoint Text Box with C#

To remove the columns from the Powerpoint text box, simply set the Shape.TextFrame.ColumnCount property to 1. Below are the detailed steps:

  • Create a Presentation object.
  • Load a PowerPoint document using the Presentation.LoadFromFile() method.
  • Retrieve a slide using the Presentation.Slides[index] property.
  • Obtain the text box object as IAutoShape.
  • Set Shape.TextFrame.ColumnCount = 1 to remove the columns.
  • Save the document to a specified path using the Presentation.SaveToFile() method.
  • C#
using Spire.Presentation;

namespace SpirePresentationDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Presentation object
            Presentation presentation = new Presentation();

            // Load the PPTX file
            presentation.LoadFromFile("Sample2.pptx");

            // Get the first slide
            ISlide slide = presentation.Slides[0];

            // Check if the first shape on the slide is of type IAutoShape
            if (slide.Shapes[0] is IAutoShape)
            {
                // Cast the first shape to an IAutoShape object
                IAutoShape shape = (IAutoShape)slide.Shapes[0];

                // Set the column count of the shape's text frame to 1
                shape.TextFrame.ColumnCount = 1;
            }

            // Save the modified presentation as a new PPTX file
            presentation.SaveToFile("RemoveColumns.pptx", Spire.Presentation.FileFormat.Pptx2016);

            // Dispose of the resources used by the Presentation object
            presentation.Dispose();
        }
    }
}

C#: Add or Remove Columns in A PowerPoint Text Box

Apply for a Temporary License

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

Accurate counting of words, characters, paragraphs, lines, and pages is essential in achieving precise document analysis. By meticulously tracking these metrics, writers can gain valuable insights into the length, structure, and overall composition of their work. In this article, we will explain how to count words, characters, paragraphs, lines, and pages in Word documents in C# using Spire.Doc for .NET.

Install Spire.Doc for .NET

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

PM> Install-Package Spire.Doc

Count Words, Characters, Paragraphs, Lines, and Pages in a Word Document in C#

Spire.Doc for .NET provides the BuiltinDocumentProperties class that enables you to retrieve crucial information from your Word documents. By using this class, you can access a wealth of details, including both the built-in and custom properties, as well as the precise counts of words, characters, paragraphs, lines, and pages contained within the document. The detailed steps are as follows.

  • Initialize an object of the Document class.
  • Load a sample Word document using the Document.LoadFromFile() method.
  • Get the BuiltinDocumentProperties object using the Document.BuiltinDocumentProperties property.
  • Get the numbers of words, characters, paragraphs, lines, and pages in the document using the WordCount, CharCount, ParagraphCount, LinesCount and PageCount properties of the BuiltinDocumentProperties class.
  • Initialize an object of the StringBuilder class and append the results to it using the StringBuilder.AppendLine() method.
  • Write the content in the StringBuilder to a text file using the File.WriteAllText() method.
  • C#
using Spire.Doc;
using System.IO;
using System.Text;

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

            //Get the BuiltinDocumentProperties object
            BuiltinDocumentProperties properties = document.BuiltinDocumentProperties;

            //Get the numbers of words, characters, paragraphs, lines, and pages in the document
            int wordCount = properties.WordCount;
            int charCount = properties.CharCount;
            int paraCount = properties.ParagraphCount;
            int lineCount = properties.LinesCount;
            int pageCount = properties.PageCount;

            //Initialize an object of the StringBuilder class
            StringBuilder sb = new StringBuilder();
            //Append the results to the StringBuilder
            sb.AppendLine("The number of words: " + wordCount);
            sb.AppendLine("The number of characters: " + charCount);
            sb.AppendLine("The number of paragraphs: " + paraCount);
            sb.AppendLine("The number of lines: " + lineCount);
            sb.AppendLine("The number of pages: " + pageCount);

            //Write the content of the StringBuilder to a text file
            File.WriteAllText("result.txt", sb.ToString());
            document.Close();
        }
    }
}

C#: Count Words, Characters, Paragraphs, Lines, and Pages in Word Documents

Count Words and Characters in a Specific Paragraph of a Word Document in C#

In addition to counting the words and characters in an entire Word document, Spire.Doc for .NET enables you to count the words and characters of a specific paragraph by using the Paragraph.WordCount and Paragraph.CharCount properties. The detailed steps are as follows.

  • Initialize an object of the Document class.
  • Load a sample Word document using the Document.LoadFromFile() method.
  • Get a specific paragraph using the Document.Sections[sectionindex].Paragraphs[paragraphIndex] property.
  • Get the numbers of words and characters in the paragraph using the Paragraph.WordCount and Paragraph.CharCount properties.
  • Initialize an object of the StringBuilder class and append the results to it using the StringBuilder.AppendLine() method.
  • Write the content in the StringBuilder to a text file using the File.WriteAllText() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.IO;
using System.Text;

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

            //Get a specific paragraph
            Paragraph paragraph = document.Sections[0].Paragraphs[0];

            //Get the numbers of words and characters in the paragraph
            int wordCount = paragraph.WordCount;
            int charCount = paragraph.CharCount;
           

            //Initialize an object of the StringBuilder class
            StringBuilder sb = new StringBuilder();
            //Append the results to the StringBuilder
            sb.AppendLine("The number of words: " + wordCount);
            sb.AppendLine("The number of characters: " + charCount);

            //Write the content of the StringBuilder to a text file
            File.WriteAllText("result.txt", sb.ToString());
            document.Close();
        }
    }
}

C#: Count Words, Characters, Paragraphs, Lines, and Pages in Word Documents

Apply for a Temporary License

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

In a Word document, content controls allow the content of the document to be dynamically updated and modified, providing users with more flexible editing and management options. Through content controls, users can easily insert, delete, or modify content in specific sections without altering the overall structure of the document. This article will explain how to use Spire.Doc for .NET to modify content controls in a Word document within a C# project.

Install Spire.Doc for .NET

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

PM> Install-Package Spire.Doc

Modify Content Controls in the Body using C#

In Spire.Doc, the object type for content controls in the body is StructureDocumentTag. You can iterate through the collection of child objects in Section.Body to find objects of type StructureDocumentTag and then modify them. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.LoadFromFile() method.
  • Access the body of a section in the document using Section.Body.
  • Iterate through the collection of child objects in the body, Body.ChildObjects, to find objects of type StructureDocumentTag.
  • Access the StructureDocumentTag.ChildObjects collection and perform the necessary modification operations based on the type of child objects.
  • Save the document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Collections.Generic;

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

            // Load document content from a file
            doc.LoadFromFile("Sample1.docx");

            // Get the body of the document
            Body body = doc.Sections[0].Body;

            // Create lists for paragraphs and tables
            List<Paragraph> paragraphs = new List<Paragraph>();
            List<Table> tables = new List<Table>();
            for (int i = 0; i < body.ChildObjects.Count; i++)
            {
                // Get the document object
                DocumentObject documentObject = body.ChildObjects[i];

                // If it is a StructureDocumentTag object
                if (documentObject.DocumentObjectType == DocumentObjectType.StructureDocumentTag)
                {
                    StructureDocumentTag structureDocumentTag = (StructureDocumentTag)documentObject;

                    // If the tag is "c1" or the alias is "c1"
                    if (structureDocumentTag.SDTProperties.Tag == "c1" || structureDocumentTag.SDTProperties.Alias == "c1")
                    {
                        for (int j = 0; j < structureDocumentTag.ChildObjects.Count; j++)
                        {
                            // If it is a paragraph object
                            if (structureDocumentTag.ChildObjects[j].DocumentObjectType == DocumentObjectType.Paragraph)
                            {
                                Paragraph paragraph = (Paragraph)structureDocumentTag.ChildObjects[j];
                                paragraphs.Add(paragraph);
                            }

                            // If it is a table object
                            if (structureDocumentTag.ChildObjects[j].DocumentObjectType == DocumentObjectType.Table)
                            {
                                Table table = (Table)structureDocumentTag.ChildObjects[j];
                                tables.Add(table);
                            }
                        }
                    }
                }
            }

            // Modify the text content of the first paragraph
            paragraphs[0].Text = "Spire.Doc for .NET is a totally independent .NET Word class library which doesn't require Microsoft Office installed on system.";

            // Reset the cells of the first table
            tables[0].ResetCells(5, 4);

            // Save the modified document to a file
            doc.SaveToFile("ModifyBodyContentControls.docx", FileFormat.Docx2016);

            // Release document resources
            doc.Dispose();
        }
    }
}

C#: Modify Content Controls in a Word Document

Modify Content Controls within Paragraphs using C#

In Spire.Doc, the object type for content controls within paragraphs is StructureDocumentTagInline. To modify them, you need to iterate through the collection of child objects of Paragraph.ChildObjects, find objects of type StructureDocumentTagInline, and then make the necessary modifications. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.LoadFromFile() method.
  • Access the body of a section in the document using Section.Body.
  • Get the first paragraph of the body using Body.Paragraphs[0].
  • Iterate through the collection of child objects of the paragraph, Paragraph.ChildObjects, to find objects of type StructureDocumentTagInline.
  • Access the collection of child objects of StructureDocumentTagInline, StructureDocumentTagInline.ChildObjects, and perform the required modifications based on the type of the child objects.
  • Save the document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Collections.Generic;

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

            // Load document content from a file
            doc.LoadFromFile("Sample2.docx");

            // Get the body of the document
            Body body = doc.Sections[0].Body;

            // Get the first paragraph in the body
            Paragraph paragraph = body.Paragraphs[0];

            // Iterate through child objects in the paragraph
            for (int i = 0; i < paragraph.ChildObjects.Count; i++)
            {
                // Check if the child object is StructureDocumentTagInline
                if (paragraph.ChildObjects[i].DocumentObjectType == DocumentObjectType.StructureDocumentTagInline)
                {
                    // Convert the child object to StructureDocumentTagInline type
                    StructureDocumentTagInline structureDocumentTagInline = (StructureDocumentTagInline)paragraph.ChildObjects[i];

                    // Check if the Tag or Alias property is "text1"
                    if (structureDocumentTagInline.SDTProperties.Tag == "text1" || structureDocumentTagInline.SDTProperties.Alias == "text1")
                    {
                        // Iterate through child objects in the StructureDocumentTagInline object
                        for (int j = 0; j < structureDocumentTagInline.ChildObjects.Count; j++)
                        {
                            // Check if the child object is a TextRange object
                            if (structureDocumentTagInline.ChildObjects[j].DocumentObjectType == DocumentObjectType.TextRange)
                            {
                                // Convert the child object to TextRange type
                                TextRange range = (TextRange)structureDocumentTagInline.ChildObjects[j];

                                // Set the text content to a specified content
                                range.Text = "97-2003/2007/2010/2013/2016/2019";
                            }
                        }
                    }

                    // Check if the Tag or Alias property is "logo1"
                    if (structureDocumentTagInline.SDTProperties.Tag == "logo1" || structureDocumentTagInline.SDTProperties.Alias == "logo1")
                    {
                        // Iterate through child objects in the StructureDocumentTagInline object
                        for (int j = 0; j < structureDocumentTagInline.ChildObjects.Count; j++)
                        {
                            // Check if the child object is an image
                            if (structureDocumentTagInline.ChildObjects[j].DocumentObjectType == DocumentObjectType.Picture)
                            {
                                // Convert the child object to DocPicture type
                                DocPicture docPicture = (DocPicture)structureDocumentTagInline.ChildObjects[j];

                                // Load a specified image
                                docPicture.LoadImage("Doc-NET.png");

                                // Set the width and height of the image
                                docPicture.Width = 100;
                                docPicture.Height = 100;
                            }
                        }
                    }
                }
            }

            // Save the modified document to a new file
            doc.SaveToFile("ModifiedContentControlsInParagraph.docx", FileFormat.Docx2016);

            // Release resources of the Document object
            doc.Dispose();
        }
    }
}

C#: Modify Content Controls in a Word Document

Modify Content Controls Wrapping Table Rows using C#

In Spire.Doc, the object type for a table row content control is StructureDocumentTagRow. To modify it, you need to iterate through the child objects collection of Table.ChildObjects, find objects of type StructureDocumentTagRow, and then make the necessary modifications. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.LoadFromFile() method.
  • Access the body of a section using Section.Body.
  • Get the first table in the body using Body.Tables[0].
  • Iterate through the child objects collection of the table, Table.ChildObjects, to find objects of type StructureDocumentTagRow.
  • Access the collection of cells in the StructureDocumentTagRow.Cells table row content control and make the required modifications to the cell contents.
  • Save the document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

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

            // Load the document from a file
            doc.LoadFromFile("Sample3.docx");

            // Get the body of the document
            Body body = doc.Sections[0].Body;

            // Get the first table
            Table table = (Table)body.Tables[0];

            // Iterate through the child objects in the table
            for (int i = 0; i < table.ChildObjects.Count; i++)
            {
                // Check if the child object is of type StructureDocumentTagRow
                if (table.ChildObjects[i].DocumentObjectType == DocumentObjectType.StructureDocumentTagRow)
                {
                    // Convert the child object to a StructureDocumentTagRow object
                    StructureDocumentTagRow structureDocumentTagRow = (StructureDocumentTagRow)table.ChildObjects[i];

                    // Check if the Tag or Alias property of the StructureDocumentTagRow is "row1"
                    if (structureDocumentTagRow.SDTProperties.Tag == "row1" || structureDocumentTagRow.SDTProperties.Alias == "row1")
                    {
                        // Clear the paragraphs in the cell
                        structureDocumentTagRow.Cells[0].Paragraphs.Clear();

                        // Add a paragraph in the cell and set the text
                        TextRange textRange = structureDocumentTagRow.Cells[0].AddParagraph().AppendText("Arts");
                        textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue;
                    }
                }
            }

            // Save the modified document to a file
            doc.SaveToFile("ModifiedTableRowContentControl.docx", FileFormat.Docx2016);

            // Release document resources
            doc.Dispose();
        }
    }
}

C#: Modify Content Controls in a Word Document

Modify Content Controls Wrapping Table Cells using C#

In Spire.Doc, the object type for the content control in a table cell is StructureDocumentTagCell. You need to iterate through the collection of child objects in TableRow.ChildObjects, find objects of type StructureDocumentTagCell, and then perform operations on them. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.LoadFromFile() method.
  • Get the body of a section using Section.Body.
  • Get the first table in the body using Body.Tables[0].
  • Iterate through the collection of table rows Table.Rows, accessing each TableRow object.
  • Iterate through the collection of child objects in the table row TableRow.ChildObjects, finding objects of type StructureDocumentTagCell.
  • Access the collection of paragraphs in the StructureDocumentTagCell content control cell, and perform the necessary modifications to the content.
  • Save the document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

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

            // Load the document from a file
            doc.LoadFromFile("Sample4.docx");

            // Get the body of the document
            Body body = doc.Sections[0].Body;

            // Get the first table in the document
            Table table = (Table)body.Tables[0];

            // Iterate through the rows of the table
            for (int i = 0; i < table.Rows.Count; i++)
            {
                // Iterate through the child objects in each row
                for (int j = 0; j < table.Rows[i].ChildObjects.Count; j++)
                {
                    // Check if the child object is a StructureDocumentTagCell
                    if (table.Rows[i].ChildObjects[j].DocumentObjectType == DocumentObjectType.StructureDocumentTagCell)
                    {
                        // Convert the child object to StructureDocumentTagCell type
                        StructureDocumentTagCell structureDocumentTagCell = (StructureDocumentTagCell)table.Rows[i].ChildObjects[j];

                        // Check if the Tag or Alias property of structureDocumentTagCell is "cell1"
                        if (structureDocumentTagCell.SDTProperties.Tag == "cell1" || structureDocumentTagCell.SDTProperties.Alias == "cell1")
                        {
                            // Clear the paragraphs in the cell
                            structureDocumentTagCell.Paragraphs.Clear();

                            // Add a new paragraph and add text to it
                            TextRange textRange = structureDocumentTagCell.AddParagraph().AppendText("92");
                            textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue;
                        }
                    }
                }
            }

            // Save the modified document to a new file
            doc.SaveToFile("ModifiedTableCellContentControl.docx", FileFormat.Docx2016);

            // Dispose of the document object
            doc.Dispose();
        }
    }
}

C#: Modify Content Controls in a Word Document

Modify Content Controls within Table Cells using C#

This case demonstrates modifying content controls within paragraphs in table cells. You need to first access the collection of paragraphs in the cell TableCell.Paragraphs, then iterate through the collection of child objects in each paragraph Paragraph.ChildObjects, find objects of type StructureDocumentTagInline, and make modifications to them. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.LoadFromFile() method.
  • Get the body of a section using Section.Body.
  • Get the first table in the body using Body.Tables[0].
  • Iterate through the collection of table rows Table.Rows, accessing each TableRow object.
  • Iterate through the collection of cells in the table row TableRow.Cells, accessing each TableCell object.
  • Iterate through the collection of paragraphs in the cell TableCell.Paragraphs, accessing each Paragraph object.
  • Iterate through the collection of child objects in the paragraph Paragraph.ChildObjects, finding objects of type StructureDocumentTagInline.
  • Access the ChildObjects collection of the StructureDocumentTagInline object, and perform the necessary modifications based on the type of the child objects.
  • Save the document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

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

            // Load document content from file
            doc.LoadFromFile("Sample5.docx");

            // Get the body of the document
            Body body = doc.Sections[0].Body;

            // Get the first table
            Table table = (Table)body.Tables[0];

            // Iterate through the rows of the table
            for (int r = 0; r < table.Rows.Count; r++)
            {
                // Iterate through the cells in the table row
                for (int c = 0; c < table.Rows[r].Cells.Count; c++)
                {
                    // Iterate through the paragraphs in the cell
                    for (int p = 0; p < table.Rows[r].Cells[c].Paragraphs.Count; p++)
                    {
                        // Get the paragraph object
                        Paragraph paragraph = table.Rows[r].Cells[c].Paragraphs[p];

                        // Iterate through the child objects in the paragraph
                        for (int i = 0; i < paragraph.ChildObjects.Count; i++)
                        {
                            // Check if the child object is of type StructureDocumentTagInline
                            if (paragraph.ChildObjects[i].DocumentObjectType == DocumentObjectType.StructureDocumentTagInline)
                            {
                                // Convert to StructureDocumentTagInline object
                                StructureDocumentTagInline structureDocumentTagInline = (StructureDocumentTagInline)paragraph.ChildObjects[i];

                                // Check if the Tag or Alias property of StructureDocumentTagInline is "test1"
                                if (structureDocumentTagInline.SDTProperties.Tag == "test1" || structureDocumentTagInline.SDTProperties.Alias == "test1")
                                {
                                    // Iterate through the child objects of StructureDocumentTagInline
                                    for (int j = 0; j < structureDocumentTagInline.ChildObjects.Count; j++)
                                    {
                                        // Check if the child object is of type TextRange
                                        if (structureDocumentTagInline.ChildObjects[j].DocumentObjectType == DocumentObjectType.TextRange)
                                        {
                                            // Convert to TextRange object
                                            TextRange textRange = (TextRange)structureDocumentTagInline.ChildObjects[j];

                                            // Set the text content
                                            textRange.Text = "89";

                                            // Set text color
                                            textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Save the modified document to a new file
            doc.SaveToFile("ModifiedContentControlInParagraphOfTableCell.docx", FileFormat.Docx2016);

            // Dispose of the Document object resources
            doc.Dispose();
        }
    }
}

C#: Modify Content Controls in a Word Document

Apply for a Temporary License

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

Creating a table of contents in a newly created Word document is an important means to enhance document quality, improve reading experience, and effectively convey information. As a navigational guide for the document, the table of contents provides readers with a way to quickly locate and navigate through the document's content. Through the table of contents, readers can swiftly grasp the document's structure and content organization, saving reading time and boosting work efficiency. This article will explain how to use Spire.Doc for .NET to create a table of contents for a newly created Word document within a C# project.

Install Spire.Doc for .NET

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

PM> Install-Package Spire.Doc

C# Create a Table Of Contents Using Heading Styles

Using heading styles to create a table of contents is a method to automatically generate a table of contents in a Word document by identifying title and subtitles in the document using different levels of heading styles. Here are the detailed steps:

  • Create a Document object.
  • Add a section using the Document.AddSection() method.
  • Add a paragraph using the Section.AddParagraph() method.
  • Create a table of contents object using the Paragraph.AppendTOC(int lowerLevel, int upperLevel) method.
  • Create a CharacterFormat object and set the font.
  • Apply a heading style to the paragraph using the Paragraph.ApplyStyle(BuiltinStyle.Heading1) method.
  • Add text content using the Paragraph.AppendText() method.
  • Apply character formatting to the text using the TextRange.ApplyCharacterFormat() method.
  • Update the table of contents using the Document.UpdateTableOfContents() method.
  • Save the document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;

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

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

            // Add a paragraph
            Paragraph TOCparagraph = section.AddParagraph();
            TOCparagraph.AppendTOC(1, 3);

            // Create a CharacterFormat object and set the font
            CharacterFormat characterFormat1 = new CharacterFormat(doc);
            characterFormat1.FontName = "Microsoft YaHei";

            // Create another CharacterFormat object
            CharacterFormat characterFormat2 = new CharacterFormat(doc);
            characterFormat2.FontName = "Microsoft YaHei";
            characterFormat2.FontSize = 12;

            // Add a paragraph with Heading 1 style
            Paragraph paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading1);

            // Add text and apply character formatting
            TextRange textRange1 = paragraph.AppendText("Overview");
            textRange1.ApplyCharacterFormat(characterFormat1);

            // Add regular content
            paragraph = section.Body.AddParagraph();
            TextRange textRange2 = paragraph.AppendText("Spire.Doc for .NET is a professional Word .NET library specifically designed for developers to create, read, write, convert, compare and print Word documents on any .NET platform (Target .NET Framework, .NET Core, .NET Standard, .NET 5.0, .NET 6.0, Xamarin & Mono Android) with fast and high quality performance.");
            textRange2.ApplyCharacterFormat(characterFormat2);

            // Add a paragraph with Heading 1 style
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading1);
            textRange1 = paragraph.AppendText("Main Functions");
            textRange1.ApplyCharacterFormat(characterFormat1);

            // Add a paragraph with Heading 2 style
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading2);
            textRange1 = paragraph.AppendText("Only Spire.Doc, No Microsoft Office Automation");
            textRange1.ApplyCharacterFormat(characterFormat1);

            // Add regular content
            paragraph = section.Body.AddParagraph();
            textRange2 = paragraph.AppendText("Spire.Doc for .NET is a totally independent .NET Word class library which doesn't require Microsoft Office installed on system. Microsoft Office Automation is proved to be unstable, slow and not scalable to produce MS Word documents. Spire.Doc for .NET is many times faster than Microsoft Word Automation and with much better stability and scalability.");
            textRange2.ApplyCharacterFormat(characterFormat2);

            // Add a paragraph with Heading 3 style
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading3);
            textRange1 = paragraph.AppendText("Word Versions");
            textRange1.ApplyCharacterFormat(characterFormat1);
            paragraph = section.Body.AddParagraph();
            textRange2 = paragraph.AppendText("Word97-03  Word2007  Word2010  Word2013  Word2016  Word2019");
            textRange2.ApplyCharacterFormat(characterFormat2);

            // Add a paragraph with Heading 2 style
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading2);
            textRange1 = paragraph.AppendText("Convert File Documents with High Quality");
            textRange1.ApplyCharacterFormat(characterFormat1);

            // Add regular content
            paragraph = section.Body.AddParagraph();
            textRange2 = paragraph.AppendText("By using Spire.Doc for .NET, users can save Word Doc/Docx to stream, save as web response and convert Word Doc/Docx to XML, Markdown, RTF, EMF, TXT, XPS, EPUB, HTML, SVG, ODT and vice versa. Spire.Doc for .NET also supports to convert Word Doc/Docx to PDF and HTML to image.");
            textRange2.ApplyCharacterFormat(characterFormat2);

            // Add a paragraph with Heading 2 style
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(BuiltinStyle.Heading2);
            textRange1 = paragraph.AppendText("Other Technical Features");
            textRange1.ApplyCharacterFormat(characterFormat1);

            // Add regular content
            paragraph = section.Body.AddParagraph();
            textRange2 = paragraph.AppendText("By using Spire.Doc, developers can build any type of a 32-bit or 64-bit .NET application including ASP.NET, Web Services, WinForms, Xamarin and Mono Android, to create and handle Word documents.");
            textRange2.ApplyCharacterFormat(characterFormat2);

            // Update the table of contents
            doc.UpdateTableOfContents();

            // Save the document
            doc.SaveToFile("CreateTOCUsingHeadingStyles.docx", FileFormat.Docx2016);

            // Release resources
            doc.Dispose();
        }
    }
}

C#: Create a Table Of Contents for a Newly Created Word Document

C# Create a Table Of Contents Using Outline Level Styles

In a Word document, a table of contents can also be created using outline level styles. The ParagraphFormat.OutlineLevel property can be used to specify the level style of a paragraph in the outline. Subsequently, these outline level styles can be applied to the table of contents creation rules through the TableOfContent.SetTOCLevelStyle() method. Here are the detailed steps:

  • Create a Document object.
  • Add a section using the Document.AddSection() method.
  • Create a ParagraphStyle object and set the outline level using ParagraphStyle.ParagraphFormat.OutlineLevel = OutlineLevel.Level1.
  • Add the created ParagraphStyle object to the document using the Document.Styles.Add() method.
  • Add a paragraph using the Section.AddParagraph() method.
  • Create a table of contents object using the Paragraph.AppendTOC(int lowerLevel, int upperLevel) method.
  • Set the default setting for creating the table of contents with heading styles to False, TableOfContent.UseHeadingStyles = false.
  • Apply the outline level style to the table of contents rules using the TableOfContent.SetTOCLevelStyle(int levelNumber, string styleName) method.
  • Create a CharacterFormat object and set the font.
  • Apply the style to the paragraph using the Paragraph.ApplyStyle(ParagraphStyle.Name) method.
  • Add text content using the Paragraph.AppendText() method.
  • Apply character formatting to the text using the TextRange.ApplyCharacterFormat() method.
  • Update the table of contents using the Document.UpdateTableOfContents() method.
  • Save the document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;

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

            // Define Outline Level 1
            ParagraphStyle titleStyle1 = new ParagraphStyle(doc);
            titleStyle1.Name = "T1S";
            titleStyle1.ParagraphFormat.OutlineLevel = OutlineLevel.Level1;
            titleStyle1.CharacterFormat.Bold = true;
            titleStyle1.CharacterFormat.FontName = "Microsoft YaHei";
            titleStyle1.CharacterFormat.FontSize = 18f;
            titleStyle1.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left;
            doc.Styles.Add(titleStyle1);

            // Define Outline Level 2
            ParagraphStyle titleStyle2 = new ParagraphStyle(doc);
            titleStyle2.Name = "T2S";
            titleStyle2.ParagraphFormat.OutlineLevel = OutlineLevel.Level2;
            titleStyle2.CharacterFormat.Bold = true;
            titleStyle2.CharacterFormat.FontName = "Microsoft YaHei";
            titleStyle2.CharacterFormat.FontSize = 16f;
            titleStyle2.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left;
            doc.Styles.Add(titleStyle2);

            // Define Outline Level 3
            ParagraphStyle titleStyle3 = new ParagraphStyle(doc);
            titleStyle3.Name = "T3S";
            titleStyle3.ParagraphFormat.OutlineLevel = OutlineLevel.Level3;
            titleStyle3.CharacterFormat.Bold = true;
            titleStyle3.CharacterFormat.FontName = "Microsoft YaHei";
            titleStyle3.CharacterFormat.FontSize = 14f;
            titleStyle3.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left;
            doc.Styles.Add(titleStyle3);

            // Add a paragraph
            Paragraph TOCparagraph = section.AddParagraph();
            TableOfContent toc = TOCparagraph.AppendTOC(1, 3);
            toc.UseHeadingStyles = false;
            toc.UseHyperlinks = true;
            toc.UseTableEntryFields = false;
            toc.RightAlignPageNumbers = true;
            toc.SetTOCLevelStyle(1, titleStyle1.Name);
            toc.SetTOCLevelStyle(2, titleStyle2.Name);
            toc.SetTOCLevelStyle(3, titleStyle3.Name);

            // Define character format
            CharacterFormat characterFormat = new CharacterFormat(doc);
            characterFormat.FontName = "Microsoft YaHei";
            characterFormat.FontSize = 12;

            // Add a paragraph and apply outline level style 1
            Paragraph paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle1.Name);
            paragraph.AppendText("Overview");

            // Add a paragraph and set the text content
            paragraph = section.Body.AddParagraph();
            TextRange textRange = paragraph.AppendText("Spire.Doc for .NET is a professional Word .NET library specifically designed for developers to create, read, write, convert, compare and print Word documents on any .NET platform (Target .NET Framework, .NET Core, .NET Standard, .NET 5.0, .NET 6.0, Xamarin & Mono Android) with fast and high quality performance.");
            textRange.ApplyCharacterFormat(characterFormat);

            // Add a paragraph and apply outline level style 1
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle1.Name);
            paragraph.AppendText("Main Functions");

            // Add a paragraph and apply outline level style 2
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle2.Name);
            paragraph.AppendText("Only Spire.Doc, No Microsoft Office Automation");

            // Add a paragraph and set the text content
            paragraph = section.Body.AddParagraph();
            textRange = paragraph.AppendText("Spire.Doc for .NET is a totally independent .NET Word class library which doesn't require Microsoft Office installed on system. Microsoft Office Automation is proved to be unstable, slow and not scalable to produce MS Word documents. Spire.Doc for .NET is many times faster than Microsoft Word Automation and with much better stability and scalability.");
            textRange.ApplyCharacterFormat(characterFormat);

            // Add a paragraph and apply outline level style 3
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle3.Name);
            paragraph.AppendText("Word Versions");

            // Add a paragraph and set the text content
            paragraph = section.Body.AddParagraph();
            textRange = paragraph.AppendText("Word97-03  Word2007  Word2010  Word2013  Word2016  Word2019");
            textRange.ApplyCharacterFormat(characterFormat);

            // Add a paragraph and apply outline level style 2
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle2.Name);
            paragraph.AppendText("Convert File Documents with High Quality");

            // Add a paragraph and set the text content
            paragraph = section.Body.AddParagraph();
            textRange = paragraph.AppendText("By using Spire.Doc for .NET, users can save Word Doc/Docx to stream, save as web response and convert Word Doc/Docx to XML, Markdown, RTF, EMF, TXT, XPS, EPUB, HTML, SVG, ODT and vice versa. Spire.Doc for .NET also supports to convert Word Doc/Docx to PDF and HTML to image.");
            textRange.ApplyCharacterFormat(characterFormat);

            // Add a paragraph and apply outline level style 2
            paragraph = section.Body.AddParagraph();
            paragraph.ApplyStyle(titleStyle2.Name);
            paragraph.AppendText("Other Technical Features");

            // Add a paragraph and set the text content
            paragraph = section.Body.AddParagraph();
            textRange = paragraph.AppendText("By using Spire.Doc, developers can build any type of a 32-bit or 64-bit .NET application including ASP.NET, Web Services, WinForms, Xamarin and Mono Android, to create and handle Word documents.");
            textRange.ApplyCharacterFormat(characterFormat);

            // Update the table of contents
            doc.UpdateTableOfContents();

            // Save the document
            doc.SaveToFile("CreateTOCUsingOutlineStyles.docx", FileFormat.Docx2016);

            // Release resources
            doc.Dispose();
        }
    }
}

C#: Create a Table Of Contents for a Newly Created Word Document

C# Create a Table Of Contents Using Image Captions

Using the Spire.Doc library, you can create a table of contents based on image captions with the TableOfContent tocForImage = new TableOfContent(Document, " \\h \\z \\c \"Image\"") method. Here are the detailed steps:

  • Create a Document object.
  • Add a section using the Document.AddSection() method.
  • Create a table of content object with TableOfContent tocForImage = new TableOfContent(Document, " \\h \\z \\c \"Image\"") and specify the style of the table of contents.
  • Add a paragraph using the Section.AddParagraph() method.
  • Add the table of content object to the paragraph using the Paragraph.Items.Add(tocForImage) method.
  • Add a field separator using the Paragraph.AppendFieldMark(FieldMarkType.FieldSeparator) method.
  • Add the text content "TOC" using the Paragraph.AppendText("TOC") method.
  • Add a field end mark using the Paragraph.AppendFieldMark(FieldMarkType.FieldEnd) method.
  • Add an image using the Paragraph.AppendPicture() method.
  • Add a caption paragraph for the image using the DocPicture.AddCaption() method, including product information and formatting.
  • Update the table of contents to reflect changes in the document using the Document.UpdateTableOfContents(tocForImage) method.
  • Save the document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;

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

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

            // Create a table of content object for images
            TableOfContent tocForImage = new TableOfContent(doc, " \\h \\z \\c \"Picture\"");

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

            // Add the TOC object to the paragraph
            tocParagraph.Items.Add(tocForImage);

            // Add a field separator
            tocParagraph.AppendFieldMark(FieldMarkType.FieldSeparator);

            // Add text content
            tocParagraph.AppendText("TOC");

            // Add a field end mark
            tocParagraph.AppendFieldMark(FieldMarkType.FieldEnd);

            // Add a blank paragraph to the section
            section.Body.AddParagraph();

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

            // Add an image
            DocPicture docPicture = paragraph.AppendPicture("images/Doc-NET.png");
            docPicture.Width = 100;
            docPicture.Height = 100;

            // Add a caption paragraph for the image
            Paragraph pictureCaptionParagraph = docPicture.AddCaption("Picture", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            pictureCaptionParagraph.AppendText("  Spire.Doc for .NET product");
            pictureCaptionParagraph.Format.AfterSpacing = 20;

            // Continue adding paragraphs to the section
            paragraph = section.Body.AddParagraph();
            docPicture = paragraph.AppendPicture("images/PDF-NET.png");
            docPicture.Width = 100;
            docPicture.Height = 100;
            pictureCaptionParagraph = docPicture.AddCaption("Picture", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            pictureCaptionParagraph.AppendText("  Spire.PDF for .NET product");
            pictureCaptionParagraph.Format.AfterSpacing = 20;
            paragraph = section.Body.AddParagraph();
            docPicture = paragraph.AppendPicture("images/XLS-NET.png");
            docPicture.Width = 100;
            docPicture.Height = 100;
            pictureCaptionParagraph = docPicture.AddCaption("Picture", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            pictureCaptionParagraph.AppendText("  Spire.XLS for .NET product");
            pictureCaptionParagraph.Format.AfterSpacing = 20;
            paragraph = section.Body.AddParagraph();
            docPicture = paragraph.AppendPicture("images/PPT-NET.png");
            docPicture.Width = 100;
            docPicture.Height = 100;
            pictureCaptionParagraph = docPicture.AddCaption("Picture", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            pictureCaptionParagraph.AppendText("  Spire.Presentation for .NET product");

            // Update the table of contents
            doc.UpdateTableOfContents(tocForImage);

            // Save the document to a file
            doc.SaveToFile("CreateTOCWithImageCaptions.docx", Spire.Doc.FileFormat.Docx2016);

            // Dispose of the document object
            doc.Dispose();
        }
    }
}

C#: Create a Table Of Contents for a Newly Created Word Document

C# Create a Table Of Contents Using Table Captions

You can also create a table of contents using table captions by using the method TableOfContent tocForTable = new TableOfContent(Document, " \\h \\z \\c \"Table\""). Here are the detailed steps:

  • Create a Document object.
  • Add a section using the Document.AddSection() method.
  • Create a table of content object TableOfContent tocForTable = new TableOfContent(Document, " \\h \\z \\c \"Table\"") and specify the style of the table of contents.
  • Add a paragraph using the Section.AddParagraph() method.
  • Add the table of content object to the paragraph using the Paragraph.Items.Add(tocForTable) method.
  • Add a field separator using the Paragraph.AppendFieldMark(FieldMarkType.FieldSeparator) method.
  • Add the text content "TOC" using the Paragraph.AppendText("TOC") method.
  • Add a field end mark using the Paragraph.AppendFieldMark(FieldMarkType.FieldEnd) method.
  • Add a table using the Section.AddTable() method and set the number of rows and columns using the Table.ResetCells(int rowsNum, int columnsNum) method.
  • Add a table caption paragraph using the Table.AddCaption() method, including product information and formatting.
  • Update the table of contents to reflect changes in the document using the Document.UpdateTableOfContents(tocForTable) method.
  • Save the document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;

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

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

            // Create a TableOfContent object
            TableOfContent tocForTable = new TableOfContent(doc, " \\h \\z \\c \"Table\"");

            // Add a paragraph in the section to place the TableOfContent object
            Paragraph tocParagraph = section.Body.AddParagraph();
            tocParagraph.Items.Add(tocForTable);
            tocParagraph.AppendFieldMark(FieldMarkType.FieldSeparator);
            tocParagraph.AppendText("TOC");
            tocParagraph.AppendFieldMark(FieldMarkType.FieldEnd);

            // Add two empty paragraphs in the section
            section.Body.AddParagraph();
            section.Body.AddParagraph();

            // Add a table in the section
            Table table = section.Body.AddTable(true);
            table.ResetCells(1, 3);

            // Add a caption paragraph for the table
            Paragraph tableCaptionParagraph = table.AddCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            tableCaptionParagraph.AppendText("  One row three columns");
            tableCaptionParagraph.Format.AfterSpacing = 18;

            // Add a new table in the section
            table = section.Body.AddTable(true);
            table.ResetCells(3, 3);

            // Add a caption paragraph for the second table
            tableCaptionParagraph = table.AddCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            tableCaptionParagraph.AppendText("  Three rows three columns");
            tableCaptionParagraph.Format.AfterSpacing = 18;

            // Add another new table in the section
            table = section.Body.AddTable(true);
            table.ResetCells(5, 3);

            // Add a caption paragraph for the third table
            tableCaptionParagraph = table.AddCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph;
            tableCaptionParagraph.AppendText("  Five rows three columns");

            // Update the table of contents
            doc.UpdateTableOfContents(tocForTable);

            // Save the document to a specified file
            doc.SaveToFile("CreateTOCUsingTableCaptions.docx", Spire.Doc.FileFormat.Docx2016);

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Create a Table Of Contents for a Newly Created Word Document

Apply for a Temporary License

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

C#: Convert Markdown to Word and PDF

2024-04-10 00:59:36 Written by Koohji

Markdown, as a lightweight markup language, is favored by programmers and technical document writers for its simplicity, readability, and clear syntax. However, in specific scenarios, there is often a need to convert Markdown documents into Word documents with rich formatting capabilities and control over the layout or to generate PDF files suitable for printing and easy viewing. This article is going to demonstrate how to convert Markdown content into Word documents or PDF files with Spire.Doc for .NET to meet various document processing requirements in different scenarios.

Install Spire.Doc for .NET

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

PM> Install-Package Spire.Doc

Convert Markdown Files to Word Documents with C#

With Spire.Doc for .NET, we can load a Markdown file using Document.LoadFromFile(string fileName, FileFormat.Markdown) method and then convert it to other formats using Document.SaveToFile(string fileName, fileFormat FileFormat) method.

Since images in Markdown files are stored as links, directly converting a Markdown file to a Word document is suitable for Markdown files that do not contain images. If the file contains images, further processing of the images is required after conversion.

Here are the steps to convert a Markdown file to a Word document:

  • Create an instance of Document class.
  • Load a Markdown file using Document.LoadFromFile(string fileName, FileFormat.Markdown) method.
  • Convert the file to a Word document and save it using Document.SaveToFile(string fileName, FileFormat.Docx) method.
  • C#
using Spire.Doc;

namespace MdToDocx
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an object of Document class
            Document doc = new Document();

            // Load a Markdown file
            doc.LoadFromFile("Sample.md", FileFormat.Markdown);

            // Convert the Markdown file to a Word document
            doc.SaveToFile("MarkdownToWord.docx", FileFormat.Docx);
            doc.Close();
        }
    }
}

C#: Convert Markdown to Word and PDF

Convert Markdown Files to PDF Files with C#

We can also directly convert Markdown files to PDF files by using the FileFormat.PDF Enum as the parameter. Here are the steps to convert a Markdown file to a PDF file:

  • Create an instance of Document class.
  • Load a Markdown file using Document.LoadFromFile(string fileName, FileFormat.Markdown) method.
  • Convert the file to a PDF file and save it using Document.SaveToFile(string fileName, FileFormat.Docx) method.
  • C#
using Spire.Doc;

namespace MdToDocx
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an object of Document class
            Document doc = new Document();

            // Load a Markdown file
            doc.LoadFromFile("Sample.md", FileFormat.Markdown);

            // Convert the Markdown file to a PDF file
            doc.SaveToFile("MarkdownToPDF.pdf", FileFormat.PDF);
            doc.Close();
        }
    }
}

C#: Convert Markdown to Word and PDF

Apply for a Temporary License

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

C#: Add Gutters on Word Document Pages

2024-03-27 01:31:57 Written by Koohji

Adding gutters on Word document pages can enhance the professionalism and aesthetics of the document. Gutters not only make the document appear neater and more organized but also serve as a guide when printing the document, making it easier for readers to navigate and browse through the content. By adding gutters on the document pages, you can simulate the common binding line effect found in physical documents, giving the document a more printed quality. This article will explain how to use Spire.Doc for .NET to add gutters on Word document pages within a C# project.

Install Spire.Doc for .NET

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

PM> Install-Package Spire.Doc

Add a Gutter at the Top of a Word Document Page using C#

To enable the top gutter on a page, you can set the section.PageSetup.IsTopGutter = true. The default gutter area displays blank without content, and this example also includes how to add text within the gutter area. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.LoadFromFile() method.
  • Iterate through all sections of the document using a for loop over the Document.Sections collection.
  • Set Section.PageSetup.IsTopGutter to true to display the gutter at the top of the page.
  • Use the Section.PageSetup.Gutter property to set the width of the gutter.
  • Call the custom AddTopGutterText() method to add text to the gutter area.
  • Save the document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;
using System.Drawing;
using System.Text;

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

			// Load the document
			document.LoadFromFile("Sample1.docx");

			// Iterate through all sections of the document
			for (int i = 0; i < document.Sections.Count; i++)
			{
				// Get the current section
				Section section = document.Sections[i];

				// Set whether to add a gutter at the top of the page to true
				section.PageSetup.IsTopGutter = true;

				// Set the width of the gutter to 100f
				section.PageSetup.Gutter = 100f;

				// Call a method to add text on the top gutter
				AddTopGutterText(section);
			}

			// Save the modified document to a file
			document.SaveToFile("Add Gutter Line at the Top of the Page.docx", FileFormat.Docx2016);

			// Release document resources
			document.Dispose();
		}
		// Method to add text on the top gutter 
		static void AddTopGutterText(Section section)
		{
			// Get the header of the section
			HeaderFooter header = section.HeadersFooters.Header;

			// Set the width of the text box to the page width
			float width = section.PageSetup.PageSize.Width;

			// Set the height of the text box to 40
			float height = 40;

			// Add a text box in the header
			TextBox textBox = header.AddParagraph().AppendTextBox(width, height);

			// Set the text box without border
			textBox.Format.NoLine = true;

			// Set the vertical starting position of the text box to the top margin area
			textBox.VerticalOrigin = VerticalOrigin.TopMarginArea;

			// Set the vertical position of the text box
			textBox.VerticalPosition = 140;

			// Set the horizontal alignment of the text box to left
			textBox.HorizontalAlignment = ShapeHorizontalAlignment.Left;

			// Set the horizontal starting position of the text box to the left margin area
			textBox.HorizontalOrigin = HorizontalOrigin.LeftMarginArea;

			// Set the text anchor to bottom
			textBox.Format.TextAnchor = ShapeVerticalAlignment.Bottom;

			// Set the text wrapping style to in front of text
			textBox.Format.TextWrappingStyle = TextWrappingStyle.InFrontOfText;

			// Set the text wrapping type to both sides
			textBox.Format.TextWrappingType = TextWrappingType.Both;

			// Create a paragraph object
			Paragraph paragraph = new Paragraph(section.Document);

			// Set the paragraph to be horizontally centered
			paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center;

			// Create a font object
			Font font = new Font("Times New Roman", 8);

			// Create a drawing object
			Graphics graphics = Graphics.FromImage(new Bitmap(1, 1));
			string text1 = " - ";
			SizeF size1 = graphics.MeasureString(text1, font);
			float textWidth1 = size1.Width / 96 * 72;
			int count = (int)(textBox.Width / textWidth1);
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 1; i < count; i++)
			{
				stringBuilder.Append(text1);
			}

			// Create a character format object
			CharacterFormat characterFormat = new CharacterFormat(section.Document);
			characterFormat.FontName = font.Name;
			characterFormat.FontSize = font.Size;
			TextRange textRange = paragraph.AppendText(stringBuilder.ToString());
			textRange.ApplyCharacterFormat(characterFormat);

			// Add the paragraph to the text box
			textBox.ChildObjects.Add(paragraph);
		}
	}
}

C#: Add Gutters on Word Document Pages

Add a Gutter at the Left of a Word Document Page using C#

To set the left-side gutter on the page, ensure that you set the Section.PageSetup.IsTopGutter property to false. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.LoadFromFile() method.
  • Iterate through all sections of the document using a for loop over the Document.Sections collection.
  • Set Section.PageSetup.IsTopGutter to false to display the gutter on the left side of the page.
  • Use the Section.PageSetup.Gutter property to set the width of the gutter.
  • Call the custom AddLeftGutterText() method to add text to the gutter area.
  • Save the document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;
using System.Drawing;
using System.Text;

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

			// Load the document
			document.LoadFromFile("Sample1.docx");

			// Iterate through all sections of the document
			for (int i = 0; i < document.Sections.Count; i++)
			{
				// Get the current section
				Section section = document.Sections[i];

				// Set whether to add a gutter at the top of the page to false, it will be added to the left side of the page
				section.PageSetup.IsTopGutter = false;

				// Set the width of the gutter to 100f
				section.PageSetup.Gutter = 100f;

				// Call a method to add text on the left gutter 
				AddLeftGutterText(section);
			}

			// Save the modified document to a file
			document.SaveToFile("Add Gutter Line on the Left Side of the Page.docx", FileFormat.Docx2016);

			// Release document resources
			document.Dispose();
		}
		// Method to add text on the left gutter 
		static void AddLeftGutterText(Section section)
		{
			// Get the header of the section
			HeaderFooter header = section.HeadersFooters.Header;

			// Set the width of the text box to 40
			float width = 40;

			// Get the page height
			float height = section.PageSetup.PageSize.Height;

			// Add a text box in the header
			TextBox textBox = header.AddParagraph().AppendTextBox(width, height);

			// Set the text box without border
			textBox.Format.NoLine = true;

			// Set the text direction in the text box from right to left
			textBox.Format.LayoutFlowAlt = TextDirection.RightToLeft;

			// Set the horizontal starting position of the text box
			textBox.HorizontalOrigin = HorizontalOrigin.LeftMarginArea;

			// Set the horizontal position of the text box
			textBox.HorizontalPosition = 140;

			// Set the vertical alignment of the text box to top
			textBox.VerticalAlignment = ShapeVerticalAlignment.Top;

			// Set the vertical starting position of the text box to the top margin area
			textBox.VerticalOrigin = VerticalOrigin.TopMarginArea;

			// Set the text anchor to top
			textBox.Format.TextAnchor = ShapeVerticalAlignment.Top;

			// Set the text wrapping style to in front of text
			textBox.Format.TextWrappingStyle = TextWrappingStyle.InFrontOfText;

			// Set the text wrapping type to both sides
			textBox.Format.TextWrappingType = TextWrappingType.Both;

			// Create a paragraph object
			Paragraph paragraph = new Paragraph(section.Document);

			// Set the paragraph to be horizontally centered
			paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center;

			// Create a font object
			Font font = new Font("Times New Roman", 8);

			// Create a drawing object
			Graphics graphics = Graphics.FromImage(new Bitmap(1, 1));
			string text1 = " - ";

			// Measure the size of the text
			SizeF size1 = graphics.MeasureString(text1, font);
			float textWidth1 = size1.Width / 96 * 72;

			int count = (int)(textBox.Height / textWidth1);
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 1; i < count; i++)
			{
				stringBuilder.Append(text1);
			}

			// Create a character format object
			CharacterFormat characterFormat = new CharacterFormat(section.Document);
			characterFormat.FontName = font.Name;
			characterFormat.FontSize = font.Size;
			TextRange textRange = paragraph.AppendText(stringBuilder.ToString());
			textRange.ApplyCharacterFormat(characterFormat);

			// Add the paragraph to the text box
			textBox.ChildObjects.Add(paragraph);
		}
	}
}

C#: Add Gutters on Word Document Pages

Apply for a Temporary License

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

Adding the ability to edit permission area  in a Word document can help users specify certain sections for others to edit while protecting the rest of the document from accidental modifications. This is particularly useful for scenarios like collaborative documents, document reviews, and comments. On the other hand, removing editable area  functionality allows the document to be restored to a read-only state when specific sections do not need to be edited, ensuring the integrity and security of the document content. This article will explain how to use Spire.Doc for .NET to add or remove editable area  in a Word document within a C# project.

Install Spire.Doc for .NET

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

PM> Install-Package Spire.Doc

Add Editable Area in a Word Document in C#

The steps to add editable area  in a Word document involve inserting PermissionStart and PermissionEnd objects in the document and setting the document to read-only protection mode to ensure that the content within the specified areas can be edited while the rest remains read-only. Here are the detailed steps:

  • Create a Document object.
  • Load a Word document using the Document.LoadFromFile() method.
  • Access a section of the document through the Document.Sections[index] property.
  • Create a PermissionStart object using PermissionStart permissionStart = new PermissionStart(document, id) to mark the beginning of the editable area .
  • Create a PermissionEnd object using PermissionEnd permissionEnd = new PermissionEnd(document, id) to mark the end of the editable area .
  • Access a paragraph using the Section.Paragraphs[index] property.
  • Insert the permission start object at the beginning of the paragraph using the Paragraph.ChildObjects.Insert(0, permissionStart) method.
  • Add the permission end object at the end of the paragraph using the Paragraph.ChildObjects.Add(permissionEnd) method.
  • Set the document to read-only protection mode and restrict editing permissions using the Document.Protect(ProtectionType.AllowOnlyReading, password) method.
  • Save the resulting document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

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

            // Load the document from the specified path
            document.LoadFromFile("Sample1.docx");

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

            // Create a permission start object
            PermissionStart permissionStart = new PermissionStart(document, "restricted1");

            // Create a permission end object
            PermissionEnd permissionEnd = new PermissionEnd(document, "restricted1");

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

            // Insert the permission start object at the beginning of the paragraph
            paragraph.ChildObjects.Insert(0, permissionStart);

            // Add the permission end object at the end of the paragraph
            paragraph.ChildObjects.Add(permissionEnd);

            // Set the document to be read-only protected
            document.Protect(ProtectionType.AllowOnlyReading, "123456");

            // Save the modified document to the specified path
            document.SaveToFile("AddedEditingPermissionsArea.docx", FileFormat.Docx);

            // Close the document and release the resources occupied by the document object
            document.Close();
            document.Dispose();
        }
  }
}

C#: Add or Remove Editable area in a Word Document

Remove Editable Area in a Word Document in C#

The key steps to remove editable area  in a Word document involve iterating through each paragraph of the document and removing the PermissionStart and PermissionEnd objects. Here are the detailed steps:

  • Create a Document object.
  • Load a Word document using the Document.LoadFromFile() method.
  • Iterate through each paragraph in each section of the document, check for the presence of PermissionStart or PermissionEnd objects, and remove them.
  • Save the resulting document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

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

            // Load the document from the specified path
            document.LoadFromFile("Sample2.docx");

            // Iterate through the sections of the document
            for (int a = 0; a < document.Sections.Count; a++)
            {
                // Get the body of the current section
                Body body = document.Sections[a].Body;

                // Iterate through the child objects of the body
                for (int i = 0; i < body.ChildObjects.Count; i++)
                {
                    // Check if the child object is a paragraph
                    if (body.ChildObjects[i] is Paragraph)
                    {
                        // Get the current paragraph
                        Paragraph paragraph = (Paragraph)body.ChildObjects[i];

                        // Iterate backwards from the last child object of the paragraph
                        for (int j = paragraph.ChildObjects.Count - 1; j >= 0; j--)
                        {
                            // Get the current child object
                            DocumentObject documentObject = paragraph.ChildObjects[j];

                            // Remove the current child object if it is a permission start object
                            if (documentObject.DocumentObjectType == DocumentObjectType.PermissionStart)
                            {
                                paragraph.ChildObjects.RemoveAt(j);
                            }
                            // Remove the current child object if it is a permission end object
                            else if (documentObject.DocumentObjectType == DocumentObjectType.PermissionEnd)
                            {
                                paragraph.ChildObjects.RemoveAt(j);
                            }
                        }
                    }
                }
            }

            // Save the modified document to the specified path
            document.SaveToFile("RemovedEditingPermissionsArea.docx", FileFormat.Docx);

            // Close the document and release the resources occupied by the document object
            document.Close();
            document.Dispose();
        }
    }
}

C#: Add or Remove Editable area in a Word Document

Apply for a Temporary License

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

C# Guide to Read Word Document Content

Word documents (.doc and .docx) are widely used in business, education, and professional workflows for reports, contracts, manuals, and other essential content. As a C# developer, you may find the need to programmatically read these files to extract information, analyze content, and integrate document data into applications.

In this complete guide, we will delve into the process of reading Word documents in C#. We will explore various scenarios, including:

  • Extracting text, paragraphs, and formatting details
  • Retrieving images and structured table data
  • Accessing comments and document metadata
  • Reading headers and footers for comprehensive document analysis

By the end of this guide, you will have a solid understanding of how to efficiently parse Word documents in C#, allowing your applications to access and utilize document content with accuracy and ease.

Table of Contents

Set Up Your Development Environment for Reading Word Documents in C#

Before you can read Word documents in C#, it’s crucial to ensure that your development environment is properly set up. This section outlines the necessary prerequisites and step-by-step installation instructions to get you ready for seamless Word document handling.

Prerequisites

Install Spire.Doc

To incorporate Spire.Doc into your C# project, follow these steps to install it via NuGet:

  1. Open your project in Visual Studio.
  2. Right-click on your project in the Solution Explorer and select Manage NuGet Packages.
  3. In the Browse tab, search for "Spire.Doc" and click Install.

Alternatively, you can use the Package Manager Console with the following command:

PM> Install-Package Spire.Doc

This installation adds the necessary references, enabling you to programmatically work with Word documents.

Load Word Document (.doc/.docx) in C#

To begin, you need to load a Word document into your project. The following example demonstrates how to load a .docx or .doc file in C#:

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

namespace LoadWordExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Specify the path of the Word document
            string filePath = @"C:\Documents\Sample.docx";

            // Create a Document object
            using (Document document = new Document())
            {
                // Load the Word .docx or .doc document
                document.LoadFromFile(filePath);
            }
        }
    }
}

This code loads a Word file from the specified path into a Document object, which is the entry point for accessing all document elements.

Read and Extract Content from Word Document in C#

After loading the Word document into a Document object, you can access its contents programmatically. This section covers various methods for extracting different types of content effectively.

Extract Text

Extracting text is often the first step in reading Word documents. You can retrieve all text content using the built-in GetText() method:

using (StreamWriter writer = new StreamWriter("ExtractedText.txt", false, Encoding.UTF8))
{
    // Get all text from the document
    string allText = document.GetText();
    
    // Write the entire text to a file
    writer.Write(allText);
}

This method extracts all text, disregarding formatting and non-text elements like images.

C# Example to Extract All Text from Word Document

Read Paragraphs and Formatting Information

When working with Word documents, it is often useful not only to access the text content of paragraphs but also to understand how each paragraph is formatted. This includes details such as alignment and spacing after the paragraph, which can affect layout and readability.

The following example demonstrates how to iterate through all paragraphs in a Word document and retrieve their text content and paragraph-level formatting in C#:

using (StreamWriter writer = new StreamWriter("Paragraphs.txt", false, Encoding.UTF8))
{
    // Loop through all sections
    foreach (Section section in document.Sections)
    {
        // Loop through all paragraphs in the section
        foreach (Paragraph paragraph in section.Paragraphs)
        {
            // Get paragraph alignment
            HorizontalAlignment alignment = paragraph.Format.HorizontalAlignment;

            // Get spacing after paragraph
            float afterSpacing = paragraph.Format.AfterSpacing;

            // Write paragraph formatting and text to the file
            writer.WriteLine($"[Alignment: {alignment}, AfterSpacing: {afterSpacing}]");
            writer.WriteLine(paragraph.Text);
            writer.WriteLine(); // Add empty line between paragraphs
        }
    }
}

This approach allows you to extract both the text and key paragraph formatting attributes, which can be useful for tasks such as document analysis, conditional processing, or preserving layout when exporting content.

Extract Images

Images embedded within Word documents play a vital role in conveying information. To extract these images, you will examine each paragraph's content, identify images (typically represented as DocPicture objects), and save them for further use:

// Create the folder if it does not exist
string imageFolder = "ExtractedImages";
if (!Directory.Exists(imageFolder))
    Directory.CreateDirectory(imageFolder);

int imageIndex = 1;

// Loop through sections and paragraphs to find images
foreach (Section section in document.Sections)
{
    foreach (Paragraph paragraph in section.Paragraphs)
    {
        foreach (DocumentObject obj in paragraph.ChildObjects)
        {
            if (obj is DocPicture picture)
            {
                // Save each image as a separate PNG file
                string fileName = Path.Combine(imageFolder, $"Image_{imageIndex}.png");
                picture.Image.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
                imageIndex++;
            }
        }
    }
}

This code saves all images in the document as separate PNG files, with options to choose other formats like JPEG or BMP.

C# Example to Extract Images from Word Document

Extract Table Data

Tables are commonly used to organize structured data, such as financial reports or survey results. To access this data, iterate through the tables in each section and retrieve the content of individual cells:

// Create a folder to store tables
string tableDir = "Tables";
if (!Directory.Exists(tableDir))
    Directory.CreateDirectory(tableDir);

// Loop through each section
for (int sectionIndex = 0; sectionIndex < document.Sections.Count; sectionIndex++)
{
    Section section = document.Sections[sectionIndex];
    TableCollection tables = section.Tables;

    // Loop through all tables in the section
    for (int tableIndex = 0; tableIndex < tables.Count; tableIndex++)
    {
        ITable table = tables[tableIndex];
        string fileName = Path.Combine(tableDir, $"Section{sectionIndex + 1}_Table{tableIndex + 1}.txt");

        using (StreamWriter writer = new StreamWriter(fileName, false, Encoding.UTF8))
        {
            // Loop through each row
            for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++)
            {
                TableRow row = table.Rows[rowIndex];

                // Loop through each cell
                for (int cellIndex = 0; cellIndex < row.Cells.Count; cellIndex++)
                {
                    TableCell cell = row.Cells[cellIndex];

                    // Loop through each paragraph in the cell
                    for (int paraIndex = 0; paraIndex < cell.Paragraphs.Count; paraIndex++)
                    {
                        writer.Write(cell.Paragraphs[paraIndex].Text.Trim() + " ");
                    }

                    // Add tab between cells
                    if (cellIndex < row.Cells.Count - 1) writer.Write("\t");
                }

                // Add newline after each row
                writer.WriteLine();
            }
        }
    }
}

This method allows efficient extraction of structured data, making it ideal for generating reports or integrating content into databases.

C# Example to Extract Table Data from Word Document

Read Comments

Comments are valuable for collaboration and feedback within documents. Extracting them is crucial for auditing and understanding the document's revision history.

The Document object provides a Comments collection, which allows you to access all comments in a Word document. Each comment contains one or more paragraphs, and you can extract their text for further processing or save them into a file.

using (StreamWriter writer = new StreamWriter("Comments.txt", false, Encoding.UTF8))
{
    // Loop through all comments in the document
    foreach (Comment comment in document.Comments)
    {
        // Loop through each paragraph in the comment
        foreach (Paragraph p in comment.Body.Paragraphs)
        {
            writer.WriteLine(p.Text);
        }
        // Add empty line to separate different comments
        writer.WriteLine();
    }
}

This code retrieves the content of all comments and outputs it into a single text file.

Retrieve Document Metadata

Word documents contain metadata such as the title, author, and subject. These metadata items are stored as document properties, which can be accessed through the BuiltinDocumentProperties property of the Document object:

using (StreamWriter writer = new StreamWriter("Metadata.txt", false, Encoding.UTF8))
{
    // Write built-in document properties to file
    writer.WriteLine("Title: " + document.BuiltinDocumentProperties.Title);
    writer.WriteLine("Author: " + document.BuiltinDocumentProperties.Author);
    writer.WriteLine("Subject: " + document.BuiltinDocumentProperties.Subject);
}

Read Headers and Footers

Headers and footers frequently contain essential content like page numbers and titles. To programmatically access this information, iterate through each section's header and footer paragraphs and retrieve the text of each paragraph:

using (StreamWriter writer = new StreamWriter("HeadersFooters.txt", false, Encoding.UTF8))
{
    // Loop through all sections
    foreach (Section section in document.Sections)
    {
        // Write header paragraphs
        foreach (Paragraph headerParagraph in section.HeadersFooters.Header.Paragraphs)
        {
            writer.WriteLine("Header: " + headerParagraph.Text);
        }

        // Write footer paragraphs
        foreach (Paragraph footerParagraph in section.HeadersFooters.Footer.Paragraphs)
        {
            writer.WriteLine("Footer: " + footerParagraph.Text);
        }
    }
}

This method ensures that all recurring content is accurately captured during document processing.

Advanced Tips and Best Practices for Reading Word Documents in C#

To get the most out of programmatically reading Word documents, following these tips can help improve efficiency, reliability, and code maintainability:

  • Use using Statements: Always wrap Document objects in using to ensure proper memory management.
  • Check for Null or Empty Sections: Prevent errors by verifying sections, paragraphs, tables, or images exist before accessing them.
  • Batch Reading Multiple Documents: Loop through a folder of Word files and apply the same extraction logic to each file. This helps automate workflows and consolidate extracted content efficiently.

Conclusion

Efficiently reading Word documents programmatically in C# involves handling various content types. With the techniques outlined in this guide, developers can:

  • Load Word documents (.doc and .docx) with ease.
  • Extract text, paragraphs, and formatting details for thorough analysis.
  • Retrieve images, structured table data, and comments.
  • Access headers, footers, and document metadata for complete insights.

FAQs

Q1: Can I read Word documents without installing Microsoft Word?

A1: Yes, libraries like Spire.Doc enable you to read and process Word files without requiring Microsoft Word installation.

Q2: Does this support both .doc and .docx formats?

A2: Absolutely, all methods discussed in this guide work seamlessly with both legacy (.doc) and modern (.docx) Word files.

Q3: Can I extract only specific sections of a document?

A3: Yes, by iterating through sections and paragraphs, you can selectively filter and extract the desired content.

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

Install Spire.Doc for .NET

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

PM> Install-Package Spire.Doc

Add a Page in a Word Document using C#

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Close the document
document.Close();

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

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

Insert a Page in a Word Document using C#

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Delete a Page from a Word Document using C#

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Apply for a Temporary License

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

Page 6 of 95
page 6