Generate a PDF in Go

· 258 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:

1
go get github.com/jung-kurt/gofpdf

Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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 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!