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

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 main 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 group of Paragraphs and other Block elements that have a specific set of properties used to define the pages. For each section you can also specify an own Page Properties and Headers & 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 container for all content elements. As well as the usual paragraph, it may contain a text, pictures, tables and so forth.
  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 });
    
    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("Table-Of-Contents.docx");
    
    Download the resulting Docx-file: Table-Of-Contens.docx
 

Complete code


       public static void TOC()
		{

			// Let's create a simple DOCX document.
			DocumentCore document = new DocumentCore();
			// DocumentCore.Serial = "put your serial here";

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

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

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

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

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

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

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

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

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

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


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

			// Add the content of Chapter 2 / Subchapter 2-1
			section.Blocks.Add(
						new Paragraph(document,
							"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)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 });

			// Save DOCX to a file
			document.Save("Table-Of-Contents.docx");
		}
        
                Imports System
Imports System.IO
Imports SautinSoft.Document

Module ExampleVB
    Sub Main()
        ExtendedTOC()
    End Sub
    Public Sub ExtendedTOC()
        ' 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(&H358CCB)
        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(&HFF9900)
        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
        Heading2Style.ParagraphFormat.LineSpacing = 2
        TOCStyle.ParagraphFormat.Alignment = HorizontalAlignment.Center
        TOCStyle.CharacterFormat.Bold = True
        ' #358CCB - blue
        TOCStyle.CharacterFormat.FontColor = New Color(&H358CCB)
        dc.Styles.Add(TOCStyle)

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

        ' Add TOC Header.
        Dim pTocHeader As New Paragraph(dc, "Table of Contents")
        pTocHeader.ParagraphFormat.Style = TOCStyle
        section.Blocks.Add(pTocHeader)

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

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

        ' Add the document content (Chapter 1).
        ' Add Chapter 1.
        Dim pChapter1 As New Paragraph(dc, "Chapter 1")
        pChapter1.ParagraphFormat.Style = Heading1Style
        pChapter1.ParagraphFormat.PageBreakBefore = True
        section.Blocks.Add(pChapter1)

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

        ' 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("Extended-Table-Of-Contents.docx")
    End Sub
End Module



          
© SautinSoft 2017