Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

gpdf

> 编程语言
Open source

gpdf English | 日本語 | 中文 | 한국어 | Español | Português A pure Go, zero-dependency PDF generation library with a layered architecture and decla…

381 stars0 likes1 views
WebsiteGitHub

About

gpdf English | 日本語 | 中文 | 한국어 | Español | Português A pure Go, zero-dependency PDF generation library with a layered architecture and decla…

gpdf

English | 日本語 | 中文 | 한국어 | Español | Português

A pure Go, zero-dependency PDF generation library with a layered architecture and declarative builder API.

Features

  • Zero dependencies — only the Go standard library
  • Layered architecture — low-level PDF primitives, document model, and high-level template API
  • 12-column grid system — Bootstrap-style responsive layout
  • TrueType font support — embed custom fonts with subsetting
  • CJK ready — full CJK text support from day one
  • Tables — headers, column widths, striped rows, vertical alignment, outer + per-cell borders
  • Borders & backgrounds — apply to tables, images, and box containers (solid / dashed / dotted)
  • Headers & Footers — consistent across all pages with page numbers
  • Lists — bulleted and numbered lists
  • QR codes — pure Go QR code generation with error correction levels
  • Barcodes — Code 128 barcode generation
  • Text decorations — underline, strikethrough, letter spacing, text indent
  • Page numbers — automatic page number and total page count
  • Go template integration — generate PDFs from Go templates
  • Reusable components — pre-built Invoice, Report, and Letter templates
  • JSON schema — define documents entirely in JSON
  • Multiple units — pt, mm, cm, in, em, %
  • Color spaces — RGB, Grayscale, CMYK
  • Images — JPEG and PNG embedding with fit options
  • Absolute positioning — place elements at exact XY coordinates on the page
  • Existing PDF overlay — open existing PDFs and add text, images, stamps on top
  • Form flattening — flatten AcroForm fields into static page content, preserving non-widget annotations
  • PDF merging — combine multiple PDFs into one with page range selection
  • Document metadata — title, author, subject, creator
  • Encryption — AES-256 encryption (ISO 32000-2, Rev 6) with owner/user passwords and permissions
  • PDF/A — PDF/A-1b and PDF/A-2b conformance with ICC profiles and XMP metadata
  • Digital signatures — CMS/PKCS#7 signatures with RSA/ECDSA keys and optional RFC 3161 timestamping

Benchmark

Comparison with go-pdf/fpdf, signintech/gopdf, and maroto v2. Median of 5 runs, 100 iterations each. Apple M1, Go 1.25.

Execution time (lower is better):

Benchmark gpdf fpdf gopdf maroto v2
Single page 13 µs 132 µs 423 µs 237 µs
Table (4x10) 108 µs 241 µs 835 µs 8.6 ms
100 pages 683 µs 11.7 ms 8.6 ms 19.8 ms
Complex document 133 µs 254 µs 997 µs 10.4 ms

Memory usage (lower is better):

Benchmark gpdf fpdf gopdf maroto v2
Single page 16 KB 1.2 MB 1.8 MB 61 KB
Table (4x10) 209 KB 1.3 MB 1.9 MB 1.6 MB
100 pages 909 KB 121 MB 83 MB 4.0 MB
Complex document 246 KB 1.3 MB 2.0 MB 2.0 MB

Why is gpdf fast?

  • Single page — Single-pass build→layout→render pipeline with no intermediate data structures. Concrete struct types throughout (no interface{} boxing), so the document tree is built with minimal heap allocations.
  • Table — Cell content is written directly as PDF content stream commands via a reusable strings.Builder buffer. No per-cell object wrapping or repeated font lookups; the font is resolved once per document.
  • 100 pages — Layout scales linearly O(n). Overflow pagination passes remaining nodes by slice reference (no deep copies). The font is parsed once and shared across all pages.
  • Complex document — Single-pass layout without re-measurement combines all the above. Font subsetting embeds only the glyphs actually used, and Flate compression is applied by default, keeping both memory and output size small.

Run benchmarks yourself:

bash
cd _benchmark && go test -bench=. -benchmem -count=5

Architecture

┌─────────────────────────────────────┐
│  gpdf (entry point)                 │
├─────────────────────────────────────┤
│  template  — Builder API, Grid      │  Layer 3
├─────────────────────────────────────┤
│  document  — Nodes, Style, Layout   │  Layer 2
├─────────────────────────────────────┤
│  pdf       — Writer, Fonts, Streams │  Layer 1
└─────────────────────────────────────┘

Requirements

  • Go 1.22 or later

Install

bash
go get github.com/gpdf-dev/gpdf

Quick Start

go
package main

import (
	"os"

	"github.com/gpdf-dev/gpdf"
	"github.com/gpdf-dev/gpdf/document"
	"github.com/gpdf-dev/gpdf/template"
)

func main() {
	doc := gpdf.NewDocument(
		gpdf.WithPageSize(gpdf.A4),
		gpdf.WithMargins(document.UniformEdges(document.Mm(20))),
	)

	page := doc.AddPage()
	page.AutoRow(func(r *template.RowBuilder) {
		r.Col(12, func(c *template.ColBuilder) {
			c.Text("Hello, World!", template.FontSize(24), template.Bold())
		})
	})

	data, _ := doc.Generate()
	os.WriteFile("hello.pdf", data, 0644)
}

Examples

Text Styling

Font size, weight, style, color, background color, and alignment:

go
page.AutoRow(func(r *template.RowBuilder) {
	r.Col(12, func(c *template.ColBuilder) {
		c.Text("Large bold title", template.FontSize(24), template.Bold())
		c.Text("Italic text", template.Italic())
		c.Text("Bold + Italic", template.Bold(), template.Italic())
		c.Text("Red text", template.TextColor(pdf.Red))
		c.Text("Custom color", template.TextColor(pdf.RGBHex(0x336699)))
		c.Text("With background", template.BgColor(pdf.Yellow))
		c.Text("Centered", template.AlignCenter())
		c.Text("Right aligned", template.AlignRight())
	})
})

CJK Fonts (Japanese / Chinese / Korean)

Embed TrueType fonts for CJK text rendering. Each language needs its own Noto Sans font:

go
fontData, _ := os.ReadFile("NotoSansJP-Regular.ttf")

doc := gpdf.NewDocument(
	gpdf.WithPageSize(gpdf.A4),
	gpdf.WithFont("NotoSansJP", fontData),
	gpdf.WithDefaultFont("NotoSansJP", 12),
)

page := doc.AddPage()
page.AutoRow(func(r *template.RowBuilder) {
	r.Col(12, func(c *template.ColBuilder) {
		c.Text("こんにちは世界", template.FontSize(18))
	})
})

For multi-language documents, register multiple fonts and switch with FontFamily():

…

Recommended fonts (all free, OFL license):

Font Language
Noto Sans JP Japanese
Noto Sans SC Simplified Chinese
Noto Sans KR Korean

12-Column Grid Layout

Build layouts using a Bootstrap-style 12-column grid:

…

Fixed-Height Rows

Use Row() with a specific height, or AutoRow() for content-based height:

go
// Fixed height: 30mm
page.Row(document.Mm(30), func(r *template.RowBuilder) {
	r.Col(12, func(c *template.ColBuilder) {
		c.Text("This row is 30mm tall")
	})
})

// Auto height (fits content)
page.AutoRow(func(r *template.RowBuilder) {
	r.Col(12, func(c *template.ColBuilder) {
		c.Text("Height adjusts to content")
	})
})

Tables

Basic table:

go
c.Table(
	[]string{"Name", "Age", "City"},
	[][]string{
		{"Alice", "30", "Tokyo"},
		{"Bob", "25", "New York"},
		{"Charlie", "35", "London"},
	},
)

Styled table with header colors, column widths, and stripe rows:

go
c.Table(
	[]string{"Product", "Category", "Qty", "Unit Price", "Total"},
	[][]string{
		{"Laptop Pro 15", "Electronics", "2", "$1,299.00", "$2,598.00"},
		{"Wireless Mouse", "Accessories", "10", "$29.99", "$299.90"},
		{"USB-C Hub", "Accessories", "5", "$49.99", "$249.95"},
	},
	template.ColumnWidths(30, 20, 10, 20, 20),
	template.TableHeaderStyle(
		template.TextColor(pdf.White),
		template.BgColor(pdf.RGBHex(0x1A237E)),
	),
	template.TableStripe(pdf.RGBHex(0xF5F5F5)),
)

Table borders — outer frame, per-cell grid, or both:

…

Images

Embed JPEG and PNG images with optional fit options:

go
// Default size (original dimensions)
c.Image(imgData)

// Fit to specific width (maintains aspect ratio)
c.Image(imgData, template.FitWidth(document.Mm(80)))

// Fit to specific height (maintains aspect ratio)
c.Image(imgData, template.FitHeight(document.Mm(30)))

Images in grid columns:

go
page.AutoRow(func(r *template.RowBuilder) {
	r.Col(6, func(c *template.ColBuilder) {
		c.Text("Image 1")
		c.Image(pngData)
	})
	r.Col(6, func(c *template.ColBuilder) {
		c.Text("Image 2")
		c.Image(jpegData)
	})
})

Image with a border and a solid backdrop (handy for transparent PNGs):

go
c.Image(pngData,
	template.FitWidth(document.Mm(60)),
	template.WithImageBorder(template.Border(
		template.BorderWidth(document.Pt(2)),
		template.BorderColor(pdf.RGBHex(0xE53935)),
	)),
	template.WithImageBackground(pdf.RGBHex(0xFFF8E1)),
)

Boxes

Wrap arbitrary column content in a styled rectangular container with a border, fill, and padding:

go
c.Box(func(c *template.ColBuilder) {
	c.Text("Inside a box")
	c.Text("with two lines of body copy")
},
	template.WithBoxBorder(template.Border(
		template.BorderWidth(document.Pt(1)),
		template.BorderColor(pdf.RGBHex(0x1A237E)),
	)),
	template.WithBoxBackground(pdf.RGBHex(0xE8EAF6)),
	template.WithBoxPadding(document.UniformEdges(document.Mm(4))),
)

Lines & Spacers

Horizontal rules with color and thickness:

go
c.Line()                                           // Default (gray, 1pt)
c.Line(template.LineColor(pdf.Red))                 // Colored
c.Line(template.LineThickness(document.Pt(3)))      // Thick
c.Line(template.LineColor(pdf.Blue),                // Combined
	template.LineThickness(document.Pt(2)))

Vertical spacing:

go
c.Spacer(document.Mm(5))   // 5mm gap
c.Spacer(document.Mm(15))  // 15mm gap

Lists

Bulleted and numbered lists:

go
// Bulleted list
c.List([]string{"First item", "Second item", "Third item"})

// Numbered list
c.OrderedList([]string{"Step one", "Step two", "Step three"})

QR Codes

Generate QR codes with configurable size and error correction:

go
// Basic QR code
c.QRCode("https://gpdf.dev")

// Custom size and error correction level
c.QRCode("https://gpdf.dev",
	template.QRSize(document.Mm(30)),
	template.QRErrorCorrection(qrcode.LevelH))

Barcodes

Generate Code 128 barcodes:

go
// Basic barcode
c.Barcode("INV-2026-0001")

// Custom width
c.Barcode("INV-2026-0001", template.BarcodeWidth(document.Mm(80)))

Page Numbers

Automatic page numbers and total page count:

go
doc.Footer(func(p *template.PageBuilder) {
	p.AutoRow(func(r *template.RowBuilder) {
		r.Col(6, func(c *template.ColBuilder) {
			c.Text("Generated by gpdf", template.FontSize(8))
		})
		r.Col(6, func(c *template.ColBuilder) {
			c.PageNumber(template.AlignRight(), template.FontSize(8))
		})
	})
})

doc.Header(func(p *template.PageBuilder) {
	p.AutoRow(func(r *template.RowBuilder) {
		r.Col(12, func(c *template.ColBuilder) {
			c.TotalPages(template.AlignRight(), template.FontSize(9))
		})
	})
})

Text Decorations

Underline, strikethrough, letter spacing, and text indent:

go
c.Text("Underlined text", template.Underline())
c.Text("Strikethrough text", template.Strikethrough())
c.Text("Wide spacing", template.LetterSpacing(3))
c.Text("Indented paragraph...", template.TextIndent(document.Pt(24)))

Headers & Footers

Define headers and footers that repeat on every page:

…

Multi-Page Documents

go
for i := 1; i <= 5; i++ {
	page := doc.AddPage()
	page.AutoRow(func(r *template.RowBuilder) {
		r.Col(12, func(c *template.ColBuilder) {
			c.Text("Page content here")
		})
	})
}

Existing PDF Overlay

Open an existing PDF and overlay content using the same builder API:

…

Form Flattening

Flatten interactive AcroForm fields into static page content. Non-

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Go

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言