PDF With Chapters From HTML and Assets Directory

This guide will demonstrate the process of creating PDF document with a chapter from multi file HTML content using UniHTML library. The HTML resources such as CSS and images are organized in a single directory and are loaded from the directory, rendered and then converted to PDF using UniHTML.

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. To set up a UniHTML server follow this getting started guide.

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 [email protected]:unidoc/unihtml-examples.git

Navigate to the directory folder in the unihtml-examples directory.

cd unihtml-examples/directory

How it works

In lines 8-15 the necessary libraries are imported. Then in the init function defined in lines 17-24 the metered License API key is loaded from the system environment and set using license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`)).

The main function is defined in lines 26-68. First the number of command line arguments is checked to make sure the server URL is provided. Then line 33 tries to create connection with server using unihtml.Connect(os.Args[1]). Line 39 initializes a new Creator object and a new creator.Chapter is created from this object. The HTML content is loaded from the directory using unihtml.NewDocument("data") in line 45. The unihtml.Document is added to the chapter in line 52 and the chapter is drawn by calling the Draw method of the creator object. Finally, the PDF document is written to a file in line 64.

Run the code

Run the code using the following command to generate the PDF file. Replace the server address with the actual address. E.g. localhost:8080 for a server running locally on port 8080.

go run directory_chapter.go <server address>

Sample output

Output

Got any Questions?

We're here to help you.