Generate a PDF in Go

· 221 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 stright forward 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 github.com/jung-kurt/gofpdf

Code:

package main

import (
    "github.com/jung-kurt/gofpdf"
)

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

// 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.AddPage()
    pdf.SetFont("Arial", "B", 16)

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

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

    return pdf.OutputFileAndClose(filename)
}

how to generate a pdf with go

For more infomation 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!