go-wkhtmltopdf
Golang commandline wrapper for wkhtmltopdf
What and whyWe needed a way to generate PDF documents from Go. These vary from invoices with highly customizable lay-outs to reports with tables, graphs and images. In our opinion the best way to do this was by using HTML/CSS templates as source for our PDFs. Using CSS print media types and millimeters instead of pixel units we can generate very acurate PDF documents using wkhtmltopdf.
go-wkhtmltopdf is a pure Golang wrapper around the wkhtmltopdf command line utility.
It has all options typed out as struct members which makes it very easy to use if you use an IDE with code completion and it has type safety for all options. For example you can set general options like
The same goes for adding pages, settings page options, TOC options per page etc.
It takes care of setting the correct order of options as these can become very long with muliple pages where you have page and TOC options for each page.
Secondly it makes usage in server-type applications easier, every instance (PDF process) has its own output buffer which contains the PDF output and you can feed one input document from an io.Reader (using stdin in wkhtmltopdf). You can combine any number of external HTML documents (HTTP(S) links) with at most one HTML document from stdin and set options for each input document.
io.Writer
For us this is one of the easiest ways to generate PDF documents from Go(lang) and performance is very acceptable.
Installationgo get or use a Go dependency manager of your liking.
go-wkhtmltopdf finds the path to wkhtmltopdf by
- first looking in the current dir
- looking in the PATH and PATHEXT environment dirs
- using the WKHTMLTOPDF_PATH environment dir
Warning: Running executables from the current path is no longer possible in Go 1.19, see https://pkg.go.dev/os/exec@master#hdr-Executables_in_the_current_directory
If you need to set your own wkhtmltopdf path or want to change it during execution, you can call SetPath().
Usagewkhtmltopdf_test.gosimplesample_test.go
As mentioned before, you can provide one document from stdin, this is done by using a PageReader object as input to AddPage. This is best constructed with NewPageReader and will accept any io.Reader so this can be used with files from disk (os.File) or memory (bytes.Buffer) etc.
A simple example snippet:
The package now has the possibility to save the PDF Generator object as JSON and to create a new PDF Generator from a JSON file. All options and pages are saved in JSON, pages added using NewPageReader are read to memory before saving and then saved as Base64 encoded strings in the JSON file.
NewPDFPreparer
NewPDFPreparerNewPDFGeneratorFromJSON
Speed
The speed if pretty much determined by wkhtmltopdf itself, or if you use external source URLs, the time it takes to get and render the source HTML.
The go wrapper time is negligible with around 0.04ms for parsing an above average number of commandline options.
Benchmarks are included.