How to create extended 'Table of Contents' in a Word document using C# and VB.Net

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;
                Heading2Style.ParagraphFormat.LineSpacing = 2;
                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 });
    
    Gets the document paginator and updates the document based on the specified options. The paginator options used to specify which parts of the document to update while paginating it.
  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)
        {
            ExtendedTOC();
        }
        public static void ExtendedTOC()
        {
            // 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;
            Heading2Style.ParagraphFormat.LineSpacing = 2;
            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("Extended-Table-Of-Contents.docx");

            // Open the result for demonstation purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("Extended-Table-Of-Contents.docx") { UseShellExecute = true });
        }
    }
}

Download.

        
            Imports System.Linq
Imports SautinSoft.Document

Module Module1

    Sub Main()

        ' Let's create a simple DOCX 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
        Dim chapter1 As New Paragraph(dc, "Chapter 1")
        chapter1.ParagraphFormat.Style = Heading1Style
        section.Blocks.Add(chapter1)

        ' Add SubChapter 1-1
        Dim subChapter11 As New Paragraph(dc, String.Format("Subchapter 1-1"))
        subChapter11.ParagraphFormat.Style = Heading2Style
        section.Blocks.Add(subChapter11)

        ' 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
        Dim chapter2 As New Paragraph(dc, "Chapter 2")
        chapter2.ParagraphFormat.Style = Heading2Style
        section.Blocks.Add(chapter2)


        ' Add SubChapter 2-1
        Dim subChapter21 As New Paragraph(dc, String.Format("Subchapter 2-1"))
        subChapter21.ParagraphFormat.Style = Heading2Style
        section.Blocks.Add(subChapter21)

        ' 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).
        Dim myToc = CType(dc.GetChildElements(True, ElementType.TableOfEntries).FirstOrDefault(), TableOfEntries)
        myToc.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("Table-Of-Contents.docx")

        ' Open the result for demonstation purposes.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo("Table-Of-Contents.docx") With {.UseShellExecute = True})
    End Sub
End Module
          

Download.

© SautinSoft 2020