Table of Content

This example demonstrates how to generate Table of Contents (TOC) with some of the options available. Click on the Description button to see the full description of the example.

Lower heading level: Upper heading level:

Table of Contents (TOC) example demonstrates the TOC feature of the Word library of Document Expert package. It will allow you to manipulate TOC of a word document with a few lines of code.

Usage of some of the available options are shown here.

  • Heading Upper Level: Ending heading level of the table of contents.
  • Heading Lower Level: Starting heading level of the table of contents.
  • Include Page number: Value indicating whether to show page numbers in table of contents.
  • Right Align Page Number: Value indicating whether to show page numbers as right aligned.
  • Use Hyperlink: Value indicating whether to use hyperlinks for the levels.
  • Use Outline Level: Value indicating whether to use outline levels. Outline level is the level at which the paragraph appears in Outline View.
  • Update table of content: Value indicating whether to update the table of contents by default or not.
  • Use custom styles: Checking this option will apply some custom styles to each level of TOC.

The version dropdown list allows you select the format of the generated word document.

Once all the options are selected, please click on the generate button to see the word document in the selected format with sample TOC.

Please look at the product documentation to understand the complete list of Table of Contents (TOC) options available.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;

using OfficeComponent.Word;


namespace OfficeComponent.Samples
{
    class TableofContentExample : WordExampleBase
#if WEB
, IUIExample
#endif
    {
        public int LowerHeadingLevel { get; set; }
        public int UpperHeadingLevel { get; set; }
        public bool IncludePageNumbers { get; set; }
        public bool RightAlignPageNumbers { get; set; }
        public bool UseHyperlinks { get; set; }
        public bool UseOutlineLevels { get; set; }
        public bool UpdateToc { get; set; }
        public bool CreateCustomStyles { get; set; }

        public TableofContentExample()
            : base(null,null)
        {

        }

        public TableofContentExample(string commonDataPath, string outputDir)
            : base(commonDataPath, outputDir)
        {

        }

        public TableofContentExample(string commonDataPath, string outputDir, string xmlFile)
            : base(commonDataPath, outputDir, xmlFile)
        {

        }

        public override string Execute()
        {
#if WEB
            ProcessForm();
#endif
            if (LowerHeadingLevel < 1 || LowerHeadingLevel > 9)
            {
                ShowError("Lower heading level must be from 1 to 9.");
                return null;
            }

            if (UpperHeadingLevel < 1 || UpperHeadingLevel > 9)
            {
                ShowError("Upper heading level must be from 1 to 9.");
                return null;
            }

            if (UpperHeadingLevel < LowerHeadingLevel)
            {
                ShowError("Heading level range is not valid. Lower Heading Level must be lower than Upper Heading Level");
                return null;
            }            

            // Create a new instance of the WordDocument class.
            WordDocument doc = new WordDocument();

            doc.EnsureMinimum();

            Paragraph para = doc.LastParagraph;

            para.AppendText("\t\t\t\t\tTable of Contents Demo\n\n").CharacterFormat.FontName = "Arial";
            if (!UpdateToc)
            {
                para.AppendText("Select TOC and press F9 to update the Table of Contents\n\n").CharacterFormat.Italic = true;
                TextRange text = para.AppendText("This sample demonstrates the TOC insertion in a word document. Note that OfficeComponentWord can only insert TOC field in a word document. It can not refresh or create TOC field. MS Word refreshes the TOC field after insertion. Please update the field or press F9 key to refresh the TOC.\n\n");
                text.CharacterFormat.Italic = true;
                text.CharacterFormat.FontName = "Arial";
                text.CharacterFormat.FontSize = 9;
            }

            const string title = "Table of Contents\n";
            para.AppendText(title).CharacterFormat.Bold = true;

            //Insert TOC
            TableOfContent toc = para.AppendTOC(1, 3);

            para.ApplyStyle(StyleIdentifier.Heading4);
            //Apply built-in paragraph formatting
            Section section = doc.LastSection;
            if (!CreateCustomStyles)
            {
                #region Default Styles
                Paragraph newPara = section.AddParagraph();
                newPara = section.AddParagraph();
                newPara.AppendBreak(BreakType.PageBreak);
                newPara.AppendText("Default styles");
                newPara.ApplyStyle(StyleIdentifier.Heading1);
                newPara = section.AddParagraph();
                newPara.AppendText("This is the heading1 of built in style.");

                section.AddParagraph();
                newPara = section.AddParagraph();
                newPara.AppendText("Section1");
                newPara.ApplyStyle(StyleIdentifier.Heading2);
                newPara = section.AddParagraph();
                newPara.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.");

                section.AddParagraph();
                newPara = section.AddParagraph();
                newPara.AppendText("Paragraph1");
                newPara.ApplyStyle(StyleIdentifier.Heading3);
                newPara = section.AddParagraph();
                newPara.AppendText("This is the heading3 of built in style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text.");

                section.AddParagraph();
                newPara = section.AddParagraph();
                newPara.AppendText("Paragraph2");
                newPara.ApplyStyle(StyleIdentifier.Heading3);
                newPara = section.AddParagraph();
                newPara.AppendText("This is the heading3 of built in style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph.");

                section.AddParagraph();
                section = doc.AddSection();
                section.BreakCode = SectionBreakCode.NewPage;
                newPara = section.AddParagraph();
                newPara.AppendText("Section2");
                newPara.ApplyStyle(StyleIdentifier.Heading2);
                newPara = section.AddParagraph();
                newPara.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.");

                section.AddParagraph();
                newPara = section.AddParagraph();
                newPara.AppendText("Paragraph1");
                newPara.ApplyStyle(StyleIdentifier.Heading3);
                newPara = section.AddParagraph();
                newPara.AppendText("This is the heading3 of built in style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text.");

                section.AddParagraph();
                newPara = section.AddParagraph();
                newPara.AppendText("Paragraph2");
                newPara.ApplyStyle(StyleIdentifier.Heading3);
                newPara = section.AddParagraph();
                newPara.AppendText("This is the heading3 of built in style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph.");

                #endregion
            }
            else
            {
                #region Custom styles

                //Custom styles.
                ParagraphStyle pStyle1 = doc.AddParagraphStyle("MyStyle1");
                ParagraphStyle pStyle2 = doc.AddParagraphStyle("MyStyle2");
                ParagraphStyle pStyle3 = doc.AddParagraphStyle("MyStyle3");

                //Set the Heading Styles to false in order to define custom levels to TOC.
                toc.UseHeadingStyles = false;

                //Set the TOC level style which determines; based on which the TOC should be created.
                toc.SetTOCLevelStyle(1, "MyStyle1");
                toc.SetTOCLevelStyle(2, "MyStyle2");
                toc.SetTOCLevelStyle(3, "MyStyle3");
                section = doc.AddSection();

                pStyle1.CharacterFormat.FontName = "Cambria";
                pStyle1.CharacterFormat.FontSize = 30f;

                para = section.AddParagraph();

                para.AppendText("Custom Styles");
                para.ApplyStyle("MyStyle1");
                para = doc.LastSection.AddParagraph();
                para.AppendText("This is the heading1 of built in style.");

                pStyle2.CharacterFormat.FontName = "Cambria";
                pStyle2.CharacterFormat.FontSize = 20f;

                doc.LastSection.AddParagraph();

                para = doc.LastSection.AddParagraph();
                para.AppendText("Section1");
                para.ApplyStyle("MyStyle2");
                para = doc.LastSection.AddParagraph();
                para.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.");

                pStyle3.CharacterFormat.FontName = "Cambria";
                pStyle3.CharacterFormat.FontSize = 14f;

                doc.LastSection.AddParagraph();

                para = doc.LastSection.AddParagraph();
                para.AppendText("Section2");
                para.ApplyStyle("MyStyle3");
                para = doc.LastSection.AddParagraph();
                para.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.");

                #endregion
            }

            toc.IncludePageNumbers = IncludePageNumbers;
            toc.RightAlignPageNumbers = RightAlignPageNumbers;
            toc.UseHyperlinks = UseHyperlinks;
            toc.LowerHeadingLevel = Convert.ToInt32(LowerHeadingLevel);
            toc.UpperHeadingLevel = Convert.ToInt32(UpperHeadingLevel);
            //Right click text. Select Paragraph option. Set OutlineLevel. Update TOC toc see the text added in TOC.
            toc.UseOutlineLevels = UseOutlineLevels;
            //Select the text that should be marked as Table of contents.
            //Press ALT+SHIFT+O. A dialog box will appear with options to enter the text, select the table identifier and level.
            //Choose the table identifier and level for the test and click �Mark�. Update TOC toc see the text added in TOC.
            //Sets the Table Identifier if necessary.
            //toc.TableID = "B";              
            //Updates the table of contents.
            if (UpdateToc)
                doc.UpdateTableOfContents();

            string fileName = Path.Combine(OutputDir, this.GetType().Name + "_" + Guid.NewGuid().ToString() + GetExtension(SaveAsFormat));
            // Save the document.
            doc.Save(fileName, SaveAsFormat);

            // Close the document.
            doc.Close();

            return fileName;
        }

#if WEB
        void ProcessForm()
        {
            
        }
#endif
    }
}
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Text

Imports OfficeComponent.Word


Namespace OfficeComponent.Samples
#If WEB Then
	Friend Class TableofContentExample
		Inherits WordExampleBase
		Implements IUIExample
#Else
	Friend Class TableofContentExample
		Inherits WordExampleBase
#End If
		Private privateLowerHeadingLevel As Integer
		Public Property LowerHeadingLevel() As Integer
			Get
				Return privateLowerHeadingLevel
			End Get
			Set(ByVal value As Integer)
				privateLowerHeadingLevel = value
			End Set
		End Property
		Private privateUpperHeadingLevel As Integer
		Public Property UpperHeadingLevel() As Integer
			Get
				Return privateUpperHeadingLevel
			End Get
			Set(ByVal value As Integer)
				privateUpperHeadingLevel = value
			End Set
		End Property
		Private privateIncludePageNumbers As Boolean
		Public Property IncludePageNumbers() As Boolean
			Get
				Return privateIncludePageNumbers
			End Get
			Set(ByVal value As Boolean)
				privateIncludePageNumbers = value
			End Set
		End Property
		Private privateRightAlignPageNumbers As Boolean
		Public Property RightAlignPageNumbers() As Boolean
			Get
				Return privateRightAlignPageNumbers
			End Get
			Set(ByVal value As Boolean)
				privateRightAlignPageNumbers = value
			End Set
		End Property
		Private privateUseHyperlinks As Boolean
		Public Property UseHyperlinks() As Boolean
			Get
				Return privateUseHyperlinks
			End Get
			Set(ByVal value As Boolean)
				privateUseHyperlinks = value
			End Set
		End Property
		Private privateUseOutlineLevels As Boolean
		Public Property UseOutlineLevels() As Boolean
			Get
				Return privateUseOutlineLevels
			End Get
			Set(ByVal value As Boolean)
				privateUseOutlineLevels = value
			End Set
		End Property
		Private privateUpdateToc As Boolean
		Public Property UpdateToc() As Boolean
			Get
				Return privateUpdateToc
			End Get
			Set(ByVal value As Boolean)
				privateUpdateToc = value
			End Set
		End Property
		Private privateCreateCustomStyles As Boolean
		Public Property CreateCustomStyles() As Boolean
			Get
				Return privateCreateCustomStyles
			End Get
			Set(ByVal value As Boolean)
				privateCreateCustomStyles = value
			End Set
		End Property

		Public Sub New()
			MyBase.New(Nothing,Nothing)

		End Sub

		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String)
			MyBase.New(commonDataPath, outputDir)

		End Sub

		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String, ByVal xmlFile As String)
			MyBase.New(commonDataPath, outputDir, xmlFile)

		End Sub

		Public Overrides Function Execute() As String
#If WEB Then
			ProcessForm()
#End If
			If LowerHeadingLevel < 1 OrElse LowerHeadingLevel > 9 Then
				ShowError("Lower heading level must be from 1 to 9.")
				Return Nothing
			End If

			If UpperHeadingLevel < 1 OrElse UpperHeadingLevel > 9 Then
				ShowError("Upper heading level must be from 1 to 9.")
				Return Nothing
			End If

			If UpperHeadingLevel < LowerHeadingLevel Then
				ShowError("Heading level range is not valid. Lower Heading Level must be lower than Upper Heading Level")
				Return Nothing
			End If

			' Create a new instance of the WordDocument class.
			Dim doc As New WordDocument()

			doc.EnsureMinimum()

			Dim para As Paragraph = doc.LastParagraph

			para.AppendText(vbTab & vbTab & vbTab & vbTab & vbTab & "Table of Contents Demo" & vbLf & vbLf).CharacterFormat.FontName = "Arial"
			If Not UpdateToc Then
				para.AppendText("Select TOC and press F9 to update the Table of Contents" & vbLf & vbLf).CharacterFormat.Italic = True
				Dim text As TextRange = para.AppendText("This sample demonstrates the TOC insertion in a word document. Note that OfficeComponentWord can only insert TOC field in a word document. It can not refresh or create TOC field. MS Word refreshes the TOC field after insertion. Please update the field or press F9 key to refresh the TOC." & vbLf & vbLf)
				text.CharacterFormat.Italic = True
				text.CharacterFormat.FontName = "Arial"
				text.CharacterFormat.FontSize = 9
			End If

'INSTANT VB NOTE: The variable title was renamed since Visual Basic does not handle local variables named the same as class members well:
			Const title_Renamed As String = "Table of Contents" & vbLf
			para.AppendText(title_Renamed).CharacterFormat.Bold = True

			'Insert TOC
			Dim toc As TableOfContent = para.AppendTOC(1, 3)

			para.ApplyStyle(StyleIdentifier.Heading4)
			'Apply built-in paragraph formatting
			Dim section As Section = doc.LastSection
			If Not CreateCustomStyles Then
'				#Region "Default Styles"
				Dim newPara As Paragraph = section.AddParagraph()
				newPara = section.AddParagraph()
				newPara.AppendBreak(BreakType.PageBreak)
				newPara.AppendText("Default styles")
				newPara.ApplyStyle(StyleIdentifier.Heading1)
				newPara = section.AddParagraph()
				newPara.AppendText("This is the heading1 of built in style.")

				section.AddParagraph()
				newPara = section.AddParagraph()
				newPara.AppendText("Section1")
				newPara.ApplyStyle(StyleIdentifier.Heading2)
				newPara = section.AddParagraph()
				newPara.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.")

				section.AddParagraph()
				newPara = section.AddParagraph()
				newPara.AppendText("Paragraph1")
				newPara.ApplyStyle(StyleIdentifier.Heading3)
				newPara = section.AddParagraph()
				newPara.AppendText("This is the heading3 of built in style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text.")

				section.AddParagraph()
				newPara = section.AddParagraph()
				newPara.AppendText("Paragraph2")
				newPara.ApplyStyle(StyleIdentifier.Heading3)
				newPara = section.AddParagraph()
				newPara.AppendText("This is the heading3 of built in style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph.")

				section.AddParagraph()
				section = doc.AddSection()
				section.BreakCode = SectionBreakCode.NewPage
				newPara = section.AddParagraph()
				newPara.AppendText("Section2")
				newPara.ApplyStyle(StyleIdentifier.Heading2)
				newPara = section.AddParagraph()
				newPara.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.")

				section.AddParagraph()
				newPara = section.AddParagraph()
				newPara.AppendText("Paragraph1")
				newPara.ApplyStyle(StyleIdentifier.Heading3)
				newPara = section.AddParagraph()
				newPara.AppendText("This is the heading3 of built in style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text.")

				section.AddParagraph()
				newPara = section.AddParagraph()
				newPara.AppendText("Paragraph2")
				newPara.ApplyStyle(StyleIdentifier.Heading3)
				newPara = section.AddParagraph()
				newPara.AppendText("This is the heading3 of built in style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph.")

'				#End Region
			Else
'				#Region "Custom styles"

				'Custom styles.
				Dim pStyle1 As ParagraphStyle = doc.AddParagraphStyle("MyStyle1")
				Dim pStyle2 As ParagraphStyle = doc.AddParagraphStyle("MyStyle2")
				Dim pStyle3 As ParagraphStyle = doc.AddParagraphStyle("MyStyle3")

				'Set the Heading Styles to false in order to define custom levels to TOC.
				toc.UseHeadingStyles = False

				'Set the TOC level style which determines; based on which the TOC should be created.
				toc.SetTOCLevelStyle(1, "MyStyle1")
				toc.SetTOCLevelStyle(2, "MyStyle2")
				toc.SetTOCLevelStyle(3, "MyStyle3")
				section = doc.AddSection()

				pStyle1.CharacterFormat.FontName = "Cambria"
				pStyle1.CharacterFormat.FontSize = 30F

				para = section.AddParagraph()

				para.AppendText("Custom Styles")
				para.ApplyStyle("MyStyle1")
				para = doc.LastSection.AddParagraph()
				para.AppendText("This is the heading1 of built in style.")

				pStyle2.CharacterFormat.FontName = "Cambria"
				pStyle2.CharacterFormat.FontSize = 20F

				doc.LastSection.AddParagraph()

				para = doc.LastSection.AddParagraph()
				para.AppendText("Section1")
				para.ApplyStyle("MyStyle2")
				para = doc.LastSection.AddParagraph()
				para.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.")

				pStyle3.CharacterFormat.FontName = "Cambria"
				pStyle3.CharacterFormat.FontSize = 14F

				doc.LastSection.AddParagraph()

				para = doc.LastSection.AddParagraph()
				para.AppendText("Section2")
				para.ApplyStyle("MyStyle3")
				para = doc.LastSection.AddParagraph()
				para.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks.")

'				#End Region
			End If

			toc.IncludePageNumbers = IncludePageNumbers
			toc.RightAlignPageNumbers = RightAlignPageNumbers
			toc.UseHyperlinks = UseHyperlinks
			toc.LowerHeadingLevel = Convert.ToInt32(LowerHeadingLevel)
			toc.UpperHeadingLevel = Convert.ToInt32(UpperHeadingLevel)
			'Right click text. Select Paragraph option. Set OutlineLevel. Update TOC toc see the text added in TOC.
			toc.UseOutlineLevels = UseOutlineLevels
			'Select the text that should be marked as Table of contents.
			'Press ALT+SHIFT+O. A dialog box will appear with options to enter the text, select the table identifier and level.
			'Choose the table identifier and level for the test and click �Mark�. Update TOC toc see the text added in TOC.
			'Sets the Table Identifier if necessary.
			'toc.TableID = "B";              
			'Updates the table of contents.
			If UpdateToc Then
				doc.UpdateTableOfContents()
			End If

			Dim fileName As String = Path.Combine(OutputDir, Me.GetType().Name & "_" & Guid.NewGuid().ToString() & GetExtension(SaveAsFormat))
			' Save the document.
			doc.Save(fileName, SaveAsFormat)

			' Close the document.
			doc.Close()

			Return fileName
		End Function

#If WEB Then
		Private Sub ProcessForm()

		End Sub
#End If
	End Class
End Namespace