PDF From HTML With Graphs

This guide will show how to convert an HTML with a graph in to a PDF using UniHTML.

Sample input

graph image

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 graph folder in the unihtml-examples directory.

cd unihtml-examples/graph

How it works

First the necessary libraries are imported in the import section in lines 8-14. Then the main function is defined in lines 22-49. Lines 23-26 the number of command line arguments are checked. The code in lines 39-45 tries to establish connection with UniHTML server. For this to work the UniHTML server should be running. If you are not sure how to run server, check this guide.

Then line 45 creates a new unihtml.Document from the input HTML file using:

htmlDocument, err := unihtml.NewDocument("graph.html")

Then using the WaitVisible method of the unihtml.Document object, we give the engine a time to load the necessary content to be visible. Here the highcharts-root class is set as a selector and selection type is set to be ByQueryAll. This equivalent to document.querySelectorAll() method in the browser. Finally, the document is written to PDF file in line 55 using:

err = htmlDocument.WriteToFile("graph.pdf")

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 graph.go <server address>

Sample output

converted PDF

Got any Questions?

We're here to help you.