In this guide you will see how to create tables with a header row configured. This header row can be repeated automatically on every new page if the table is multi page spanning. This guide also shows how to add an image to a given table cell.
Before you begin
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
tables folder in the unipdf-examples directory.
Configure environment variables
UNIDOC_LICENSE_API_KEY with API credentials from your UniCloud account.
How it works
The following example code shows how to create a table with header row and how to add image to table cells.
import section in lines
9-17 imports unipdf packages
license and other necessary libraries.
init() function in lines
18-25 authenticates your request by loading your metered License API key before running the main function.
main function defined in lines
28-53 creates the pdf document with the table and writes it to file.
29-30 in this function instantiate a new
creator.Creator object by calling
creator.New() and sets the margins for the page. Lines
34-42 create the necessary fonts for the document. The
tableHeaders function is called in line
45. Finally the document is written to file in lines
tableHeaders function is defined. Here is where all the components of the example document are created. In lines
57-61 the header component of the page is defined. This is created by using
c.NewChapter("Headers"). A new description paragraph is also created in lines
64-66 and is added to chapter using
A table with 4 columns is created using
c.NewTable(4) in line
83-94 an anonymous function for drawing a table cell is defined. In line
97 two table cells that span 4 columns are drawn. In line
98 the two rows are set to be Header rows by calling
table.SetHeaderRows(1, 2). This means rows
1-2 are header rows.
In the loop in lines
101-120 the content of the tables is created one row at a time. This means 4 cells are drawn per iteration.
The first cell is drawn in lines
112-115. This cell contains an image which is set using
cell.SetContent(img) at line
The rest 3 cells of the row are drawn in lines
122 the table is added to the chapter object using
ch.Add(table). Finally the chapter is drawn in lines
Run the code
To create the example document run the code using the following command.
go run pdf_tables_header_images.go
This is the first page of the output pdf document.