pdf

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 12, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package pdf is a write-only PDF 1.3–1.7 serializer: the low-level object model, document/xref writer, content-stream operator builder, and standard-14 font support. It is the Go replacement for react-pdf's pdfkit fork. Higher layers (layout, render) build documents through this package.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsStandardFont

func IsStandardFont(name string) bool

IsStandardFont reports whether name is one of the 14 standard fonts.

func MeasureText

func MeasureText(baseFont string, size float64, text string) (float64, error)

MeasureText returns the advance width in points of text set in a standard font at the given size, under WinAnsiEncoding. It errors if baseFont is not one of the 14 standard fonts.

func StandardFonts

func StandardFonts() []string

StandardFonts returns the 14 standard PDF font names.

Types

type Array

type Array []Object

Array is a PDF array.

type Boolean

type Boolean bool

Boolean is a PDF boolean.

type ChoiceOption

type ChoiceOption struct {
	Export  string
	Display string
}

ChoiceOption is one entry of a choice field: an export value and the display label shown to the user (often identical).

type Content

type Content struct {
	// contains filtered or unexported fields
}

Content builds a page content stream from PDF drawing operators. Methods are chainable. It also records which standard fonts were used so the page can build a matching /Font resource dictionary.

func NewContent

func NewContent() *Content

NewContent returns an empty content-stream builder.

func (*Content) AddFormField

func (c *Content) AddFormField(f FormField)

AddFormField records an interactive form field widget for this page.

func (c *Content) AddLink(x0, y0, x1, y1 float64, uri string)

AddLink records a hyperlink annotation over the given page-space rectangle.

func (*Content) AddNote

func (c *Content) AddNote(x, y float64, text string)

AddNote records a text-note annotation anchored at the given page-space point.

func (*Content) AlphaResource

func (c *Content) AlphaResource(a float64) (Name, bool)

AlphaResource returns the resource name assigned to an alpha value.

func (*Content) Alphas

func (c *Content) Alphas() []float64

Alphas returns the alpha values used, in first-use order.

func (*Content) BeginText

func (c *Content) BeginText() *Content

BeginText begins a text object (BT).

func (*Content) Bytes

func (c *Content) Bytes() []byte

Bytes returns the raw (uncompressed) content-stream bytes.

func (*Content) CharSpacing

func (c *Content) CharSpacing(v float64) *Content

CharSpacing sets the character spacing (Tc).

func (*Content) Clip

func (c *Content) Clip() *Content

Clip intersects the clip path using the nonzero rule (W).

func (*Content) ClipEvenOdd

func (c *Content) ClipEvenOdd() *Content

ClipEvenOdd intersects the clip path using the even-odd rule (W*).

func (*Content) ClosePath

func (c *Content) ClosePath() *Content

ClosePath closes the current subpath (h).

func (*Content) CurveTo

func (c *Content) CurveTo(x1, y1, x2, y2, x3, y3 float64) *Content

CurveTo appends a cubic Bézier segment (c).

func (*Content) Dash

func (c *Content) Dash(phase float64, pattern ...float64) *Content

Dash sets the line dash pattern (d).

func (*Content) DrawImage

func (c *Content) DrawImage(spec *ImageSpec, x, y, w, h float64) *Content

DrawImage draws an image, scaled to w×h at (x, y) in the current coordinate system (bottom-left origin). Images are drawn from a unit square, so the CTM maps them to the target rectangle.

func (*Content) EmbeddedFontResource

func (c *Content) EmbeddedFontResource(ef *EmbeddedFont) (Name, bool)

EmbeddedFontResource returns the resource name assigned to an embedded font.

func (*Content) EmbeddedFonts

func (c *Content) EmbeddedFonts() []*EmbeddedFont

EmbeddedFonts returns the embedded fonts used, in first-use order.

func (*Content) EndPath

func (c *Content) EndPath() *Content

EndPath ends the path with no fill or stroke (n), e.g. after a clip.

func (*Content) EndText

func (c *Content) EndText() *Content

EndText ends a text object (ET).

func (*Content) Fill

func (c *Content) Fill() *Content

Fill fills the path with the nonzero winding rule (f).

func (*Content) FillEvenOdd

func (c *Content) FillEvenOdd() *Content

FillEvenOdd fills the path with the even-odd rule (f*).

func (*Content) FillGray

func (c *Content) FillGray(v float64) *Content

FillGray sets the nonstroking gray level (g). 0 is black, 1 is white.

func (*Content) FillRGB

func (c *Content) FillRGB(r, g, b float64) *Content

FillRGB sets the nonstroking color in DeviceRGB (rg). Components are 0..1.

func (*Content) FillStroke

func (c *Content) FillStroke() *Content

FillStroke fills then strokes the path (B).

func (*Content) FontResource

func (c *Content) FontResource(baseFont string) (Name, bool)

FontResource returns the resource name assigned to a base font (valid after SetFont has been called for it).

func (*Content) Fonts

func (c *Content) Fonts() []string

Fonts returns the base fonts used, in first-use order.

func (*Content) FormFields

func (c *Content) FormFields() []FormField

FormFields returns the form fields recorded for this page.

func (*Content) HorizScale

func (c *Content) HorizScale(pct float64) *Content

HorizScale sets horizontal text scaling as a percentage (Tz).

func (*Content) ImageResource

func (c *Content) ImageResource(spec *ImageSpec) (Name, bool)

ImageResource returns the resource name assigned to an image.

func (*Content) Images

func (c *Content) Images() []*ImageSpec

Images returns the images used, in first-use order.

func (*Content) Leading

func (c *Content) Leading(v float64) *Content

Leading sets the text leading (TL).

func (*Content) LineCap

func (c *Content) LineCap(style int) *Content

LineCap sets the line cap style (J): 0 butt, 1 round, 2 square.

func (*Content) LineJoin

func (c *Content) LineJoin(style int) *Content

LineJoin sets the line join style (j): 0 miter, 1 round, 2 bevel.

func (*Content) LineTo

func (c *Content) LineTo(x, y float64) *Content

LineTo appends a straight segment (l).

func (*Content) LineWidth

func (c *Content) LineWidth(v float64) *Content

LineWidth sets the stroke line width (w).

func (c *Content) Links() []LinkAnnotation

Links returns the hyperlink annotations recorded for this page.

func (*Content) MoveTo

func (c *Content) MoveTo(x, y float64) *Content

MoveTo begins a new subpath (m).

func (*Content) NextLine

func (c *Content) NextLine() *Content

NextLine moves to the start of the next line (T*).

func (*Content) Notes

func (c *Content) Notes() []NoteAnnotation

Notes returns the text-note annotations recorded for this page.

func (*Content) Rect

func (c *Content) Rect(x, y, wid, hgt float64) *Content

Rect appends a rectangle subpath (re).

func (*Content) Restore

func (c *Content) Restore() *Content

Restore pops the graphics state (Q).

func (*Content) Save

func (c *Content) Save() *Content

Save pushes the graphics state (q).

func (*Content) SetAlpha

func (c *Content) SetAlpha(a float64) *Content

SetAlpha sets the constant alpha for fills and strokes (ca/CA) via an ExtGState resource, recording the alpha so the page can build /ExtGState. Values are clamped to [0,1]. Requires PDF 1.4+.

func (*Content) SetEmbeddedFont

func (c *Content) SetEmbeddedFont(ef *EmbeddedFont, size float64) *Content

SetEmbeddedFont selects an embedded TrueType font and size (Tf), registering it so the page can wire a matching /Font resource.

func (*Content) SetFont

func (c *Content) SetFont(baseFont string, size float64) *Content

SetFont selects a standard font and size (Tf). The base font is registered so the page can wire the matching resource name to a font object.

func (*Content) Shade

func (c *Content) Shade(sh *Shading) *Content

Shade registers a shading and emits `sh` to paint it, subject to the current clip path. Wrap in Save → path → Clip → EndPath → Shade → Restore to confine the gradient to a shape.

func (*Content) ShadingResource

func (c *Content) ShadingResource(sh *Shading) (Name, bool)

ShadingResource returns the resource name assigned to a shading.

func (*Content) Shadings

func (c *Content) Shadings() []*Shading

Shadings returns the shadings used, in first-use order.

func (*Content) ShowText

func (c *Content) ShowText(s string) *Content

ShowText shows a string, encoding it to WinAnsiEncoding (Tj). Runes not representable in WinAnsi are shown as '?'.

func (*Content) ShowTextRaw

func (c *Content) ShowTextRaw(enc []byte) *Content

ShowTextRaw shows already-encoded bytes as a literal string (Tj).

func (*Content) Stroke

func (c *Content) Stroke() *Content

Stroke strokes the path (S).

func (*Content) StrokeGray

func (c *Content) StrokeGray(v float64) *Content

StrokeGray sets the stroking gray level (G).

func (*Content) StrokeRGB

func (c *Content) StrokeRGB(r, g, b float64) *Content

StrokeRGB sets the stroking color in DeviceRGB (RG). Components are 0..1.

func (*Content) TextMatrix

func (c *Content) TextMatrix(a, b, cc, d, e, f float64) *Content

TextMatrix sets the text matrix (Tm).

func (*Content) TextPosition

func (c *Content) TextPosition(x, y float64) *Content

TextPosition moves to the next line offset by (tx, ty) (Td).

func (*Content) TextRise

func (c *Content) TextRise(v float64) *Content

TextRise sets the text rise, used for super/subscript (Ts).

func (*Content) Transform

func (c *Content) Transform(a, b, cc, d, e, f float64) *Content

Transform concatenates the matrix [a b c d e f] to the CTM (cm).

func (*Content) WordSpacing

func (c *Content) WordSpacing(v float64) *Content

WordSpacing sets the word spacing (Tw).

type Dict

type Dict map[Name]Object

Dict is a PDF dictionary. Keys are serialized in sorted order so that output is deterministic.

type Document

type Document struct {
	// contains filtered or unexported fields
}

Document assembles a PDF: metadata, a page tree, and shared font objects.

func New

func New(opts Options) *Document

New creates a Document with the given options.

func (*Document) AddPage

func (d *Document) AddPage(width, height float64, content *Content)

AddPage appends a page of the given size (in points) with the given content. The page's /Font resources are built from the fonts the content used.

func (*Document) SetOutline

func (d *Document) SetOutline(roots []*Outline)

SetOutline installs the document outline (bookmark tree). Passing an empty slice leaves the document without an /Outlines dictionary.

func (*Document) WriteTo

func (d *Document) WriteTo(out io.Writer) (int64, error)

WriteTo finalizes the page tree, catalog, info dictionary, and file identifier, then serializes the document to out.

type EmbeddedFont

type EmbeddedFont struct {
	Name       string // PDF /BaseFont name (unique per face)
	Program    []byte // raw TrueType (sfnt) bytes
	Descriptor FontDescriptor
	Widths     []int
	// contains filtered or unexported fields
}

EmbeddedFont is a TrueType font program embedded as a simple (WinAnsi) PDF font. Widths is indexed by WinAnsi code (0..255), in 1000-unit advances. It is compared by pointer identity, so reuse the same *EmbeddedFont per face — that also lets the compressed font program be built once and shared across every document the face appears in.

type FontDescriptor

type FontDescriptor struct {
	Ascent, Descent, CapHeight float64
	BBox                       [4]float64 // xMin, yMin, xMax, yMax
	ItalicAngle                float64
	Flags                      int
	StemV                      float64
}

FontDescriptor holds embedded-font metrics in 1000-unit text space.

type FormField

type FormField struct {
	Kind      FormFieldKind
	Name      string  // fully-qualified field name (/T)
	Value     string  // text value (/V) for text fields
	FontSize  float64 // text fields: 0 means auto-size (/DA "0 Tf")
	MultiLine bool    // text field flag: multi-line
	Password  bool    // text field flag: password (value masked)

	Checked bool   // checkbox: initial state
	OnState string // checkbox: export value of the "on" state (default "Yes")

	Options []ChoiceOption // choice field entries
	Combo   bool           // choice field: dropdown (combo) vs. list box

	X0, Y0, X1, Y1 float64 // widget rectangle in page (default user) space
}

FormField is an interactive AcroForm field rendered as a widget annotation on a page. Text fields (/Tx) and checkboxes (/Btn) are supported.

type FormFieldKind

type FormFieldKind int

FormFieldKind selects the widget type of an AcroForm field.

const (
	FieldText     FormFieldKind = iota // single- or multi-line text (/Tx)
	FieldCheckbox                      // toggle button (/Btn)
	FieldChoice                        // combo box / list box (/Ch)
)

type HexString

type HexString []byte

HexString is a PDF hexadecimal string.

type ImageSpec

type ImageSpec struct {
	Width, Height    int
	ColorSpace       string // "DeviceRGB", "DeviceGray", "DeviceCMYK"
	BitsPerComponent int
	Filter           string // "DCTDecode" or "FlateDecode"
	Data             []byte // filtered stream bytes
	SMask            []byte // optional 8-bit gray alpha, FlateDecode-compressed
}

ImageSpec describes an image ready to embed as an XObject: its dimensions, color space, and already-filtered stream data (plus an optional alpha SMask).

type Integer

type Integer int64

Integer is a PDF integer.

type LinkAnnotation

type LinkAnnotation struct {
	X0, Y0, X1, Y1 float64
	URI            string
}

LinkAnnotation is a clickable URI link over a rectangle, in page (default user) space — bottom-left origin, x0<x1, y0<y1. It is a page annotation, not a content-stream op, so it is unaffected by the content CTM.

type LiteralString

type LiteralString string

LiteralString is a PDF literal string; the bytes are written verbatim inside parentheses with the required escaping.

type Name

type Name string

Name is a PDF name object (written with a leading slash).

type NoteAnnotation

type NoteAnnotation struct {
	X, Y float64
	Text string
}

NoteAnnotation is a text (sticky-note) annotation anchored at a page-space point (its icon's top-left), carrying popup text. Coordinates are in default user space (bottom-left origin), so it is unaffected by the content CTM.

type Null

type Null struct{}

Null is the PDF null object.

type Object

type Object interface {
	// contains filtered or unexported methods
}

Object is any PDF object that can serialize itself as PDF syntax.

func TextString

func TextString(s string) Object

TextString returns a PDF text string: a literal ASCII string when possible, otherwise a UTF-16BE hex string with a byte-order mark (PDF text string form).

type Options

type Options struct {
	Title    string
	Author   string
	Subject  string
	Keywords string
	Creator  string
	Producer string

	PDFVersion string // "1.3".."1.7"; defaults to "1.4"
	Language   string // catalog /Lang
	PageMode   string // catalog /PageMode, e.g. "UseOutlines"
	PageLayout string // catalog /PageLayout, e.g. "TwoColumnLeft"

	CreationDate time.Time // omitted from /Info when zero
	ModDate      time.Time // omitted from /Info when zero

	// UserPassword and OwnerPassword enable standard-security-handler
	// encryption (RC4 128-bit, V=2/R=3) when either is non-empty. An empty
	// user password with a non-empty owner password yields a file that opens
	// without a password but whose permissions require the owner password to
	// change.
	UserPassword  string
	OwnerPassword string
	// Permissions is the encryption dictionary's /P flags value. Zero means
	// "everything allowed" and is replaced by -4 (0xFFFFFFFC): every flag
	// bit set except bits 1–2, which are reserved and shall be 0 per
	// PDF 32000-1 Table 22. Ignored unless encryption is enabled.
	Permissions int32
	// EncryptAES selects AES-128 (AESV2, /V 4 /R 4) instead of the default
	// RC4-128 handler when encryption is enabled. Ignored without a password.
	EncryptAES bool
	// EncryptAES256 selects AES-256 (AESV3, /V 5 /R 6) — the strongest handler.
	// Takes precedence over EncryptAES. Ignored without a password.
	EncryptAES256 bool
}

Options configure document-level metadata and output determinism.

type Outline

type Outline struct {
	Title    string
	Page     int
	Top      float64
	Children []*Outline
}

Outline is one document-outline (bookmark) entry: a title, the destination page (0-based index into the pages added to the document), the destination Y in PDF space (points from the page bottom), and any nested child entries.

type Real

type Real float64

Real is a PDF real number.

type Reference

type Reference struct {
	Num int
	Gen int
}

Reference is an indirect reference to another object.

type Shading

type Shading struct {
	Radial bool
	Coords []float64
	Stops  []ShadingStop
}

Shading describes an axial (linear) or radial gradient in DeviceRGB, expressed in the current user space — it is painted with the `sh` operator, which honors the current CTM and clip (so it needs no pattern matrix). Coords are [x0 y0 x1 y1] for axial and [cx0 cy0 r0 cx1 cy1 r1] for radial. Compared by pointer identity; reuse the same *Shading per gradient instance.

type ShadingStop

type ShadingStop struct {
	Offset, R, G, B float64
}

ShadingStop is a gradient color stop: Offset in [0,1], RGB components in [0,1].

type Stream

type Stream struct {
	Dict Dict
	Data []byte
}

Stream is a PDF stream object: a dictionary plus raw bytes. Streams must be indirect objects. The /Length entry is filled in automatically at encode time.

func FlateStream

func FlateStream(extra Dict, data []byte) *Stream

FlateStream returns a stream object whose data is zlib/FlateDecode-compressed. extra dictionary entries (if any) are merged in alongside /Filter.

type Writer

type Writer struct {
	Root    Reference // catalog; required
	Info    Reference // document info dict; optional
	Encrypt Reference // encryption dictionary; optional
	ID      [2][]byte // file identifier halves; optional
	Version string    // e.g. "1.4"; defaults to "1.4"
	// contains filtered or unexported fields
}

Writer manages the indirect object table and serializes a complete PDF file (header, body, cross-reference table, trailer). Object numbers are assigned in allocation order, which callers drive deterministically.

func NewWriter

func NewWriter() *Writer

NewWriter returns an empty Writer.

func (*Writer) Add

func (w *Writer) Add(obj Object) Reference

Add appends a new object and returns its reference.

func (*Writer) Alloc

func (w *Writer) Alloc() Reference

Alloc reserves an object number without assigning content.

func (*Writer) Set

func (w *Writer) Set(ref Reference, obj Object)

Set assigns content to a previously allocated reference.

func (*Writer) WriteTo

func (w *Writer) WriteTo(out io.Writer) (int64, error)

WriteTo serializes the document to out. The whole file is assembled in memory so that byte offsets for the cross-reference table are exact.

Directories

Path Synopsis
Package afm parses Adobe Font Metrics for the 14 standard PDF fonts and exposes glyph widths and font metrics used for text measurement.
Package afm parses Adobe Font Metrics for the 14 standard PDF fonts and exposes glyph widths and font metrics used for text measurement.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL