Recursive AI

Create a PDF in Go

onepdf-go is a free, open-source PDF library for Go from Recursive AI that reads, edits, signs, redacts and lays out PDFs. MIT or Apache-2.0, no third-party dependencies.

Call doc.WritePDF on a layout document with a line-item table, a repeating header, and page numbers.

Terminal
go get recursiveai.org/go/onepdf
go get recursiveai.org/go/onepdf/fonts

Go 1.24+ required (download: Go 1.26.8).

GO
package main
 
import (
	"bytes"
	"fmt"
	"log"
	"os"
 
	"recursiveai.org/go/onepdf/fonts"
	"recursiveai.org/go/onepdf/layout"
)
 
func row(item, price string) *layout.TableRow {
	return &layout.TableRow{Cells: []*layout.TableCell{
		{Content: layout.Text(item)},
		{Content: layout.Text(price)},
	}}
}
 
func main() {
	face, ok := fonts.Lookup("Helvetica")
	if !ok {
		log.Fatal("missing bundled font")
	}
	faces := layout.NewFonts()
	spec := layout.FontSpec{Family: "Invoice"}
	if _, err := faces.Add(face.Data(), spec); err != nil {
		log.Fatal(err)
	}
	table := &layout.Table{
		Columns: []layout.TableColumn{
			{Kind: layout.WidthRelative, Width: 3},
			{Kind: layout.WidthRelative, Width: 1},
		},
		Header: []*layout.TableRow{row("Item", "Amount")},
		Rows: []*layout.TableRow{
			row("Design consultation", "$120.00"),
			row("Proof copy", "$30.00"),
			row("Total", "$150.00"),
		},
	}
	page := &layout.Section{
		Size:    layout.Letter,
		Margin:  layout.All(layout.Mm(20)),
		Header:  layout.Text("Invoice 1042"),
		Content: table,
		Footer:  &layout.PageNumberText{Format: "Page {page}"},
	}
	doc := &layout.Document{
		Fonts:        faces,
		DefaultStyle: layout.TextStyle{Size: 12},
		Sections:     []*layout.Section{page},
	}
	var pdf bytes.Buffer
	if _, err := doc.WritePDF(&pdf); err != nil {
		log.Fatal(err)
	}
	name := "invoice.pdf"
	if err := os.WriteFile(name, pdf.Bytes(), 0644); err != nil {
		log.Fatal(err)
	}
	fmt.Println("Wrote", name)
}

Paste the code above into main.go, run go mod init example and go get recursiveai.org/go/onepdf, then go run .; or unzip the example and go run ..

If you paste the code into a new module, also run go get recursiveai.org/go/onepdf/fonts before go run ..

go run . prints:

Text
Wrote invoice.pdf

Open invoice.pdf to see “Invoice 1042” at the top, three rows under the “Item” and “Amount” column headings, and “Page 1” in the footer. The program builds the PDF in memory so a layout or PDF generation error stops it before it opens the output file.

Variations

Use A4 instead of US Letter. Change the Size field in page to:

GO
Size: layout.A4,

Show the current and total page numbers. Change the Footer field in page to:

GO
Footer: &layout.PageNumberText{
    Format: "Page {page} of {total}",
},

The same one-page invoice now has “Page 1 of 1” in its footer.

The short answer

To create a PDF in Go, put the content in a layout.Document and call WritePDF. For an invoice, give the section a Header for the invoice number, a Table for line items, and a Footer for the page number. The example builds the document from Go values; it doesn’t render HTML or fill a pre-existing PDF.

How do I generate a PDF invoice from a template in Go?

Use the same layout for every invoice and replace the data that goes into it. The sample’s row function takes an item description and a formatted amount and returns a pair of table cells. In your application, feed it the items from your invoice record, in the order you want them printed. Calculate the amounts and the total before passing them to the layout; the table displays strings and doesn’t do the accounting.

The page header and table header do different jobs. The section’s Header runs at the top of every page in the section, whether or not there’s a table. The table’s Header supplies the column labels when the table continues on another page. Keeping those in separate slots lets a reader identify both the invoice and the columns on a continuation page. The widths 3 and 1 share the available table space three to one, leaving more room for descriptions than for amounts.

If you already have a PDF with named fillable fields and only need to add values, fill the form instead. Here the app owns the entire page layout, so the number of rows can vary from one invoice to the next.

How do I create a PDF with embedded fonts in Go?

layout.Fonts.Add takes font bytes. The PDF stores the font it needs rather than relying on the reader’s installed fonts. The example looks up Helvetica in the fonts module, which supplies Liberation Sans as the substitute. It registers that face in the layout’s font set under the family name Invoice; it doesn’t read a font from your system. The bundled font files use the SIL Open Font License 1.1.

For your own typeface, use font bytes you have permission to embed and add the faces you need to the layout font set. Check the characters your customers and item descriptions use: choosing a font that works for the English sample doesn’t establish that it covers your own text.

All onepdf Go recipes