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.
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
Configure environment variables
UNIDOC_LICENSE_API_KEY with your API credentials from your UniCloud account.
How it works
import section in lines
9-18 imports UniPDF packages and other necessary libraries.
init function defined in lines
20-27 loads your metered license key from the system environment and authenticates your library request.
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
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
drawTitleCell functions are used to draw the table cells. Finally in line
73 the table of content is drawn using
89-94 two new pages are created that contain new chapter and are drawn.
96-99 the document is written to file using
drawCell defined in lines
102-113 draws a new table cell based on the information given as the parameters of the function.
drawTitleCell in lines
115-125 draws a title cell.
Run the code
go run pdf_custom_toc.go