Table of Contents

This guide explains how to create a clickable Table of Contents (TOC) in a Microsoft Word document.

Before you begin

You should get your API key from your UniCloud account.

If this is your first time using UniOffice SDK, follow this guide to set up a local development environment.

Clone the project repository

In your terminal, clone the examples repository. It contains the Go code we will be using for this guide.

git clone https://github.com/unidoc/unioffice-examples

To get the example navigate to the path document/toc folder in the unioffice-examples directory.

cd unioffice-examples/document/toc

How it works

Lines 4-11 import the UniOffice packages and other required dependencies.

The init function in lines 13-20 authenticates your request with your UNIDOC_LICENSE_API_KEY.

The main function, spanning from line 24 to 72, begins by creating a new document at line 25. In line 29, it enforces updating the table of contents every time the document is opened using the SetUpdateFieldsOnOpen method.

At line 32, a paragraph is added to the document along with a run that inserts a TOC (Table of Contents) field using the AddField method with the parameter document.FieldTOC.

Following this, a page break is added after inserting the TOC.

On line 36, a numbering definition (nd) is created, which will be used to determine how list levels will appear in the document. A loop is then initiated, where in each iteration, a new level is added to the TOC using the AddLevel method, and its format and alignment are defined.

If it’s an even level, the format is changed, and a different font family is set, along with altering the text for that level. In all cases, a left indentation is also defined.

After defining the TOC, the code proceeds to add paragraphs with their respective heading levels from lines 50 to 70. A loop is used to add a paragraph, assign the previously created definition using the SetNumberingDefinition method, set the heading level with SetHeadingLevel, and add some text. Inside this loop, another loop creates two new paragraphs with the same assignments as the first but at a lower level.

Finally, the file is saved at line 71.

Run the code

You can create the Table of Contents (TOC) example by running this command:

go run main.go

Sample output

Table of contents 1

Table of contents 2

Table of contents 3

Table of contents 4

Got any Questions?

We're here to help you.