Generating PDFs with Go
Go's PDF story is narrower than Java's or .NET's but it is clean: one dependency-free drawing library with a long lineage, one grid-layout engine on top of it, one processing tool that doubles as a validator, and a mature headless-Chromium driver. None of the open-source options reads and lays out existing PDFs the way iText does, so the choice is usually between drawing it yourself and rendering HTML.
## The options| Library | Approach | Licence | Import path | Best for | Avoid when |
|---|---|---|---|---|---|
| go-pdf/fpdf | Drawing API, port of FPDF; pure Go, no cgo | MIT | github.com/go-pdf/fpdf (v0.9.0, September 2023) | Fixed layouts, labels, simple multi-page text, small binaries | You need tables that paginate themselves or rich text |
| jung-kurt/gofpdf | The original port | MIT | github.com/jung-kurt/gofpdf | Nothing new: the repository was archived on 13 November 2021 and its README says it will not be maintained | Any new project; use go-pdf/fpdf, which continued from it |
| Maroto v2 | Grid layout engine (12-column rows) on top of fpdf | MIT | github.com/johnfercher/maroto/v2 (v2.4.4) | Invoices and reports with tables, barcodes, images; declarative code | Pixel-precise placement; documents that are mostly prose |
| pdfcpu | Processing: validate, optimise, merge, split, boxes, watermarks, forms, encryption; limited creation | Apache-2.0 | github.com/pdfcpu/pdfcpu (v0.16.4, October 2026, requires Go 1.26) | Post-processing whatever you generated; CLI in CI | Laying out new documents |
| gopdf | Drawing API with TrueType support | MIT | github.com/signintech/gopdf | Simple drawing with Unicode fonts | You want the larger fpdf ecosystem |
| UniPDF | Full-featured creation and editing | Commercial (UniDoc EULA); a metered licence key is required, with a free tier | github.com/unidoc/unipdf/v5 | Teams that want a supported commercial SDK | Projects that need an open-source licence |
| chromedp, rod | Headless Chromium (HTML renderer) | MIT (both) | github.com/chromedp/chromedp (v0.21.0, October 2026), github.com/go-rod/rod | Documents that exist as HTML templates | Environments that cannot run a browser |
The gofpdf history matters because search results still point at the archived repository. go-pdf/fpdf is the continuation with the same API, so code written for one compiles against the other after an import change; new work should import github.com/go-pdf/fpdf.
For the general choice between drawing, layout and HTML rendering, the developers hub has the decision table.
fpdf: text with an embedded UTF-8 font#
fpdf keeps the FPDF model: you add pages, set a font and emit cells. The core fonts (Helvetica, Times, Courier) support only the Windows-1252 range; for anything else you add a TrueType font with AddUTF8Font, which embeds a subset of it in the output.
package main
import (
"log"
"github.com/go-pdf/fpdf"
)
func main() {
// Orientation, unit, size, font directory (empty: fonts are given as paths).
pdf := fpdf.New("P", "mm", "A4", "")
pdf.SetMargins(20, 20, 20)
// Register a TrueType font for UTF-8 text. The file is embedded as a subset.
pdf.AddUTF8Font("inter", "", "fonts/Inter-Regular.ttf")
pdf.AddUTF8Font("inter", "B", "fonts/Inter-Bold.ttf")
pdf.AddPage()
pdf.SetFont("inter", "B", 18)
pdf.Cell(0, 10, "Delivery note 2026-0142")
pdf.Ln(14)
pdf.SetFont("inter", "", 11)
body := "Ordered 28 October 2026. Ship to: Jaana Mäkelä, Køge, Denmark. " +
"Multi-line text wraps inside the cell width; 0 means the remaining page width."
pdf.MultiCell(0, 6, body, "", "L", false)
// Simple ruled rows; fpdf does not paginate tables for you.
pdf.Ln(6)
pdf.SetFont("inter", "B", 11)
pdf.CellFormat(110, 8, "Item", "B", 0, "L", false, 0, "")
pdf.CellFormat(30, 8, "Qty", "B", 0, "R", false, 0, "")
pdf.CellFormat(30, 8, "Price", "B", 1, "R", false, 0, "")
pdf.SetFont("inter", "", 11)
for _, r := range [][3]string{{"Cable, 2 m", "3", "4.90"}, {"Adapter", "1", "12.00"}} {
pdf.CellFormat(110, 8, r[0], "", 0, "L", false, 0, "")
pdf.CellFormat(30, 8, r[1], "", 0, "R", false, 0, "")
pdf.CellFormat(30, 8, r[2], "", 1, "R", false, 0, "")
}
if err := pdf.OutputFileAndClose("delivery-note.pdf"); err != nil {
log.Fatal(err)
}
}CellFormat takes width, height, text, border spec, position after the cell (0 right, 1 next line), alignment, fill flag, link id and link URL. fpdf accumulates errors internally and reports the first one from OutputFileAndClose or Error(), so a wrong font path shows up at the end, not at AddUTF8Font.
Maroto v2: a table that paginates#
Maroto turns a page into rows of a 12-column grid. Each row has a height in millimetres; each column has a width in grid units and holds one component: text, image, barcode, QR code, signature line. Rows that do not fit are moved to the next page, which is the feature fpdf lacks.
package main
import (
"log"
"github.com/johnfercher/maroto/v2"
"github.com/johnfercher/maroto/v2/pkg/components/col"
"github.com/johnfercher/maroto/v2/pkg/components/row"
"github.com/johnfercher/maroto/v2/pkg/components/text"
"github.com/johnfercher/maroto/v2/pkg/config"
"github.com/johnfercher/maroto/v2/pkg/consts/align"
"github.com/johnfercher/maroto/v2/pkg/consts/fontstyle"
"github.com/johnfercher/maroto/v2/pkg/core"
"github.com/johnfercher/maroto/v2/pkg/props"
)
func main() {
cfg := config.NewBuilder().Build()
m := maroto.New(cfg)
m.AddRow(12, text.NewCol(12, "Transactions", props.Text{Size: 16, Style: fontstyle.Bold}))
m.AddRows(tableRows()...)
document, err := m.Generate()
if err != nil {
log.Fatal(err)
}
if err := document.Save("transactions.pdf"); err != nil {
log.Fatal(err)
}
}
func tableRows() []core.Row {
header := row.New(7).Add(
text.NewCol(6, "Description", props.Text{Size: 9, Style: fontstyle.Bold}),
text.NewCol(3, "Date", props.Text{Size: 9, Style: fontstyle.Bold, Align: align.Center}),
text.NewCol(3, "Amount", props.Text{Size: 9, Style: fontstyle.Bold, Align: align.Right}),
)
grey := &props.Color{Red: 235, Green: 237, Blue: 240}
rows := []core.Row{header}
items := [][3]string{
{"Hosting, October", "2026-10-01", "48.00"},
{"Domain renewal", "2026-10-07", "14.20"},
{"Support hours", "2026-10-29", "150.00"},
}
for i, it := range items {
r := row.New(6).Add(
text.NewCol(6, it[0], props.Text{Size: 9}),
text.NewCol(3, it[1], props.Text{Size: 9, Align: align.Center}),
text.NewCol(3, it[2], props.Text{Size: 9, Align: align.Right}),
)
if i%2 == 1 {
r.WithStyle(&props.Cell{BackgroundColor: grey})
}
rows = append(rows, r)
}
return rows
}A column of width 12 spans the page; col.New(12) with no component is an empty spacer row. Maroto's own examples register page numbers and page headers through the config builder and the RegisterHeader and RegisterFooter methods on the document; the billing example in the repository is the reference for those.
pdfcpu: validate and post-process#
pdfcpu is the tool to run after generation. As a library it validates files against the specification, and as a CLI it does the jobs that a generation library makes awkward: setting page boxes, watermarking, merging, optimising and encrypting. It has no dependency on cgo and compiles into your service.
package main
import (
"context"
"log"
"github.com/pdfcpu/pdfcpu/pkg/api"
)
func main() {
// A nil configuration uses the defaults; a nil options pointer disables progress reporting.
if err := api.ValidateFile(context.Background(), "transactions.pdf", nil, nil); err != nil {
log.Fatalf("invalid PDF: %v", err)
}
// Text watermark on every page (selectedPages nil), drawn on top of the content.
err := api.AddTextWatermarksFile(context.Background(),
"transactions.pdf", "transactions-draft.pdf", nil, true,
"DRAFT", "fontname:Helvetica, points:64, rotation:45, opacity:0.25", nil)
if err != nil {
log.Fatal(err)
}
}The same operations from the command line, which is often the better place for them because the description strings are documented there:
# Structural validation (relaxed by default; -mode strict for the full check)
pdfcpu validate transactions.pdf
# Crop box 1 inch inside the media box; bleed box 15% inside that; art and trim boxes equal to bleed
pdfcpu boxes add 'c:1, b:15%, a:b, t:b' in.pdf out.pdf -u inches
# Text watermark on every page
pdfcpu watermark add 'DRAFT' 'points:64, rotation:45, opacity:.25' in.pdf out.pdf --mode textThe box command is the quickest way to give a print-ready file the page boxes a printer asks for without touching the generator.
chromedp: printing HTML with Chromium#
For documents that already exist as HTML, chromedp drives a Chromium process over the DevTools protocol. Since v0.21.0 (October 2026) it has a typed PrintToPDF action with option helpers, and a generic Run that returns the action's value, so the PDF comes back as bytes without a custom action.
package main
import (
"context"
"log"
"os"
"time"
"github.com/chromedp/chromedp"
)
const footer = `<div style="font-size:9px;width:100%;text-align:right;margin-right:1cm">
page <span class="pageNumber"></span> of <span class="totalPages"></span></div>`
func main() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
ctx, cancel = context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// Navigate waits for the load event, which includes the page's images and fonts.
if err := chromedp.Do(ctx, chromedp.Navigate("http://127.0.0.1:8080/invoice/2026-0142")); err != nil {
log.Fatal(err)
}
buf, err := chromedp.Run(ctx, chromedp.PrintToPDF(
chromedp.PDFPaper(chromedp.PaperA4),
chromedp.PDFMargins(0.9, 0.6, 0.9, 0.6), // inches: top, right, bottom, left
chromedp.PDFPrintBackground(),
chromedp.PDFFooterTemplate(footer),
))
if err != nil {
log.Fatal(err)
}
if err := os.WriteFile("invoice.pdf", buf, 0o644); err != nil {
log.Fatal(err)
}
}Without options Chromium prints on Letter paper in portrait with 1 cm margins and no background; PDFPreferCSSPageSize() makes an @page { size: A4 } rule in the stylesheet win over the paper option. Header and footer templates are drawn inside the margins, so the margins must be large enough to hold them. The HTML-to-PDF guide covers print CSS, page breaks and the security of rendering untrusted HTML. rod offers the same capability with page.PDF(&proto.PagePrintToPDF{...}) and a MustPDF convenience.
Traps specific to Go#
Fonts. fpdf's core fonts cannot represent text outside Windows-1252, and they are not embedded, so a document that looks fine in one viewer may substitute glyphs in another. Register a TrueType font with AddUTF8Font for anything user-supplied, and ship the font file with the binary (an embedded filesystem via embed and AddUTF8FontFromBytes keeps the deployment self-contained). Maroto inherits the same rules. The fonts page explains what the viewer does with an embedded subset.
One document, one goroutine. An *fpdf.Fpdf is a stateful builder and is not safe for concurrent use. Generate each document in its own goroutine with its own instance; share only immutable inputs such as font bytes.
pdfcpu moves quickly. The API is versioned below 1.0 and signatures have changed between minor releases (the context.Context first parameter and the progress options are recent). Pin the version in go.mod and read the release notes before upgrading; the CLI description-string syntax is more stable than the Go signatures.
Chromium in containers. chromedp needs a Chromium binary in the image, with the shared libraries and a font set installed; fonts-liberation or fonts-noto on Debian-based images covers most Latin and CJK text. Run the browser with a timeout, reuse the context across requests, and never render HTML from untrusted sources without disabling network access, because <img> and <link> tags will fetch internal URLs.
No cgo, no surprises. fpdf, Maroto, gopdf and pdfcpu are pure Go, so cross-compilation and static binaries work as usual. That is a real operational advantage over wrapping a C library and worth weighing against feature gaps.
Check the result. Validate with pdfcpu validate in CI, and open a sample in the PDF inspector to confirm page size, embedded fonts and metadata. Generated files that pass validation but show "Helvetica, not embedded" are the fpdf core-font trap above.
Sources
- go-pdf/fpdf package documentation (MIT; AddUTF8Font, MultiCell)
- jung-kurt/gofpdf repository (archived 13 November 2021)
- Maroto v2 repository and package documentation
- Maroto v2 billing example (rows, columns, text properties)
- pdfcpu API package documentation (ValidateFile, AddBoxesFile, AddTextWatermarksFile)
- pdfcpu CLI, page boxes
- pdfcpu CLI, watermarks
- chromedp package documentation (PrintToPDF, PDFOption helpers, generic Run)
- chromedp PDF example
- signintech/gopdf repository (MIT)
- UniPDF repository (commercial EULA)
- go-rod/rod package documentation (Page.PDF)