Docs/Web & UI/PDF generation

PDF generation

Generate PDF 1.4 invoices, receipts, and reports in pure Go with fletch/pdf: flowing text, headings, rules, multi-page tables, and metadata.

github.com/fletchhq/fletch/pdf

fletch/pdfpkg.go.dev

Updated 2026-12-06 fletch docs show pdf 5 min read

On this page

github.com/fletchhq/fletch/pdf writes PDF 1.4 documents in pure Go with zero external dependencies, zero CGO, and no headless Chrome binary. It supports flowing word-wrapped text, headings, horizontal rules, multi-page tables with repeated headers, page numbers, stream compression, and document metadata.

Introduction

Many applications need to produce structured business documents—invoices, receipts, order summaries, or certificates of analysis—without bundling a browser engine or shelling out to a sidecar service. fletch/pdf gives you a small, standard-library-only builder that compiles into your Go binary and outputs valid PDF 1.4 bytes directly to an io.Writer or byte slice.

Core concepts

Creating a document

Create a document with pdf.New(opts...). A new *pdf.Document starts with one blank page using pdf.A4 (595.28 × 841.89 pt) and 56 pt margins (about 2 cm) on all four sides. Content flows downward from the top margin and opens new pages automatically whenever an element does not fit.

doc := pdf.New(
	pdf.PageSize(pdf.Letter),
	pdf.Margin(54),
	pdf.PageNumbers(),
	pdf.Compress(),
	pdf.WithMetadata(pdf.Metadata{
		Title:   "Invoice INV-0042",
		Author:  "Acme Corp",
		Subject: "Monthly subscription",
		Creator: "acme-billing",
	}),
)

If you pass a zero or negative PageSize, or a Margin that leaves no usable space, pdf.New falls back to pdf.A4 and 56 pt. A *pdf.Document is not safe for concurrent use; construct one document per PDF you generate.

Text, headings, rules, and spacing

Add content in top-to-bottom order with Heading, Text, Rule, Space, and PageBreak. Text wraps long lines automatically at the content width and honors embedded \n newlines. Pass an optional pdf.Style to override alignment, font size, weight, or color.

doc.Heading(1, "Invoice INV-0042")
doc.Text("Bill to: Zoë Müller (Café Ltd)\nNet 30 — due 2027-01-01")
doc.Space(8)
doc.Rule()
doc.Text("Status: Paid", pdf.Style{
	Align: pdf.Right,
	Size:  12,
	Bold:  true,
	Color: pdf.RGB(22, 163, 74),
})

Colors use RGB channels from 0 to 1 (pdf.Color{} is black). Use pdf.RGB(r, g, b) for 0–255 values or pdf.Gray(v) for grays between 0 (black) and 1 (white). Call doc.PageBreak() to start a new page explicitly, and doc.Pages() to inspect the current page count.

Tables that break across pages

Call doc.Table(pdf.Table{...}) to render a shaded header row followed by data rows. Column Width values are relative weights across the usable page width; omitted widths default evenly. When a table reaches the bottom of a page, fletch/pdf opens a new page and repeats the header row automatically.

err := doc.Table(pdf.Table{
	Columns: []pdf.Column{
		{Header: "Description", Width: 4},
		{Header: "Qty", Align: pdf.Right},
		{Header: "Amount", Align: pdf.Right, Width: 2},
	},
	Rows: [][]string{
		{"Pro Plan (December)", "1", "$49.00"},
		{"Extra seats", "3", "$30.00"},
		{"Total", "", "$79.00"},
	},
	BoldLastRow: true,
})
if err != nil {
	return err
}

Table returns an error if Columns is empty or if any row has a different cell count than Columns. If a single row plus the table header is taller than one page's usable height, Table returns pdf.ErrRowTooTall.

Rendering bytes or streaming to an io.Writer

Finish a document by calling doc.Bytes() or doc.WriteTo(w). Calling Bytes() does not mutate the document, so you may call it more than once (for example, once to archive the PDF in object storage and once to return it to the caller).

data, err := doc.Bytes()
if err != nil {
	return err
}

When pdf.WithMetadata leaves Created zero, Bytes() stamps the current UTC time; when Creator is empty, it defaults to "Fletch". Enabling pdf.Compress() deflates each page's content stream with zlib (/FlateDecode).

Common tasks

Serving a PDF from a Fletch handler

Because *pdf.Document implements io.WriterTo, you can write it straight to an http.ResponseWriter after setting Content-Type and Content-Disposition.

func downloadInvoice(w http.ResponseWriter, r *http.Request) {
	doc := pdf.New(
		pdf.PageSize(pdf.Letter),
		pdf.PageNumbers(),
		pdf.Compress(),
		pdf.WithMetadata(pdf.Metadata{
			Title:  "Invoice INV-0042",
			Author: "Acme Corp",
		}),
	)

	doc.Heading(1, "Invoice INV-0042")
	doc.Text("Issued: 2026-12-05\nCustomer: Acme Labs")
	doc.Space(12)
	doc.Rule()

	err := doc.Table(pdf.Table{
		Columns: []pdf.Column{
			{Header: "Item", Width: 4},
			{Header: "Qty", Align: pdf.Right},
			{Header: "Price", Align: pdf.Right, Width: 2},
		},
		Rows: [][]string{
			{"Annual license", "1", "$1,200.00"},
			{"Total", "", "$1,200.00"},
		},
		BoldLastRow: true,
	})
	if err != nil {
		http.Error(w, "could not build invoice", http.StatusInternalServerError)
		return
	}

	raw, err := doc.Bytes()
	if err != nil {
		http.Error(w, "could not render pdf", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/pdf")
	w.Header().Set("Content-Disposition", `attachment; filename="invoice-0042.pdf"`)
	w.Header().Set("Content-Length", strconv.Itoa(len(raw)))
	_, _ = w.Write(raw)
}

Rendering to raw before writing headers ensures that any rendering error can still return a clean 500 response instead of a half-written PDF stream. Use inline instead of attachment in Content-Disposition if you want the browser to display the PDF in a tab.

Attaching a generated PDF to an email

Pass the slice from doc.Bytes() directly into mail.Attachment when sending receipts or statements through Fletch's mailer:

raw, err := doc.Bytes()
if err != nil {
	return err
}

err = app.Mailer().Send(ctx, mail.Message{
	From:    "billing@acme.example",
	To:      []string{customer.Email},
	Subject: "Your invoice INV-0042",
	Text:    "Your invoice is attached.",
	Attachments: []mail.Attachment{
		{
			Filename:    "invoice-0042.pdf",
			ContentType: "application/pdf",
			Content:     raw,
		},
	},
})

Reference

Document options

Option Default Behavior
pdf.PageSize(s pdf.Size) pdf.A4 (595.28 × 841.89 pt) Sets the page dimensions in points (1/72 inch). pdf.Letter is 612 × 792 pt.
pdf.Margin(pts float64) 56 pt Sets all four page margins in points.
pdf.WithMetadata(m pdf.Metadata) Creator: "Fletch", Created: time.Now() Populates the PDF info dictionary (Title, Author, Subject, Keywords, Creator, Created).
pdf.PageNumbers() off Prints "Page i of n" centered at the bottom of every page and reserves bottom margin space.
pdf.Compress() off Deflates page content streams with zlib (/FlateDecode).

Types, helpers, and methods

Symbol Role
pdf.New(opts ...Option) *Document Creates a new single-page document.
(*Document).Heading(level int, text string) Writes a bold heading scaled by level (for example 1, 2, 3).
(*Document).Text(s string, style ...Style) Writes word-wrapped text with optional Style{Align, Size, Bold, Color}.
(*Document).Rule() Draws a horizontal rule across the content width.
(*Document).Space(pts float64) Advances vertical cursor by pts points.
(*Document).PageBreak() Starts a new page when the current page already has content.
(*Document).Pages() int Returns the number of pages built so far.
(*Document).Table(t Table) error Renders a multi-page table with repeated headers (Columns, Rows, BoldLastRow).
(*Document).Bytes() ([]byte, error) Serializes the finished PDF 1.4 bytes without mutating the document.
(*Document).WriteTo(w io.Writer) (int64, error) Writes the finished PDF to w.
pdf.Left, pdf.Center, pdf.Right Align values for Style and Column.
pdf.Gray(v float64) Color Grayscale color from 0 (black) to 1 (white).
pdf.RGB(r, g, b uint8) Color RGB color from 0–255 channel values.
pdf.ErrRowTooTall Sentinel error returned by Table when a row plus header exceeds one page.