Create PDF Custom Table of Contents

This guide will show how to create a custom table of contents layout using UniPDF library.

Before you begin

Before starting to follow along with this guide you should get your API key from your UniCloud account.

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

Project setup

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/unipdf-examples.git

Navigate to the report folder in the unipdf-examples directory.

cd unipdf-examples/report

Configure environment variables

Replace the UNIDOC_LICENSE_API_KEY with your API credentials from your UniCloud account.

Linux/Mac

export UNIDOC_LICENSE_API_KEY=PUT_YOUR_API_KEY_HERE

Windows

set UNIDOC_LICENSE_API_KEY=PUT_YOUR_API_KEY_HERE

How it works

The import section in lines 9-18 imports UniPDF packages and other necessary libraries.
The init function defined in lines 20-27 loads your metered license key from the system environment and authenticates your library request.

The main function defined in lines 29-100 is an entry point to the program and creates the document with the table of contents. In this function in line 30 a new creator.Creator object is created using creator.New(). In lines 33-34 adding table of contents and custom table of contents is enabled using

c.AddTOC = true
c.CustomTOC = true

Here the code in the first line controls wether a table of contents should be generated and the second line specifies wether the table of contents should be generated by the user. The code in lines 35-80 creates the table of content by calling the CreateTableOfContents method of the creator object by providing the callback function. Inside the call back function in lines 36-44 creates the title of the table of contents using c.NewParagraph("Table of Contents") and then draws the paragraph using c.Draw(tocTitle).

In lines 46-47 a new table is defined with three columns. The for loop in lines 49-71 iterates through each TOCLine and draws the lines by setting the content and adding the destination they point to. Here in lines 68-70 the drawCell and drawTitleCell functions are used to draw the table cells. Finally in line 73 the table of content is drawn using c.Draw(tocTable).

In lines 82-87 and 89-94 two new pages are created that contain new chapter and are drawn. In lines 96-99 the document is written to file using c.WriteToFile("pdf-custom-toc.pdf").

The function drawCell defined in lines 102-113 draws a new table cell based on the information given as the parameters of the function. The function drawTitleCell in lines 115-125 draws a title cell.

Run the code

go run pdf_custom_toc.go

Sample output

Custom Table of Contents

Got any Questions?

We're here to help you.