PDF Using HTML From Web URL

This guide will explain how to render a PDF page from an HTML page that is loaded from a web URL.

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

cd unihtml-examples/weburl

How it works

In lines 8-19, the necessary libraries are imported. In the init function the metered license key is set using license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`)).

The main function is defined in lines 30-80. Lines 31-34 checks for the server path in the command line arguments. Line 37 tries to make connection to the UniHTML server using unihtml.Connect(os.Args[1]). The os.Args[1] is the server path provided via the command line arguments.

Line 43 creates a new creator.Creator object. Using a web URL as a path, a new unihtml.Document is created in line 46. The page size is set A3 in line 52. The margins and the page orientations are set in lines 56-57 using the following code.

webDocument.SetMargins(30, 30, 30, 30)
webDocument.SetLandscapeOrientation()

A background context with time out is created to be used in the server request. Then by calling the GetPdfPages page method all pages are obtained and converted to PDF. These pages are then added to the creator in lines 68-73. Finally, the PDF document is written to file in line 76.

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

Sample output

output

Got any Questions?

We're here to help you.