Create and Update Word TOC in C# and VB.NET

A Table of Contents (TOC) provides clear and brief information about the organization of a Word document. It's represented with the TableOfEntries element, which contains Entries.

TOC entries are usually titles or descriptions of the document's headings or chapters. They may indicate where each part starts with page numbers, which are often separated from the entry's text by characters called leaders (like dots or periods).

The following example shows how you can easily create and update a TOC element in a document using GemBox.Document from C# and VB.NET code.

Create and update Table of Contents in Word document from C# and VB.NET
Screenshot of updated TOC element in Word document
using System.Linq;
using GemBox.Document;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");
        
        int heading1Count = %Headings1%;
        int heading2Count = %Headings2%;

        var document = new DocumentModel();

        var section = new Section(document);
        document.Sections.Add(section);

        // Create and add "Heading 1" style.
        var heading1Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading1, document);
        document.Styles.Add(heading1Style);

        // Create and add "Heading 2" style.
        var heading2Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading2, document);
        document.Styles.Add(heading2Style);

        // Create and add new TOC element.
        section.Blocks.Add(new TableOfEntries(document, FieldType.TOC));

        section.Blocks.Add(
            new Paragraph(document,
                new SpecialCharacter(document, SpecialCharacterType.PageBreak)));

        // Add document content.
        for (int i = 0; i < heading1Count; i++)
        {
            // Add "Heading 1" paragraph with Level1 for OutlineLevel. 
            section.Blocks.Add(
                new Paragraph(document, $"Heading 1 ({i + 1})") { ParagraphFormat = { Style = heading1Style } });

            for (int j = 0; j < heading2Count; j++)
            {
                // Add "Heading 2" paragraph with Level2 for OutlineLevel.
                section.Blocks.Add(
                    new Paragraph(document, $"Heading 2 ({i + 1}-{j + 1})") { ParagraphFormat = { Style = heading2Style } });

                section.Blocks.Add(
                    new Paragraph(document, "This is a paragraph.\nIt has a default BodyText for OutlineLevel.\nIt won't be listed in TOC entries."));
            }
        }

        // Get and update TOC element.
        var toc = (TableOfEntries)document.GetChildElements(true, ElementType.TableOfEntries).First();
        toc.Update();

        // Update TOC entries page numbers.
        // This is not needed when saving to PDF, XPS and image format or when printing.
        // Page numbers are automatically updated in that case.
        document.GetPaginator(new PaginatorOptions() { UpdateFields = true });

        document.Save("TOC.%OutputFileType%");
    }
}
Imports System.Linq
Imports GemBox.Document

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        Dim heading1Count As Integer = %Headings1%
        Dim heading2Count As Integer = %Headings2%
            
        Dim document As New DocumentModel()

        Dim section As New Section(document)
        document.Sections.Add(section)

        ' Create and add "Heading 1" style.
        Dim heading1Style = DirectCast(Style.CreateStyle(StyleTemplateType.Heading1, document), ParagraphStyle)
        document.Styles.Add(heading1Style)

        ' Create and add "Heading 2" style.
        Dim heading2Style = DirectCast(Style.CreateStyle(StyleTemplateType.Heading2, document), ParagraphStyle)
        document.Styles.Add(heading2Style)

        ' Create and add new TOC element.
        section.Blocks.Add(New TableOfEntries(document, FieldType.TOC))

        section.Blocks.Add(
            New Paragraph(document,
                New SpecialCharacter(document, SpecialCharacterType.PageBreak)))

        ' Add document content.
        For i As Integer = 0 To heading1Count - 1

            ' Add "Heading 1" paragraph with Level1 for OutlineLevel. 
            section.Blocks.Add(
                New Paragraph(document, $"Heading 1 ({i + 1})") With {.ParagraphFormat = New ParagraphFormat() With {.Style = heading1Style}})

            For j As Integer = 0 To heading2Count - 1

                ' Add "Heading 2" paragraph with Level2 for OutlineLevel.
                section.Blocks.Add(
                    New Paragraph(document, $"Heading 2 ({i + 1}-{j + 1})") With {.ParagraphFormat = New ParagraphFormat() With {.Style = heading2Style}})

                section.Blocks.Add(
                    New Paragraph(document, "This is a paragraph.\nIt has a default BodyText for OutlineLevel.\nIt won't be listed in TOC entries."))
            Next
        Next

        ' Get and update TOC element.
        Dim toc = DirectCast(document.GetChildElements(True, ElementType.TableOfEntries).First(), TableOfEntries)
        toc.Update()

        ' Update TOC entries page numbers.
        ' This is not needed when saving to PDF, XPS and image format or when printing.
        ' Page numbers are automatically updated in that case.
        document.GetPaginator(New PaginatorOptions() With {.UpdateFields = True})

        document.Save("TOC.%OutputFileType%")

    End Sub
End Module

TableOfEntries.Update method is used to update TOC entries. On this method's help page, under the remarks, you can find a list of currently supported Table of Contents and Table of Contents Entry switches that you can use.

Note: the page numbers in TOC entries are updated using the DocumentModel.GetPaginator method. This method uses GemBox.Document's rendering engine, the same engine that's used when saving to PDF, XPS and image format or when printing.

Want more?

Next example GitHub

Check the next example or select an example from the menu. You can also download our examples from the GitHub.


Like it?

Download Buy

If you want to try the GemBox.Document yourself, you can download the free version. It delivers the same performance and set of features as the professional version, but with some operations limited. To remove the limitation, you need to purchase a license.