Skip to content

Custom Table of Contents

Run.AddTOC writes the same TOC field as Run.AddField(document.FieldTOC), with switches appended to the field instruction. The switches are what let you turn the entries into hyperlinks, drop the page numbers, or limit the list to particular heading levels. Everything else about the field is unchanged: the application that opens the document is still what computes the entries.

TOCOptions fieldSwitch writtenEffect
UseHyperlinks: true\hEntries become clickable links to their heading.
OmitPageNumbers: true\nEntries are listed without page numbers.
HeadingLevel: "1-3"\o '1-3'Only headings in that level range are collected.

AddTOC(nil) produces a bare TOC instruction, which is exactly what AddField does, so pass options or use AddField; there is no reason to pass nil.

Writing the field

doc := document.New()
defer doc.Close()

doc.Settings.SetUpdateFieldsOnOpen(true)

options := &document.TOCOptions{
    UseHyperlinks: true,
    HeadingLevel:  "1-1",
}
doc.AddParagraph().AddRun().AddTOC(options)
doc.AddParagraph().Properties().AddSection(wml.ST_SectionMarkNextPage)

With HeadingLevel set to "1-1" the contents list holds only the level 1 headings, even though the example goes on to write level 2 and level 3 headings into the body. Widen it to "1-3" to get all three.

The range string is written into the \o switch as you give it. UniOffice does not parse or validate it, so a malformed range reaches the field instruction unchanged and the application decides what to do with it.

Limitations

TOCOptions models three switches. A TOC field accepts several more, and the only way to reach them through UniOffice is Run.AddFieldWithFormatting, which takes the field code and a format string and writes them out verbatim. Pass document.FieldTOC as the code and your own switch string as the format.

Everything on the table of contents page still applies here. The document carries no computed result until Word or LibreOffice evaluates the field, and the native DOCX to PDF converter does not evaluate TOC fields at all.

Nothing checks that the heading range matches the headings you actually wrote. A document with only level 1 and level 2 headings and a HeadingLevel of "3-3" produces an empty contents list with no error from UniOffice.

Run the example

The example is the plain table of contents example with AddField swapped for AddTOC, so the two files are worth diffing. It writes toc.docx with a hyperlinked, level 1 only contents page followed by headings at three levels.

git clone https://github.com/unidoc/unioffice-examples.git
cd unioffice-examples/document/toc-custom
go run main.go

If this is your first time using UniOffice, follow the getting started guide to create an API key and set up your development environment.

View the full source
Last updated on