gpdf Package

Overview

The gpdf package is a facade that re-exports commonly used functions from the internal layers. You can either import gpdf for convenience or import the specific packages directly.

import "github.com/gpdf-dev/gpdf"

// Using facade
doc := gpdf.NewDocument(gpdf.WithPageSize(gpdf.A4))
import (
    "github.com/gpdf-dev/gpdf/template"
    "github.com/gpdf-dev/gpdf/document"
)

// Using packages directly (recommended)
doc := template.New(template.WithPageSize(document.A4))

Functions

NewDocument

func NewDocument(opts ...template.Option) *template.Document

Creates a new PDF document builder. This is the primary entry point.

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

FromJSON

func FromJSON(schema []byte, data any, opts ...template.Option) (*template.Document, error)

Creates a Document from a JSON schema definition with optional Go template data binding.

doc, err := gpdf.FromJSON(schema, map[string]any{"title": "Report"})

FromTemplate

func FromTemplate(tmpl *template.Template, data any, opts ...template.Option) (*template.Document, error)

Creates a Document by executing a pre-parsed Go template that produces JSON schema output.

TemplateFuncMap

func TemplateFuncMap() template.FuncMap

Returns helper functions (toJSON, etc.) for use when parsing Go templates.

Document Options

FunctionDescription
WithPageSize(size)Set page dimensions (A4, A3, Letter, Legal)
WithMargins(edges)Set page margins
WithFont(family, data)Register a TrueType font (accepts []byte)
WithDefaultFont(family, size)Set the default font family and size
WithMetadata(meta)Set document metadata
WithEncryption(opts...)Enable AES-256 encryption
WithPDFA(opts...)Enable PDF/A conformance

Document Metadata

gpdf.WithMetadata(document.DocumentMetadata{
    Title:   "Invoice #INV-2026-001",
    Author:  "ACME Corporation",
    Subject: "Monthly Invoice",
    Creator: "gpdf v1.0.3",
})

Page Sizes

ConstantDimensions
gpdf.A4 / document.A4210mm x 297mm (595.28pt x 841.89pt)
gpdf.A3 / document.A3297mm x 420mm (841.89pt x 1190.55pt)
gpdf.Letter / document.Letter8.5" x 11" (612pt x 792pt)
gpdf.Legal / document.Legal8.5" x 14" (612pt x 1008pt)

Document Methods

AddPage

func (d *Document) AddPage() *PageBuilder

Adds a new page and returns its builder.

func (d *Document) Header(fn func(p *PageBuilder))
func (d *Document) Footer(fn func(p *PageBuilder))

Define content that repeats on every page.

Generate / Render

func (d *Document) Generate() ([]byte, error)
func (d *Document) Render(w io.Writer) error

Generate() returns the PDF as a byte slice. Render() writes directly to an io.Writer.

PageBuilder Methods

Row

func (p *PageBuilder) Row(height document.Value, fn func(r *RowBuilder))
func (p *PageBuilder) AutoRow(fn func(r *RowBuilder))

Row() creates a fixed-height row. AutoRow() creates a row that adjusts to content.

RowBuilder Methods

Col

func (r *RowBuilder) Col(span int, fn func(c *ColBuilder))

Creates a column spanning span out of 12 grid columns.

ColBuilder Methods

MethodDescription
Text(text, opts...)Add text with styling options
Image(data, opts...)Add an image (JPEG or PNG bytes)
Table(headers, rows, opts...)Add a table
List(items, opts...)Add an unordered list
OrderedList(items, opts...)Add an ordered list
Line(opts...)Add a horizontal rule
Spacer(height)Add vertical spacing
QRCode(data, opts...)Add a QR code
Barcode(data, opts...)Add a barcode (Code 128)
RichText(fn)Add mixed-style inline text
PageNumber(opts...)Current page number
TotalPages(opts...)Total page count

QR Code Options

FunctionDescription
QRSize(value)Display size (width = height)
QRErrorCorrection(level)Error correction: LevelL, LevelM, LevelQ, LevelH
QRScale(s)Pixels per QR module

Barcode Options

FunctionDescription
BarcodeWidth(value)Display width
BarcodeHeight(value)Display height
BarcodeFormat(format)Barcode format (default: Code 128)

Existing PDF Operations

Open

func Open(data []byte, opts ...template.Option) (*template.ExistingDocument, error)

Opens an existing PDF for reading and modification. Returns an ExistingDocument that supports overlay operations via Incremental Update (non-destructive append).

doc, err := gpdf.Open(pdfBytes)

ExistingDocument Methods

MethodDescription
PageCount() (int, error)Returns the number of pages in the PDF
Overlay(pageIndex int, fn func(p *PageBuilder)) errorAdd content on top of a specific page (0-based index)
EachPage(fn func(pageIndex int, p *PageBuilder)) errorAdd content on top of every page
Save() ([]byte, error)Returns the modified PDF as a byte slice
doc, err := gpdf.Open(pdfBytes, gpdf.WithFont("NotoSans", fontData))

// Add watermark on page 1
doc.Overlay(0, func(p *template.PageBuilder) {
    p.Absolute(document.Mm(40), document.Mm(120), func(c *template.ColBuilder) {
        c.Text("DRAFT", template.FontSize(72),
            template.TextColor(pdf.Gray(0.85)))
    })
})

// Add page numbers on every page
count, _ := doc.PageCount()
doc.EachPage(func(i int, p *template.PageBuilder) {
    p.Absolute(document.Mm(170), document.Mm(285), func(c *template.ColBuilder) {
        c.Text(fmt.Sprintf("%d / %d", i+1, count),
            template.FontSize(10), template.AlignRight())
    }, template.AbsoluteWidth(document.Mm(20)))
})

result, err := doc.Save()

PDF Merge Since v1.0.2

Merge

func Merge(sources []Source, opts ...MergeOption) ([]byte, error)

Combines pages from multiple PDF sources into a single output PDF.

merged, err := gpdf.Merge([]gpdf.Source{
    {Data: cover},
    {Data: body},
})

Source

type Source struct {
    Data  []byte    // raw PDF bytes
    Pages PageRange // which pages to include; zero value = all pages
}

PageRange

type PageRange struct {
    From int  // 1-based start page; 0 means first page
    To   int  // 1-based end page; 0 means last page
}

Merge Options

FunctionDescription
WithMergeMetadata(title, author, producer)Set document info (title, author, producer) on merged output
merged, err := gpdf.Merge(
    []gpdf.Source{
        {Data: cover},
        {Data: body},
        {Data: appendix},
    },
    gpdf.WithMergeMetadata("Policy Bundle", "Example Ltd", "gpdf"),
)

Component Constructors

FunctionDescription
NewInvoice(data)Create an invoice PDF
NewReport(data)Create a report PDF
NewLetter(data)Create a business letter PDF

See Components for detailed usage.

Encryption

AES-256 encryption (ISO 32000-2, Rev 6) with owner/user passwords and permission control.

WithEncryption

func WithEncryption(opts ...encrypt.Option) template.Option

Enables PDF encryption.

doc := gpdf.NewDocument(
    gpdf.WithPageSize(gpdf.A4),
    gpdf.WithEncryption(
        encrypt.WithOwnerPassword("owner-pass"),
        encrypt.WithUserPassword("user-pass"),
        encrypt.WithPermissions(encrypt.PermPrint|encrypt.PermCopy),
    ),
)

Encryption Options

FunctionDescription
encrypt.WithOwnerPassword(pw)Set owner password
encrypt.WithUserPassword(pw)Set user password
encrypt.WithPermissions(perm)Set document permissions

Permissions

ConstantDescription
encrypt.PermPrintAllow printing
encrypt.PermModifyAllow modification
encrypt.PermCopyAllow copying text
encrypt.PermAnnotateAllow annotations
encrypt.PermPrintHighResAllow high-resolution printing
encrypt.PermAllAll permissions (default)

PDF/A Conformance

Generate PDF/A-1b or PDF/A-2b compliant documents with ICC color profiles and XMP metadata.

WithPDFA

func WithPDFA(opts ...pdfa.Option) template.Option

Enables PDF/A conformance.

doc := gpdf.NewDocument(
    gpdf.WithPageSize(gpdf.A4),
    gpdf.WithPDFA(
        pdfa.WithLevel(pdfa.LevelA2b),
        pdfa.WithMetadata(pdfa.MetadataInfo{
            Title:  "Archived Report",
            Author: "gpdf",
        }),
    ),
)

PDF/A Options

FunctionDescription
pdfa.WithLevel(level)Set conformance level (LevelA1b, LevelA2b)
pdfa.WithMetadata(info)Set XMP metadata

PDF/A Levels

ConstantDescription
pdfa.LevelA1bPDF/A-1b (ISO 19005-1, Level B) — default
pdfa.LevelA2bPDF/A-2b (ISO 19005-2, Level B)

Digital Signatures

CMS/PKCS#7 digital signatures with RSA or ECDSA keys.

SignDocument

func SignDocument(pdfData []byte, signer signature.Signer, opts ...signature.Option) ([]byte, error)

Signs a generated PDF with a digital signature.

data, _ := doc.Generate()

signed, err := gpdf.SignDocument(data, signature.Signer{
    Certificate: cert,
    PrivateKey:  key,
    Chain:       intermediates, // optional
},
    signature.WithReason("Approved"),
    signature.WithLocation("Tokyo"),
)

Signer

type Signer struct {
    Certificate *x509.Certificate
    PrivateKey  crypto.PrivateKey    // *rsa.PrivateKey or *ecdsa.PrivateKey
    Chain       []*x509.Certificate  // intermediate certificates (optional)
}

Signature Options

FunctionDescription
signature.WithReason(reason)Set the reason for signing
signature.WithLocation(location)Set the location of signing
signature.WithTimestamp(tsaURL)Enable RFC 3161 timestamping
signature.WithSignTime(t)Set signing time (default: current time)