How to create 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. Update TOC.
  6. Save the document in PDF format.

Let's create a simple DOCX document with TOC containg two Chapters and SubChapters:

Simple DOCX document

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 Headings style for TOC.
    
    ParagraphStyle Heading1Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading1, document);	
        document.Styles.Add(Heading1Style);
    ParagraphStyle Heading2Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading2, document);			
        document.Styles.Add(Heading2Style);
    
    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.
    If you want to learn more about styles and formatting, please go to our example about advanced formatting.
  4. Add new Section with Paragraphs into our document.
    
        Section section = new Section(document);
        document.Sections.Add(section);
        
        section.Blocks.Add(new Paragraph(document, "Table of Contents"));
        section.Blocks.Add(new TableOfEntries(document, FieldType.TOC));
        section.Blocks.Add(new Paragraph(document, "The end."));
    
    Section is a collection of Block elements that are grouped by a unify page properties concept and having specific headers and footers.
    Create TOC by applying heading styles — for example, Heading 1, Heading 2, and Heading 3 — to the text that you want to include in the table of contents.
    Document.Net searches for those headings and then inserts the table of contents into your document.
  5. Create a new paragraph for Chapter and SubChapter.
    
        // Add document content.
    			// Add Chapter 1
        section.Blocks.Add(
    				new Paragraph(document, "Chapter 1")
    				{
    					ParagraphFormat =
    					{
    						Style = Heading1Style
    					}
    				});
    
    			// Add SubChapter 1-1
    			section.Blocks.Add(
    						new Paragraph(document, String.Format("Subchapter 1-1"))
    						{
    							ParagraphFormat =
    							{
    							Style = Heading2Style
    							}
    						});
    			// Add the content of Chapter 1 / Subchapter 1-1
    			section.Blocks.Add(
    						new Paragraph(document,
    							"«Document .Net» will help you in development of applications which operates with DOCX, RTF, PDF 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."));
    
    
    Paragraph is a Block derived element used to group Inline elements like a Run, Shape, Picture, Field etc.
  6. When you create a 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 toc = (TableOfEntries)document.GetChildElements(true, ElementType.TableOfEntries).FirstOrDefault();
       toc.Update();
    
    // Update TOC's page numbers.
    // Page numbers are automatically updated in that case.
       document.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("Table-Of-Contents.docx");
    
    The paginator is used to divide a document into discrete pages.
  8. Save our document as DOCX.
    
        // Save DOCX to a file
        document.Save("Table-Of-Contents.docx");
    
    Download the resulting Docx-file: Table-Of-Contents.docx

Complete code

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

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

            TOC();
        }

        /// <summary>
        /// Create a document with table of content.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/table-of-contents-toc.php
        /// </remarks>
        public static void TOC()
        {
            string resultFile = "Table-Of-Contents.docx";

            // Let's create a simple document.
            DocumentCore dc = new DocumentCore();

            // Create and add Heading 1 style for TOC.
            ParagraphStyle Heading1Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading1, dc);
            dc.Styles.Add(Heading1Style);

            // Create and add Heading 2 style for TOC.
            ParagraphStyle Heading2Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading2, dc);
            dc.Styles.Add(Heading2Style);

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

            // Add TOC title in the DOCX document.
            section.Blocks.Add(new Paragraph(dc, "Table of Contents"));

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

            section.Blocks.Add(new Paragraph(dc, "The end."));

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

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

            // 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 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."));

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

            // Add document content.
            // 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."));

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

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

            // Save DOCX to a 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()
        TOC()
    End Sub
    ''' Get your free 100-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Create a document with table of content.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/table-of-contents-toc.php
    ''' </remarks>
    Sub TOC()
        Dim resultFile As String = "Table-Of-Contents.docx"

        ' Let's create a simple document.
        Dim dc As New DocumentCore()

        ' Create and add Heading 1 style for TOC.
        Dim Heading1Style As ParagraphStyle = CType(Style.CreateStyle(StyleTemplateType.Heading1, dc), ParagraphStyle)
        dc.Styles.Add(Heading1Style)

        ' Create and add Heading 2 style for TOC.
        Dim Heading2Style As ParagraphStyle = CType(Style.CreateStyle(StyleTemplateType.Heading2, dc), ParagraphStyle)
        dc.Styles.Add(Heading2Style)

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

        ' Add TOC title in the DOCX document.
        section.Blocks.Add(New Paragraph(dc, "Table of Contents"))

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

        section.Blocks.Add(New Paragraph(dc, "The end."))

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

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

        ' 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 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."))

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

        ' Add document content.
        ' 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."))

        ' Update TOC (TOC can be updated only after all document content is added).
        'INSTANT VB NOTE: The variable toc was renamed since Visual Basic does not handle local variables named the same as class members well:
        Dim toc_Renamed = CType(dc.GetChildElements(True, ElementType.TableOfEntries).FirstOrDefault(), TableOfEntries)
        toc_Renamed.Update()

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

        ' Save DOCX to a 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.