Click or drag to resize

TableOfEntriesUpdate Method

Performs an update on TOC (Table of Contents) field.

Namespace: SautinSoft.Document
Assembly: SautinSoft.Document (in SautinSoft.Document.dll) Version: 2024.1.24
Syntax
public void Update()
Remarks

The TOC field collects entries for a table of contents using heading levels, specified styles, or entries specified by TC (Table of Contents Entry) fields.

If InstructionText is not specified Update method will set a default set of switches: \o "1-3" \h \u \z.

Supported TOC field switches:

\o "Headings"
Builds a table of contents from paragraphs formatted with built-in heading styles. For example, { TOC \o "1-3" } lists only headings formatted with the styles Heading 1 through Heading 3. If no heading range is specified, all heading levels used in the document are listed. Enclose the range numbers in quotation marks.

\u
Builds a table of contents from paragraphs formatted with all built-in heading styles (1-9).

\f EntryIdentifier
Builds a table from TC fields. If EntryIdentifier is specified, the table is built only from TC fields with the same identifier (typically a letter). For example, { TOC \f t } builds a table of contents from TC fields such as { TC "Entry Text" \f t }.

\h
Inserts TOC entries as hyperlinks.

\n Levels
Omits page numbers from the table of contents. Page numbers are omitted from all levels unless a range of entry levels is specified. For example, { TOC \n 3-4 } omits page numbers from levels 3 and 4. Delete this switch to include page numbers.

\l Levels
Builds a table of contents from TC fields that assign entries to one of the specified levels. For example, { TOC \l 1-4 } builds a table of contents from TC fields that assign entries to levels 1-4. TC fields that assign entries to lower levels are skipped.

\p "Separators"
Specifies the characters that separate an entry and its page number. For example, the field { TOC \p "—" }, with an em dash, displays a result such as "Selecting Text—53." The default is a tab with leader dots. You can use up to five characters, which must be enclosed in quotation marks.

Supported TC field instructions:

"Text"
Text to appear in the table of contents for an entry.

Supported TC field switches:

\f Type
The type of items collected in a particular contents list. Use a unique Type identifier (typically a letter from A-Z) for each type of list. For example, to build a list of illustrations, mark each illustration with a field such as { TC "Illustration 1" \f i }, where "i" indicates only illustration entries. If no type is specified, the entry is listed in a table of contents.

\l Level
The level of the TC entry. For example, the field { TC "Entering Data" \l 4 } marks a level-4 entry, and Microsoft Word applies the built-in style TOC 4 to that entry in the table of contents. If no level is specified, level 1 is assumed.

\n
Omits the page number for the entry.

For more information about TOC and TC fields, see Field codes in Word

Example

See Developer Guide: Update table of contents in word document

Update table of contents in word document using C#
using System;
using System.IO;
using System.Linq;
using SautinSoft.Document;
using SautinSoft.Document.Drawing;

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

            TOC();
        }

        /// <summary>
        /// Update table of contents in word document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/update-table-of-contents-in-word-document-net-csharp-vb.php
        /// </remarks>
        public static void TOC()
        {

            string pathFile = @"..\..\..\toc.docx";
            string resultFile = "UpdatedTOC.docx";

            // Load a .docx document with TOC.
            DocumentCore dc = DocumentCore.Load(pathFile);

            Paragraph p = new Paragraph(dc);
            p.Content.Start.Insert("I was born in the year 1632, in the city of York, of a good family, though not of that country, " +
                "my father being a foreigner of Bremen, who settled first at Hull.  He got a good estate by merchandise, and leaving " +
                "off his trade, lived afterwards at York, from whence he had married my mother, whose relations were named Robinson, " +
                "a very good family in that country, and from whom I was called Robinson Kreutznaer; but, by the usual corruption " +
                "of words in England, we are now called-nay we call ourselves and write our name-Crusoe; and so my companions always " +
                "called me. I had two elder brothers, one of whom was lieutenant-colonel to an English regiment of foot in Flanders, " +
                "formerly commanded by the famous Colonel Lockhart, and was killed at the battle near Dunkirk against the Spaniards.",

                new CharacterFormat() { Size = 28 });
            p.ParagraphFormat.Alignment = HorizontalAlignment.Justify;

            // Insert the paragraph as 6th element in the 1st section.
            dc.Sections[0].Blocks.Insert(5, p);

            Paragraph p1 = new Paragraph(dc);
            p1.Content.Start.Insert("That evil influence which carried me first away from my father�s house-which hurried me into the " +
                "wild and indigested notion of raising my fortune, and that impressed those conceits so forcibly upon me as to make me " +
                "deaf to all good advice, and to the entreaties and even the commands of my father-I say, the same influence, whatever " +
                "it was, presented the most unfortunate of all enterprises to my view; and I went on board a vessel bound to the coast " +
                "of Africa; or, as our sailors vulgarly called it, a voyage to Guinea. It was my great misfortune that in all these " +
                "adventures I did not ship myself as a sailor; when, though I might indeed have worked a little harder than ordinary, " +
                "yet at the same time I should have learnt the duty and office of a fore-mast man, and in time might have qualified " +
                "myself for a mate or lieutenant, if not for a master.  But as it was always my fate to choose for the worse, so I did " +
                "here; for having money in my pocket and good clothes upon my back, I would always go on board in the habit of " +
                "a gentleman; and so I neither had any business in the ship, nor learned to do any.",

                new CharacterFormat() { Size = 28 });
            p1.ParagraphFormat.Alignment = HorizontalAlignment.Justify;

            // Insert the paragraph as 10th element in the 1st section.
            dc.Sections[0].Blocks.Insert(9, p1);

            // Update TOC (TOC can be updated only after all document content is added).
            TableOfEntries 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 });

            // Change default character formatting for all text inside TOC
            CharacterFormat cf = new CharacterFormat();
            cf.Size = 20;
            cf.FontColor = Color.Blue;
            foreach (Inline inline in toc.GetChildElements(true, ElementType.Run, ElementType.SpecialCharacter))
            {
                if (inline is Run)
                    ((Run)inline).CharacterFormat = cf.Clone();
                else
                    ((SpecialCharacter)inline).CharacterFormat = cf.Clone();
            }

            // Save the document as new DOCX file.
            dc.Save(resultFile);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(resultFile) { UseShellExecute = true });
        }
    }
}
Update table of contents in word document using VB.Net
Imports System
Imports System.IO
Imports System.Linq
Imports SautinSoft.Document
Imports SautinSoft.Document.Drawing

Namespace Example
    Friend Class Sample
        Shared Sub Main(ByVal args() As String)
            TOC()
        End Sub
        ''' Get your free 30-day key here:   
        ''' https://sautinsoft.com/start-for-free/
        ''' <summary>
        ''' Update table of contents in word document.
        ''' </summary>
        ''' <remarks>
        ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/update-table-of-contents-in-word-document-net-csharp-vb.php
        ''' </remarks>
        Public Shared Sub TOC()

            Dim pathFile As String = "..\..\..\toc.docx"
            Dim resultFile As String = "UpdatedTOC.docx"

            ' Load a .docx document with TOC.
            Dim dc As DocumentCore = DocumentCore.Load(pathFile)

            Dim p As New Paragraph(dc)
            p.Content.Start.Insert("I was born in the year 1632, in the city of York, of a good family, though not of that country, " &
            "my father being a foreigner of Bremen, who settled first at Hull.  He got a good estate by merchandise, and leaving " &
            "off his trade, lived afterwards at York, from whence he had married my mother, whose relations were named Robinson, " &
            "a very good family in that country, and from whom I was called Robinson Kreutznaer; but, by the usual corruption " &
            "of words in England, we are now called-nay we call ourselves and write our name-Crusoe; and so my companions always " &
            "called me. I had two elder brothers, one of whom was lieutenant-colonel to an English regiment of foot in Flanders, " &
            "formerly commanded by the famous Colonel Lockhart, and was killed at the battle near Dunkirk against the Spaniards.",
            New CharacterFormat() With {.Size = 28})
            p.ParagraphFormat.Alignment = HorizontalAlignment.Justify

            ' Insert the paragraph as 6th element in the 1st section.
            dc.Sections(0).Blocks.Insert(5, p)

            Dim p1 As New Paragraph(dc)
            p1.Content.Start.Insert("That evil influence which carried me first away from my father�s house-which hurried me into the " &
            "wild and indigested notion of raising my fortune, and that impressed those conceits so forcibly upon me as to make me " &
            "deaf to all good advice, and to the entreaties and even the commands of my father-I say, the same influence, whatever " &
            "it was, presented the most unfortunate of all enterprises to my view; and I went on board a vessel bound to the coast " &
            "of Africa; or, as our sailors vulgarly called it, a voyage to Guinea. It was my great misfortune that in all these " &
            "adventures I did not ship myself as a sailor; when, though I might indeed have worked a little harder than ordinary, " &
            "yet at the same time I should have learnt the duty and office of a fore-mast man, and in time might have qualified " &
            "myself for a mate or lieutenant, if not for a master.  But as it was always my fate to choose for the worse, so I did " &
            "here; for having money in my pocket and good clothes upon my back, I would always go on board in the habit of " &
            "a gentleman; and so I neither had any business in the ship, nor learned to do any.",
            New CharacterFormat() With {.Size = 28})
            p1.ParagraphFormat.Alignment = HorizontalAlignment.Justify

            ' Insert the paragraph as 10th element in the 1st section.
            dc.Sections(0).Blocks.Insert(9, p1)

            ' 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 As TableOfEntries = 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})

            ' Change default character formatting for all text inside TOC
            Dim cf As New CharacterFormat()
            cf.Size = 20
            cf.FontColor = Color.Blue
            For Each inline As Inline In toc_Renamed.GetChildElements(True, ElementType.Run, ElementType.SpecialCharacter)
                If TypeOf inline Is Run Then
                    CType(inline, Run).CharacterFormat = cf.Clone()
                Else
                    CType(inline, SpecialCharacter).CharacterFormat = cf.Clone()
                End If
            Next inline

            ' Save the document as new DOCX file.
            dc.Save(resultFile)
            System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(resultFile) With {.UseShellExecute = True})
        End Sub
    End Class
End Namespace
See Also