How to create extended Table of Contents (TOC) in a Word document using C# and .NET

  1. Add SautinSoft.Document from Nuget.
  2. Create a new document.
  3. Add paragraphs with heading 1 and 2 styles.
  4. Add Table of Contents (TOC).
  5. Set custom formatting and styles for the TOC.
  6. Update the TOC and page numbering.
  7. Save the document in DOCX format.

Here we'll show you how to create a document with well-formatted TOC. As result you will see the DOCX document with TOC containing two Chapters and SubChapters.

A few steps:

  1. Notice you are importing the SautinSoft.Document namespace.
    using SautinSoft.Document;
  2. First of all, create a DocumentCore object with name document.
    
    DocumentCore document = new DocumentCore();
    
    DocumentCore is root class, it represents a document itself.
  3. Create and add Heading1, Heading2 and TOC styles.
    
                // Create and add Heading1 style. For "Chapter 1" and "Chapter 2".
                ParagraphStyle Heading1Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading1, dc);
                Heading1Style.ParagraphFormat.LineSpacing = 3;
                Heading1Style.CharacterFormat.Size = 18;
                // #358CCB - blue
                Heading1Style.CharacterFormat.FontColor = new Color("#358CCB");
                dc.Styles.Add(Heading1Style);
    
    
                // Create and add Heading2 style. For "SupChapter 1-1" and "SubChapter 2-1".
                ParagraphStyle Heading2Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading2, dc);
                Heading2Style.ParagraphFormat.LineSpacing = 2;
                Heading2Style.CharacterFormat.Size = 14;
                // #FF9900 - orange
                Heading2Style.CharacterFormat.FontColor = new Color("#FF9900");
                dc.Styles.Add(Heading2Style);
    
    
                // Create and add TOC style. 
                ParagraphStyle TOCStyle = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Subtitle, dc);
                TOCStyle.ParagraphFormat.OutlineLevel = OutlineLevel.BodyText;
                TOCStyle.ParagraphFormat.Alignment = HorizontalAlignment.Center;
                TOCStyle.CharacterFormat.Bold = true;
                // #358CCB - blue
                TOCStyle.CharacterFormat.FontColor = new Color("#358CCB");
                dc.Styles.Add(TOCStyle);
    
    Word's heading styles are called Heading 1, Heading 2, on down to Heading 9. Use them to identify different parts of a document, but they also take advantage of other Word features.
    In Word, a style is a collection of formatting instructions. You use styles to format the paragraphs in your document. So you would use the "Title" style for your title, "Body Text" style for body text, "Caption" style for the picture captions, and "Heading 1" for the major headings.

  4. We have created styles. Next step is apllying these styles for TOC Header, TOC, and Toc Ending.
    
                // Add TOC Header.
                section.Blocks.Add(
                    new Paragraph(dc, "Table of Contents")
                    {ParagraphFormat = {Style = TOCStyle}});
    
                // Create and add TOC (Table of Contents).
                section.Blocks.Add(new TableOfEntries(dc, FieldType.TOC));
    
                // Add TOC Ending.
                section.Blocks.Add(
                     new Paragraph(dc, "The End")
                     {ParagraphFormat = { Alignment = HorizontalAlignment.Center, BackgroundColor = Color.Gray}});
    
    
    We got this result:
  5. Create a new paragraph for Chapter and SubChapter using Heading1Style and Heading2Style.
    
                /// Add the document content (Chapter 1).
                // Add Chapter 1.
                section.Blocks.Add(
                    new Paragraph(dc, "Chapter 1")
                    {
                        ParagraphFormat =
                        {
                    Style = Heading1Style,
                    PageBreakBefore=true
                        }
                    });
    
                // Add SubChapter 1-1.
                section.Blocks.Add(
                            new Paragraph(dc, String.Format("Subchapter 1-1"))
                            {
                                ParagraphFormat =
                                {
                        Style = Heading2Style
                                }
                            });
    
    Paragraph is a Block derived element used to group Inline elements like a Run, Shape, Picture, Field etc.
  6. When you create the table of contents this way, you can automatically update it if you make changes in your document.
    TOC can be updated only after all document content is added.
    
       var tableofcontents = (TableOfEntries)dc.GetChildElements(true, ElementType.TableOfEntries).FirstOrDefault();
       tableofcontents.Update();
       // Apply the style for the TOC.
                foreach (Paragraph par in tableofcontents.Entries)
                {
                    par.ParagraphFormat.Style = TOCStyle;
                }
    
                // Update TOC's page numbers.
                // Page numbers are automatically updated in that case.
                dc.GetPaginator(new PaginatorOptions() { UpdateFields = true });
    
    The paginator is used to divide a document into discrete pages.
  7. Save our document as DOCX.
    
        // Save DOCX to a file
        document.Save("Extended-Table-Of-Contents.docx");
    
    Download the resulting Docx-file: Extended-Table-Of-Contents.docx
 

Complete code

using System;
using System.Linq;
using SautinSoft.Document;

namespace Example
{
    class Sample
    {
        static void Main(string[] args)
        {
            // Get your free 100-day key here:   
            // https://sautinsoft.com/start-for-free/

            ExtendedTOC();
        }

        /// <summary>
        /// Create extended table of contents in word document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/create-extended-table-of-contents-in-word-document-net-csharp-vb.php
        /// </remarks> 
        public static void ExtendedTOC()
        {
            string resultFile = "Extended-Table-Of-Contents.docx";
            // First of all, create an instance of DocumentCore.
            DocumentCore dc = new DocumentCore();

            // Create and add Heading1 style. For "Chapter 1" and "Chapter 2".
            ParagraphStyle Heading1Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading1, dc);
            Heading1Style.ParagraphFormat.LineSpacing = 3;
            Heading1Style.CharacterFormat.Size = 18;
            // #358CCB - blue
            Heading1Style.CharacterFormat.FontColor = new Color("#358CCB");
            dc.Styles.Add(Heading1Style);

            // Create and add Heading2 style. For "SupChapter 1-1" and "SubChapter 2-1".
            ParagraphStyle Heading2Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading2, dc);
            Heading2Style.ParagraphFormat.LineSpacing = 2;
            Heading2Style.CharacterFormat.Size = 14;
            // #FF9900 - orange
            Heading2Style.CharacterFormat.FontColor = new Color("#FF9900");
            dc.Styles.Add(Heading2Style);

            // Create and add TOC style.
            ParagraphStyle TOCStyle = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Subtitle, dc);
            TOCStyle.ParagraphFormat.OutlineLevel = OutlineLevel.BodyText;
            TOCStyle.ParagraphFormat.Alignment = HorizontalAlignment.Center;
            TOCStyle.CharacterFormat.Bold = true;
            // #358CCB - blue
            TOCStyle.CharacterFormat.FontColor = new Color("#358CCB");
            dc.Styles.Add(TOCStyle);

            // Add new section.
            Section section = new Section(dc);
            dc.Sections.Add(section);

            // Add TOC Header.
            section.Blocks.Add(
                new Paragraph(dc, "Table of Contents")
                { ParagraphFormat = { Style = TOCStyle } });

            // Create and add TOC (Table of Contents).
            section.Blocks.Add(new TableOfEntries(dc, FieldType.TOC));

            // Add TOC Ending.
            section.Blocks.Add(
                 new Paragraph(dc, "The End")
                 { ParagraphFormat = { Alignment = HorizontalAlignment.Center, BackgroundColor = Color.Gray } });

            // Add the document content (Chapter 1).
            // Add Chapter 1.
            section.Blocks.Add(
                new Paragraph(dc, "Chapter 1")
                {
                    ParagraphFormat =
                    {
                Style = Heading1Style,
                PageBreakBefore=true
                    }
                });

            // Add SubChapter 1-1.
            section.Blocks.Add(
                        new Paragraph(dc, String.Format("Subchapter 1-1"))
                        {
                            ParagraphFormat =
                            {
                    Style = Heading2Style
                            }
                        });

            // Add the content of Chapter 1 / Subchapter 1-1.
            section.Blocks.Add(
                        new Paragraph(dc,
                            "Document.Net will help you in development of applications which operates with DOCX, RTF, PDF, HTML and Text documents.After adding of the reference to(SautinSoft.Document.dll) - it's 100% C# managed assembly you will be able to create a new document, parse an existing, modify anything what you want.")
                        {
                            ParagraphFormat = new ParagraphFormat
                            {
                                LeftIndentation = 10,
                                RightIndentation = 10,
                                SpecialIndentation = 20,
                                LineSpacing = 20,
                                LineSpacingRule = LineSpacingRule.Exactly,
                                SpaceBefore = 20,
                                SpaceAfter = 20
                            }
                        });

            // Let's add another page break into.
            section.Blocks.Add(
                   new Paragraph(dc,
                   new SpecialCharacter(dc, SpecialCharacterType.PageBreak)));

            // Add the document content (Chapter 2).
            // Add Chapter 2.
            section.Blocks.Add(
                     new Paragraph(dc, "Chapter 2")
                     {
                         ParagraphFormat =
                         {
                Style = Heading1Style
                         }
                     });

            // Add SubChapter 2-1.
            section.Blocks.Add(
                new Paragraph(dc, String.Format("Subchapter 2-1"))
                {
                    ParagraphFormat =
                    {
                    Style = Heading2Style
                    }
                });

            // Add the content of Chapter 2 / Subchapter 2-1.
            section.Blocks.Add(
                        new Paragraph(dc,
                            "Requires only .Net 4.0 or above. Our product is compatible with all .Net languages and supports all Operating Systems where .Net Framework can be used. Note that Document .Net is entirely written in managed C#, which makes it absolutely standalone and an independent library. Of course, No dependency on Microsoft Word.")
                        {
                            ParagraphFormat = new ParagraphFormat
                            {
                                LeftIndentation = 10,
                                RightIndentation = 10,
                                SpecialIndentation = 20,
                                LineSpacing = 20,
                                LineSpacingRule = LineSpacingRule.Exactly,
                                SpaceBefore = 20,
                                SpaceAfter = 20
                            }
                        });

            // Update TOC (TOC can be updated only after all document content is added).
            var tableofcontents = (TableOfEntries)dc.GetChildElements(true, ElementType.TableOfEntries).FirstOrDefault();
            tableofcontents.Update();

            // Apply the style for the TOC.
            foreach (Paragraph par in tableofcontents.Entries)
            {
                par.ParagraphFormat.Style = TOCStyle;
            }

            // Update TOC's page numbers.
            // Page numbers are automatically updated in that case.
            dc.GetPaginator(new PaginatorOptions() { UpdateFields = true });

            // Save the document as DOCX file.
            dc.Save(resultFile);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(resultFile) { UseShellExecute = true });
        }
    }
}

Download

Option Infer On

Imports System
Imports System.Linq
Imports SautinSoft.Document

Module Sample
    Sub Main()
        ExtendedTOC()
    End Sub
    ''' Get your free 100-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Create extended table of contents in word document.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/create-extended-table-of-contents-in-word-document-net-csharp-vb.php
    ''' </remarks>
    Sub ExtendedTOC()
        Dim resultFile As String = "Extended-Table-Of-Contents.docx"
        ' First of all, create an instance of DocumentCore.
        Dim dc As New DocumentCore()

        ' Create and add Heading1 style. For "Chapter 1" and "Chapter 2".
        Dim Heading1Style As ParagraphStyle = CType(Style.CreateStyle(StyleTemplateType.Heading1, dc), ParagraphStyle)
        Heading1Style.ParagraphFormat.LineSpacing = 3
        Heading1Style.CharacterFormat.Size = 18
        ' #358CCB - blue
        Heading1Style.CharacterFormat.FontColor = New Color("#358CCB")
        dc.Styles.Add(Heading1Style)

        ' Create and add Heading2 style. For "SupChapter 1-1" and "SubChapter 2-1".
        Dim Heading2Style As ParagraphStyle = CType(Style.CreateStyle(StyleTemplateType.Heading2, dc), ParagraphStyle)
        Heading2Style.ParagraphFormat.LineSpacing = 2
        Heading2Style.CharacterFormat.Size = 14
        ' #FF9900 - orange
        Heading2Style.CharacterFormat.FontColor = New Color("#FF9900")
        dc.Styles.Add(Heading2Style)

        ' Create and add TOC style.
        Dim TOCStyle As ParagraphStyle = CType(Style.CreateStyle(StyleTemplateType.Subtitle, dc), ParagraphStyle)
        TOCStyle.ParagraphFormat.OutlineLevel = OutlineLevel.BodyText
        TOCStyle.ParagraphFormat.Alignment = HorizontalAlignment.Center
        TOCStyle.CharacterFormat.Bold = True
        ' #358CCB - blue
        TOCStyle.CharacterFormat.FontColor = New Color("#358CCB")
        dc.Styles.Add(TOCStyle)

        ' Add new section.
        Dim section As New Section(dc)
        dc.Sections.Add(section)

        ' Add TOC Header.
        section.Blocks.Add(New Paragraph(dc, "Table of Contents") With {
            .ParagraphFormat = New ParagraphFormat With {.Style = TOCStyle}
        })

        ' Create and add TOC (Table of Contents).
        section.Blocks.Add(New TableOfEntries(dc, FieldType.TOC))

        ' Add TOC Ending.
        section.Blocks.Add(New Paragraph(dc, "The End") With {
            .ParagraphFormat = New ParagraphFormat With {
                .Alignment = HorizontalAlignment.Center,
                .BackgroundColor = Color.Gray
            }
        })

        ' Add the document content (Chapter 1).
        ' Add Chapter 1.
        section.Blocks.Add(New Paragraph(dc, "Chapter 1") With {
            .ParagraphFormat = New ParagraphFormat With {
                .Style = Heading1Style,
                .PageBreakBefore = True
            }
        })

        ' Add SubChapter 1-1.
        section.Blocks.Add(New Paragraph(dc, String.Format("Subchapter 1-1")) With {
            .ParagraphFormat = New ParagraphFormat With {.Style = Heading2Style}
        })

        ' Add the content of Chapter 1 / Subchapter 1-1.
        section.Blocks.Add(New Paragraph(dc, "Document.Net will help you in development of applications which operates with DOCX, RTF, PDF, HTML and Text documents.After adding of the reference to(SautinSoft.Document.dll) - it's 100% C# managed assembly you will be able to create a new document, parse an existing, modify anything what you want.") With {
            .ParagraphFormat = New ParagraphFormat With {
                .LeftIndentation = 10,
                .RightIndentation = 10,
                .SpecialIndentation = 20,
                .LineSpacing = 20,
                .LineSpacingRule = LineSpacingRule.Exactly,
                .SpaceBefore = 20,
                .SpaceAfter = 20
            }
        })

        ' Let's add another page break into.
        section.Blocks.Add(New Paragraph(dc, New SpecialCharacter(dc, SpecialCharacterType.PageBreak)))

        ' Add the document content (Chapter 2).
        ' Add Chapter 2.
        section.Blocks.Add(New Paragraph(dc, "Chapter 2") With {
            .ParagraphFormat = New ParagraphFormat With
            {.Style = Heading1Style}
        })

        ' Add SubChapter 2-1.
        section.Blocks.Add(New Paragraph(dc, String.Format("Subchapter 2-1")) With {
            .ParagraphFormat = New ParagraphFormat With {.Style = Heading2Style}
        })

        ' Add the content of Chapter 2 / Subchapter 2-1.
        section.Blocks.Add(New Paragraph(dc, "Requires only .Net 4.0 or above. Our product is compatible with all .Net languages and supports all Operating Systems where .Net Framework can be used. Note that Document .Net is entirely written in managed C#, which makes it absolutely standalone and an independent library. Of course, No dependency on Microsoft Word.") With {
            .ParagraphFormat = New ParagraphFormat With {
                .LeftIndentation = 10,
                .RightIndentation = 10,
                .SpecialIndentation = 20,
                .LineSpacing = 20,
                .LineSpacingRule = LineSpacingRule.Exactly,
                .SpaceBefore = 20,
                .SpaceAfter = 20
            }
        })

        ' Update TOC (TOC can be updated only after all document content is added).
        Dim tableofcontents = CType(dc.GetChildElements(True, ElementType.TableOfEntries).FirstOrDefault(), TableOfEntries)
        tableofcontents.Update()

        ' Apply the style for the TOC.
        For Each par As Paragraph In tableofcontents.Entries
            par.ParagraphFormat.Style = TOCStyle
        Next par

        ' Update TOC's page numbers.
        ' Page numbers are automatically updated in that case.
        dc.GetPaginator(New PaginatorOptions() With {.UpdateFields = True})

        ' Save the document as DOCX file.
        dc.Save(resultFile)

        ' Open the result for demonstration purposes.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(resultFile) With {.UseShellExecute = True})
    End Sub

End Module

Download


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.