HTML to PDF with GoLang

The easiet way to format and create PDFs is to write them first as HTML and then convert them to PDF. wkhtmltopdf is a command line tool that let’s you do this. Let’s do it with GoLang.

First, you start with an html template. This template could as well be a file on your computer.

htmlTemplate := `
    <!DOCTYPE html>
    <html lang="en">
        <meta charset="UTF-8">
        <h1>{{.FirstName}} {{.LastName}}</h1>

            {{range .Skills}}

And a struct that will be used to populate the html template.

type Person struct {
	FirstName string
	LastName  string
	JobTitle  string
	Skills    []string

Next, generate an in-memory HTML buffer using the html/template package.

var htmlBuffer bytes.Buffer
err := template.Must(template.New("html").
    Execute(&htmlBuffer, person)

person is a pointer to a Person struct.

Once you have the HTML buffer, you can convert it to PDF using This package is just a wrapper around wkhtmltopdf.

pdfGen, _ := wkhtmltopdf.NewPDFGenerator()
page := wkhtmltopdf.NewPageReader(bytes.NewReader(htmlBuffer.Bytes()))

The above snippet will convert the HTML buffer to a PDF.

Putting it all together

I have created that contains a production ready dockerized example. Feel free to use it as a starting point for your own projects.

Published 16 May 2022