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

Table of Contents (TOC) can be easily updated with GemBox.Document.

Following sample demonstrates how to create a document with different heading paragraphs, insert a TOC element and update it.

Screenshot

TOC Screenshot

See the full code below, use RUN EXAMPLE to execute.


1using System;
2using System.IO;
3using System.Linq;
4using GemBox.Document;
5using GemBox.Document.Drawing;
6
7class Sample
8{
9    [STAThread]
10    static void Main(string[] args)
11    {
12        // If using Professional version, put your serial key below.
13        ComponentInfo.SetLicense("FREE-LIMITED-KEY");
14
15        DocumentModel document = new DocumentModel();
16
17        int heading1Count = 3;
18        int heading2Count = 5;
19
20        // Create and add Heading 1 style.
21        ParagraphStyle heading1Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading1, document);
22        document.Styles.Add(heading1Style);
23
24        // Create and add Heading 2 style.
25        ParagraphStyle heading2Style = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading2, document);
26        document.Styles.Add(heading2Style);
27
28        // Create and add TOC style.
29        ParagraphStyle tocHeading = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading1, document);
30        tocHeading.Name = "toc";
31        tocHeading.ParagraphFormat.OutlineLevel = OutlineLevel.BodyText;
32        document.Styles.Add(tocHeading);
33
34        Section section = new Section(document);
35        document.Sections.Add(section);
36
37        // Add TOC title.
38        section.Blocks.Add(
39            new Paragraph(document, "Contents")
40            {
41                ParagraphFormat =
42                {
43                    Style = tocHeading
44                }
45            });
46
47        // Create and add new TOC.
48        section.Blocks.Add(
49            new TableOfEntries(document, FieldType.TOC));
50
51        section.Blocks.Add(
52            new Paragraph(document,
53                new SpecialCharacter(document, SpecialCharacterType.PageBreak)));
54
55        // Add document content.
56        for (int i = 0; i < heading1Count; i++)
57        {
58            // Heading 1
59            section.Blocks.Add(
60                new Paragraph(document, "Heading 1 (" + (i + 1) + ")")
61                {
62                    ParagraphFormat =
63                    {
64                        Style = heading1Style
65                    }
66                });
67
68            for (int j = 0; j < heading2Count; j++)
69            {
70                // Heading 2
71                section.Blocks.Add(
72                    new Paragraph(document, String.Format("Heading 2 ({0}-{1})", i + 1, j + 1))
73                    {
74                        ParagraphFormat =
75                        {
76                            Style = heading2Style
77                        }
78                    });
79
80                // Heading 2 content.
81                section.Blocks.Add(
82                    new Paragraph(document,
83                        "GemBox.Document is a .NET component that enables developers to read, write, convert and print document files (DOCX, DOC, PDF, HTML, XPS, RTF and TXT) from .NET applications in a simple and efficient way."));
84            }
85        }
86
87        // Update TOC (TOC can be updated only after all document content is added).
88        var toc = (TableOfEntries)document.GetChildElements(true, ElementType.TableOfEntries).First();
89        toc.Update();
90
91        // Update TOC's page numbers.
92        // NOTE: This is not necessary when printing and saving to PDF, XPS or an image format.
93        // Page numbers are automatically updated in that case.
94        document.GetPaginator(new PaginatorOptions() { UpdateFields = true });
95
96        document.Save("TOC.docx");
97    }
98}
1Imports System
2Imports System.IO
3Imports System.Linq
4Imports GemBox.Document
5Imports GemBox.Document.Drawing
6
7Module Samples
8
9    Sub Main()
10
11        ' If using Professional version, put your serial key below.
12        ComponentInfo.SetLicense("FREE-LIMITED-KEY")
13
14        Dim document As DocumentModel = New DocumentModel
15
16        Dim heading1Count As Integer = 3
17        Dim heading2Count As Integer = 5
18
19        ' Create and add Heading 1 style.
20        Dim heading1Style As ParagraphStyle = DirectCast(Style.CreateStyle(StyleTemplateType.Heading1, document), ParagraphStyle)
21        document.Styles.Add(heading1Style)
22
23        ' Create and add Heading 2 style.
24        Dim heading2Style As ParagraphStyle = DirectCast(Style.CreateStyle(StyleTemplateType.Heading2, document), ParagraphStyle)
25        document.Styles.Add(heading2Style)
26
27        ' Create and add TOC style.
28        Dim tocHeading As ParagraphStyle = DirectCast(Style.CreateStyle(StyleTemplateType.Heading1, document), ParagraphStyle)
29        tocHeading.Name = "toc"
30        tocHeading.ParagraphFormat.OutlineLevel = OutlineLevel.BodyText
31        document.Styles.Add(tocHeading)
32
33        Dim section As New Section(document)
34        document.Sections.Add(section)
35
36        ' Add TOC title.
37        section.Blocks.Add(
38            New Paragraph(document, "Contents") With { _
39                .ParagraphFormat = New ParagraphFormat() With {.Style = tocHeading}})
40
41        ' Create and add new TOC.
42        section.Blocks.Add(
43            New TableOfEntries(document, FieldType.TOC))
44
45        section.Blocks.Add(
46            New Paragraph(document,
47                New SpecialCharacter(document, SpecialCharacterType.PageBreak)))
48
49        ' Add document content.
50        For i As Integer = 0 To heading1Count - 1
51
52            ' Heading 1
53            section.Blocks.Add(
54                New Paragraph(document, "Heading 1 (" & (i + 1) & ")") With { _
55                 .ParagraphFormat = New ParagraphFormat() With { _
56                     .Style = heading1Style} _
57                })
58
59            For j As Integer = 0 To heading2Count - 1
60                ' Heading 2
61                section.Blocks.Add(
62                    New Paragraph(document, String.Format("Heading 2 ({0}-{1})", i + 1, j + 1)) With { _
63                     .ParagraphFormat = New ParagraphFormat() With { _
64                         .Style = heading2Style} _
65                })
66
67                ' Heading 2 content.
68                section.Blocks.Add(
69                    New Paragraph(document,
70                        "GemBox.Document is a .NET component that enables developers to read, write, convert and print document files (DOCX, DOC, PDF, HTML, XPS, RTF and TXT) from .NET applications in a simple and efficient way."))
71            Next
72        Next
73
74        ' Update TOC (TOC can be updated only after all document content is added).
75        Dim toc = DirectCast(document.GetChildElements(True, ElementType.TableOfEntries).First(), TableOfEntries)
76        toc.Update()
77
78        ' Update TOC's page numbers.
79        ' NOTE: This is not necessary when printing and saving to PDF, XPS or an image format.
80        ' Page numbers are automatically updated in that case.
81        document.GetPaginator(New PaginatorOptions() With {.UpdateFields = True})
82
83        document.Save("TOC.docx")
84
85    End Sub
86
87End Module

Check next sample or find out more about GemBox.Document and GemBox Software.