PDF From HTML With External Links
This guide will demonstrate how to create a PDF document with a list of external links from an HTML file using UniHTML
.
Sample input
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 links
folder in the unihtml-examples
directory.
cd unihtml-examples/links
How it works
The example code starts by first importing the necessary dependencies in the import section.
Then the init
function defined in lines 22-29
sets the metered license key that is used to authenticate the library request.
The main
function starts in line 31
. First the number of command line arguments is checked to make sure the server address is provided. Line 38
tries to establish a connection to the UniHTML server using the UniHTML client. Then a new creator
is instantiated in line 44
. Line 47
creates a unihtml.Document
based on the input HTML file. Then the page size is set to ISO A5 in line 54
.
Lines 60-63
, sets the page margins using different units as follows.
htmlDocument.SetMarginLeft(sizes.Millimeter(10))
htmlDocument.SetMarginRight(sizes.Point(10))
htmlDocument.SetMarginTop(sizes.Millimeter(10))
htmlDocument.SetMarginBottom(sizes.Inch(0.5))
Lines 67
creates a context with a timeout duration set. The defer
call in line 68
is just a cleanup operation to release the resource by canceling the context. By calling GetPdfPages
method the output PDF pages are obtained. This method call internally calls a series of functions to extract and convert the HTML document into PDF pages.
The for
loop in lines 78-83
iterates through each PDF page and adds it to the creator like follows.
for _, p := range pages {
if err := c.AddPage(p); err != nil {
fmt.Printf("Err: adding page failed: %v\n", err)
os.Exit(1)
}
}
The PDF document properties are set in lines 86-91
and finally the document is written to a file in line 94
.
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 main.go <server address>