Rendering HTML templates to PDF in golang with chromedp and headless Chromium
We already had HTML and CSS templates, so instead of a golang PDF library we print them with headless Chromium through chromedp. The render code, the container setup, a rough page count, and the API change in chromedp v0.24 that broke my first try.
We had to produce a PDF agreement for a user to sign, from a golang API. The agreement already existed as an HTML template with proper CSS, written by people who know HTML much better than any Go PDF layout API. Rebuilding it in a library that draws text at x and y coordinates would have been weeks of fiddling, and every copy change after that would need a developer.
So we didn't rebuild it. We load the HTML into headless Chromium and ask Chromium to print it, the same as pressing Ctrl+P in a browser. chromedp drives Chromium over the DevTools protocol from Go, so the whole thing stays inside the API process.
In this blog we will look at the render function, a template to feed it, how to run it in a Debian slim container, and a cheap way to count the pages. I also hit a compile error on the first try, because chromedp changed its API a lot this year, so that is in here too.
The render function
First, the code. This is written for chromedp v0.24.0, which is the current release as I write this (it came out on 18 November 2026).
// Package pdf turns an HTML document into PDF bytes with headless Chromium.
package pdf
import (
"context"
"fmt"
"regexp"
"time"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
)
// RenderTimeout bounds one render, browser start included.
const RenderTimeout = 30 * time.Second
// Render prints html to PDF. chromePath may be "" to let chromedp find
// Chrome or Chromium on its own.
func Render(ctx context.Context, html, chromePath string) ([]byte, error) {
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.Flag("headless", true),
chromedp.Flag("no-sandbox", true), // containers usually run as root
chromedp.Flag("disable-gpu", true),
)
if chromePath != "" {
opts = append(opts, chromedp.ExecPath(chromePath))
}
allocCtx, cancelAlloc := chromedp.NewExecAllocator(ctx, opts...)
defer cancelAlloc()
browserCtx, cancelBrowser := chromedp.NewContext(allocCtx)
defer cancelBrowser()
ctx, cancel := context.WithTimeout(browserCtx, RenderTimeout)
defer cancel()
// Load the HTML straight into a blank page: no temp file, no local server.
err := chromedp.Do(ctx,
chromedp.Navigate("about:blank"),
chromedp.Func(func(ctx context.Context, t *chromedp.Target) error {
tree, err := cdp.Call(ctx, t, page.GetFrameTree, cdp.Empty{})
if err != nil {
return err
}
_, err = cdp.Call(ctx, t, page.SetDocumentContent, page.SetDocumentContentParams{
FrameID: tree.FrameTree.Frame.ID,
HTML: html,
})
return err
}),
)
if err != nil {
return nil, fmt.Errorf("load html: %w", err)
}
out, err := chromedp.Run(ctx, chromedp.PrintToPDF(
chromedp.PDFPrintBackground(),
chromedp.PDFPreferCSSPageSize(),
))
if err != nil {
return nil, fmt.Errorf("render pdf: %w", err)
}
return out, nil
}
Some notes on whats going on.
Each call starts its own browser and kills it at the end, when the deferred cancels run. That is slower than keeping one browser alive, but there is nothing to leak, nothing to restart if Chromium crashes, and two renders can't see each other's pages. For a few documents a minute that trade is fine. If you render hundreds per minute, keep one allocator for the process and open a new tab per render with chromedp.NewContext(browserCtx).
The 30 second timeout wraps the whole thing, browser start included. The chromedp docs warn you not to put a timeout on the context of the first Run, because that timeout stops the browser. Here that is exactly what I want. A render that hangs should take its browser down with it.
about:blank plus SetDocumentContent means we never write the HTML to disk and never serve it over HTTP. The template goes straight into the page.
PDFPreferCSSPageSize tells Chromium to use the @page rule in the CSS. Without it you get Letter paper by default, which is not what anyone in India expects, and PDFPrintBackground keeps the table header colours. Without that one, background colours just disappear from the print. I forgot it the first time I did this years ago and spent a while blaming the CSS.
The API change that broke my first try
I started this post from memory, using the style most chromedp examples on the internet still show: chromedp.ActionFunc, page.PrintToPDF().WithPrintBackground(true).Do(ctx). go get github.com/chromedp/chromedp@latest pulled v0.24.0 and the build failed straight away:
pdf/pdf.go:41:12: undefined: chromedp.ActionFunc
pdf/pdf.go:49:19: invalid operation: cannot call page.PrintToPDF (variable of struct type
cdp.Command[page.PrintToPDFParams, page.PrintToPDFResult]): cdp.Command[page.PrintToPDFParams,
page.PrintToPDFResult] is not a function
Between v0.16 and v0.24 (July to November 2026) chromedp moved to generic actions. An action is now Action[T], chromedp.Run returns the value, chromedp.Do runs a list of steps that return nothing, and protocol commands are values you send with cdp.Call instead of builder functions with a Do method. There is a MIGRATION.md in the repo that goes through it part by part, and it is long.
The old style still works if you pin an older version. I checked it against v0.15.0 (March 2026) and it ran fine:
var out []byte
err := chromedp.Run(ctx,
chromedp.Navigate("about:blank"),
chromedp.ActionFunc(func(ctx context.Context) error {
tree, err := page.GetFrameTree().Do(ctx)
if err != nil {
return err
}
return page.SetDocumentContent(tree.Frame.ID, html).Do(ctx)
}),
chromedp.ActionFunc(func(ctx context.Context) error {
buf, _, err := page.PrintToPDF().WithPrintBackground(true).Do(ctx)
out = buf
return err
}),
)
So if you have that code in production on an older chromedp, it is not broken. Just don't run go get -u on it in a hurry. The real service I took this from is on an older chromedp too and uses the style above.
A template to feed it
Now the template. Nothing special, html/template and normal CSS. The @page rule sets the paper and margins, and page-break-inside: avoid stops a table row getting cut in half between two pages.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
@page { size: A4; margin: 18mm 16mm; }
body { font-family: "Liberation Sans", Arial, sans-serif; font-size: 11pt; color: #222; }
table { width: 100%; border-collapse: collapse; margin-top: 6mm; }
th, td { border-bottom: 1px solid #ccc; padding: 2mm; text-align: left; }
td.num, th.num { text-align: right; }
thead { background: #f1f5f9; }
tr { page-break-inside: avoid; }
.sign { margin-top: 20mm; height: 25mm; width: 70mm; border: 1px dashed #999; }
</style>
</head>
<body>
<h1>Invoice {{.Number}}</h1>
<div>{{.Customer}}<br>{{.Date}}</div>
<table>
<thead><tr><th>Item</th><th class="num">Qty</th><th class="num">Amount</th></tr></thead>
<tbody>
{{range .Lines}}<tr><td>{{.Name}}</td><td class="num">{{.Qty}}</td><td class="num">{{printf "%.2f" .Amount}}</td></tr>
{{end}}
</tbody>
</table>
<div class="sign">Signature</div>
</body>
</html>
tpl := template.Must(template.ParseFiles("templates/invoice.html"))
var html bytes.Buffer
if err := tpl.Execute(&html, inv); err != nil {
log.Fatal(err)
}
out, err := pdf.Render(context.Background(), html.String(), os.Getenv("CHROMIUM_PATH"))
if err != nil {
log.Fatal(err)
}
fmt.Printf("wrote invoice.pdf: %d bytes, %d pages\n", len(out), pdf.CountPages(out))
Use html/template, not text/template. The HTML runs in a real browser, so a customer name with a <script> tag in it would run too. In my test I put <script>alert(1)</script> in the customer name and it came out in the PDF as plain text, escaped, which is what you want.
go run ./cmd/invoice
wrote invoice.pdf: 117324 bytes, 3 pages
On my Mac with the normal Google Chrome installed, chromedp found Chrome by itself, so the path can stay empty locally. The very first render took about 8 seconds (cold start of Chrome), after that a full go run with browser start and 60 table rows took between 1.2 and 2.4 seconds.
Counting pages without a PDF library
Our e-sign step needs to know which page the signature box is on, and with a variable number of rows that is the last page, whatever it turns out to be. Pulling in a full PDF parser for one number felt like too much. Chromium writes one /Type /Page object per page and one /Type /Pages node for the page tree, so a regex that skips the s does the job:
// pageRe matches "/Type /Page" but not "/Type /Pages", the page tree node.
var pageRe = regexp.MustCompile(`/Type\s*/Page(?:[^s]|$)`)
// CountPages is a rough page count without a PDF parser. Good enough for
// PDFs Chromium just wrote; don't trust it for PDFs from outside.
func CountPages(b []byte) int {
return len(pageRe.FindAll(b, -1))
}
It is rough. A PDF with compressed object streams can hide those markers, and other tools write PDFs differently. For PDFs that Chromium produced a second ago it gave the right answer in both renders I did, the invoice and a three page test where each page is forced with page-break-after. The test for that runs only when you ask for it, because it needs a real browser:
go test ./...
PDF_TEST_CHROME=1 go test -run TestRender ./pdf
Running it in a container
In the container we install Chromium from Debian and point the code at it with an env var:
FROM golang:1.27 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/invoice ./cmd/invoice
FROM debian:trixie-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends chromium fonts-liberation ca-certificates \
&& rm -rf /var/lib/apt/lists/*
ENV CHROMIUM_PATH=/usr/bin/chromium
WORKDIR /app
COPY --from=build /out/invoice ./invoice
COPY templates ./templates
CMD ["./invoice"]
I stayed on Debian slim. Alpine is smaller but I didn't want to find out how Chromium and fonts behave on musl, and Debian just worked. The image does get big, Chromium is the bulk of it. I wrote this Dockerfile for the post but did not build it here, the image we run in the real service follows the same idea on Debian bookworm.
Install fonts on purpose. A slim image has very few, and whatever font your CSS asks for has to exist in the container or Chromium falls back to something else. I name Liberation Sans in the CSS and install fonts-liberation, so what I see on my Mac and what comes out of the container stay close.
About the flags. no-sandbox is needed because the process usually runs as root in the container and Chromium refuses to start its sandbox as root. That takes away a layer of protection, so only ever render your own templates with escaped data. Never point this at a URL a user gave you. One day in July the team tried a longer list of flags and pointed CHROMIUM_PATH at the binary under /usr/lib/chromium/ instead of the Debian launcher script. Both changes was reverted within minutes, same morning and the short list above is what stayed. My take: start with the three flags, and only add one when you have an actual error that it fixes.
Also, chromedp now turns on disable-dev-shm-usage in its default options. Docker gives a container only 64 MB of /dev/shm by default and Chromium can crash when that fills, so that one you get for free.
If you deploy the image to ECS or Kubernetes, give the task more memory than the Go binary alone needs. A Chromium render is a few hundred MB for a short moment. And keep the start command as CMD, the reason is in why your Docker image should use CMD and not ENTRYPOINT when ECS overrides the command. For the multi-stage part of the Dockerfile there is an older post, creating a multi-stage Dockerfile for a golang web service.
That's it. The templates stay in HTML where they belong, and the Go side is about 60 lines.