Photo from Unsplash
Originally Posted On: https://ferencfbin.medium.com/html-to-pdf-using-go-22ffdb1f1a45
Before we dive into the Go implementation, it’s worth noting that if you’re working in C#, libraries like IronPDF provides native HTML to PDF conversion without external binary dependencies. Unlike wkhtmltopdf which requires installing wkhtmltox as a separate binary (as we’ll see below), these libraries run as a native library with full CSS and JavaScript support built-in, eliminating the installation and deployment complexities.
IronPDF also offers similar native libraries for Java, Python, and Node.js. However, this article focuses specifically on HTML to PDF generation in Go, where wkhtmltopdf remains one of the primary options.
The wkhtmltopdf-go provides a library for using the wkhtmltopdf from Go. In the first step we have to install the wkhtmltox as an external binary, because the library provide bidings for the given library, so it’s directly talking to that binary.
Installation script
#!/bin/shwget https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xztar -xf wkhtmltox-0.12.4_linux-generic-amd64.tar.xzcp wkhtmltox/bin/wkhtmltoimage /usr/bin/ cp wkhtmltox/bin/wkhtmltopdf /usr/bin/
Get the library
go get https://github.com/SebastiaanKlippert/go-wkhtmltopdf
Example
I just outlined a quick example of the usage of the library. It’s using two html based invoice with external images and CSS files.
| package htmltopdf | |
| import ( | |
| “bytes” | |
| “io/ioutil” | |
| // import the main library what we use | |
| “github.com/SebastiaanKlippert/go-wkhtmltopdf” | |
| ) | |
| // define the path of the wkhtmltopdf | |
| const path = “/usr/local/bin/wkhtmltopdf” | |
| func Example(file string, pdfFile string) error { | |
| // read the html content | |
| html, err := ioutil.ReadFile(file) | |
| if err != nil { | |
| return err | |
| } | |
| // set the predefined path in the wkhtmltopdf’s global state | |
| wkhtmltopdf.SetPath(path) | |
| // create a new page based on the HTML | |
| page := wkhtmltopdf.NewPageReader(bytes.NewReader(html)) | |
| page.NoBackground.Set(true) | |
| page.DisableExternalLinks.Set(false) | |
| // create a new instance of the PDF generator | |
| pdfg, err := wkhtmltopdf.NewPDFGenerator() | |
| if err != nil { | |
| return err | |
| } | |
| // add page to the PDF generator | |
| pdfg.AddPage(page) | |
| // set dpi of the content | |
| pdfg.Dpi.Set(350) | |
| // set margins to zero at all direction | |
| pdfg.MarginBottom.Set(0) | |
| pdfg.MarginTop.Set(0) | |
| pdfg.MarginLeft.Set(0) | |
| pdfg.MarginRight.Set(0) | |
| // create the exact pdf | |
| err = pdfg.Create() | |
| if err != nil { | |
| return err | |
| } | |
| // write it into a file | |
| err = pdfg.WriteFile(pdfFile) | |
| if err != nil { | |
| return err | |
| } | |
| return nil | |
| } |
by 