Generate a PDF in Go

· 220 words · 2 minutes read

We have already covered pdf generation to some degree, by using wkhtmltopdf on AWS’ Lambda service. This post is about generating pdfs without needing wkhtml - by building the pdf from Go itself. To do this we use a library called gofpdf to build the pdf.

It quite straightforward for simple documents, but gets more complicated the more you add to it. In our example we add some text as a title and an image just beneath it. Finally call OutputFileAndClose() to save the pdf to file - a screenshot of our example is shown below.

To Install:

go get


package main

import (

func main() {
    err := GeneratePdf("hello.pdf")
    if err != nil {

// GeneratePdf generates our pdf by adding text and images to the page
// then saving it to a file (name specified in params).
func GeneratePdf(filename string) error {

    pdf := gofpdf.New("P", "mm", "A4", "")
    pdf.SetFont("Arial", "B", 16)

    // CellFormat(width, height, text, border, position after, align, fill, link, linkStr)
    pdf.CellFormat(190, 7, "Welcome to", "0", 0, "CM", false, 0, "")

    // ImageOptions(src, x, y, width, height, flow, options, link, linkStr)
        80, 20,
        0, 0,
        gofpdf.ImageOptions{ImageType: "JPG", ReadDpi: true},

    return pdf.OutputFileAndClose(filename)

how to generate a pdf with go

For more information and available methods, see the library's documentation.

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!