font

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: Apache-2.0 Imports: 19 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package font handles font loading, parsing, metrics, subsetting, and PDF embedding for TrueType, OpenType, and the 14 standard PDF fonts (ISO 32000 §9.6.2.2).

The Face interface abstracts over font formats, providing glyph metrics, character mapping, kerning, and raw font bytes needed for PDF font descriptors (§9.8). Use ParseTTF to parse from bytes or LoadTTF to load from a file path.

For the 14 standard fonts, pre-defined variables (Helvetica, TimesRoman, Courier, etc.) provide Standard values with hardcoded width tables and metrics from the PDF specification (Appendix D). Both Standard and EmbeddedFont implement the TextMeasurer interface for layout-engine integration.

Font subsetting via Subset produces minimal TrueType programs containing only the glyphs used in a document, reducing file size.

Package font handles font loading, parsing, subsetting, and PDF embedding.

It supports the 14 standard PDF fonts (which require no embedding), TrueType/OpenType fonts parsed in-tree (head, hhea, maxp, hmtx, OS/2, name, cmap), and WOFF1 web fonts decoded to TTF. Embedded fonts are subset to include only the glyphs actually used, reducing file size.

Text measurement and kerning are available for both standard and embedded fonts through the TextMeasurer interface and the Kern methods.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnknownFormat indicates that the input data does not match any
	// font format recognized by this package (TTF, OTF, WOFF1). The data
	// may be a different format entirely or simply not a font file.
	ErrUnknownFormat = errors.New("font: unknown font format")

	// ErrTruncated indicates that the input ends before a structure it
	// was in the middle of parsing. The data is shorter than its own
	// declared offsets require.
	ErrTruncated = errors.New("font: data truncated")

	// ErrMissingTable indicates that a table required for the requested
	// operation (typically subsetting) is absent from the font.
	ErrMissingTable = errors.New("font: required table missing")

	// ErrCorruptTable indicates that a table's contents could not be
	// parsed. The table is present but its internal layout is invalid.
	ErrCorruptTable = errors.New("font: corrupt table data")
)

Sentinel errors returned by font parsing and subsetting. Callers can match against these with errors.Is to distinguish failure modes without string matching.

View Source
var (
	Helvetica            = &Standard{name: "Helvetica"}
	HelveticaBold        = &Standard{name: "Helvetica-Bold"}
	HelveticaOblique     = &Standard{name: "Helvetica-Oblique"}
	HelveticaBoldOblique = &Standard{name: "Helvetica-BoldOblique"}

	TimesRoman      = &Standard{name: "Times-Roman"}
	TimesBold       = &Standard{name: "Times-Bold"}
	TimesItalic     = &Standard{name: "Times-Italic"}
	TimesBoldItalic = &Standard{name: "Times-BoldItalic"}

	Courier            = &Standard{name: "Courier"}
	CourierBold        = &Standard{name: "Courier-Bold"}
	CourierOblique     = &Standard{name: "Courier-Oblique"}
	CourierBoldOblique = &Standard{name: "Courier-BoldOblique"}

	Symbol       = &Standard{name: "Symbol", sym: true}
	ZapfDingbats = &Standard{name: "ZapfDingbats", sym: true}
)

The 14 standard PDF fonts.

Functions

func BuildGIDToUnicode

func BuildGIDToUnicode(fontData []byte) map[uint16]rune

BuildGIDToUnicode parses a TrueType/OpenType font and builds a map from glyph ID to Unicode code point by scanning the font's cmap table. This is used as a fallback for CIDFont text extraction when no ToUnicode CMap is provided.

First rune wins if multiple runes map to the same GID — matching the previous sfnt-backed behavior, which scanned the BMP in ascending order.

Returns nil if parsing fails or the cmap yields no entries.

func CanEncodeWinAnsi

func CanEncodeWinAnsi(s string) bool

CanEncodeWinAnsi reports whether all characters in s can be encoded in WinAnsiEncoding without loss. Returns false if any character would be replaced with '?' during encoding.

func CanEncodeWinAnsiRune added in v0.7.0

func CanEncodeWinAnsiRune(r rune) bool

CanEncodeWinAnsiRune reports whether a single rune can be encoded in WinAnsiEncoding. Used by the per-glyph font fallback splitter.

func IsStandardFont

func IsStandardFont(name string) bool

IsStandardFont returns true if name is one of the 14 standard PDF fonts.

func ParseKern added in v0.7.0

func ParseKern(data []byte) map[[2]uint16]int16

ParseKern parses the contents of a TrueType kern table and returns the full map of (leftGID, rightGID) pairs to signed FUnit adjustments from every horizontal, non-cross-stream format-0 subtable. Subtables in unsupported formats, vertical subtables, cross-stream subtables, and minimum/override subtables are ignored. Unknown, short, or malformed data yields an empty map (nil). The returned map never contains zero-valued entries.

Supports both version-0 (Microsoft/OpenType) and version-1 (Apple AAT) kern tables. The two versions use different header and coverage-field layouts; see the Apple TrueType Reference Manual and Microsoft OpenType specification for the exact bit assignments.

func StandardFontBuiltinEncoding added in v0.11.0

func StandardFontBuiltinEncoding(name string) []rune

StandardFontBuiltinEncoding returns the code → Unicode table of the built-in encoding of the named symbolic standard font (Symbol or ZapfDingbats); unused codes map to 0. It returns nil for every other font, whose text is not encoded with a font-specific table. The result is a fresh copy the caller may modify.

Readers use it to decode a symbolic standard font that has no /Encoding entry, or whose /Encoding dictionary has /Differences but no /BaseEncoding (ISO 32000-1 §9.6.6.1).

func StandardFontByteWidths

func StandardFontByteWidths(name string) []int

StandardFontByteWidths returns a 256-element width array for the named standard font, indexed by character code. Each entry is in units of 1/1000 of text space. Returns nil if name is not a standard font.

Codes follow the encoding a standard font is read with when the PDF declares none: WinAnsiEncoding for the Latin fonts, and the built-in encoding for the symbolic fonts Symbol and ZapfDingbats (see StandardFontBuiltinEncoding). Codes without a glyph get the font's default (space) width.

This is designed for readers that need to compute text width from raw content stream bytes without the font's /Widths array (which standard fonts omit from the PDF since viewers are required to know them).

func Subset

func Subset(raw []byte, usedGlyphs map[uint16]rune) ([]byte, error)

Subset produces a minimal TrueType font containing only the glyphs referenced in usedGlyphs. Original glyph IDs are preserved (Option A): unused glyph slots are zeroed out so /CIDToGIDMap /Identity remains valid.

The subset includes tables: head, hhea, maxp, OS/2, name, cmap, post, loca, glyf, hmtx. All other tables are omitted.

Errors returned by this function wrap one of the sentinel errors ErrMissingTable, ErrTruncated, or ErrCorruptTable so callers can match failure modes with errors.Is.

func SubsetCFF added in v0.8.0

func SubsetCFF(cffBytes []byte, usedGlyphs map[uint16]rune) ([]byte, error)

SubsetCFF returns a CID-keyed CFF v1 blob containing only the charstrings referenced in usedGlyphs and the subroutines they transitively reach. Unused charstrings are replaced with a single `endchar` byte (0x0E); unreached global and per-FD local subroutines are replaced with a single `return` byte (0x0B). GID 0 (.notdef) is always retained.

The output preserves source-byte layout for sections that are already minimal: Header, Name INDEX, String INDEX, Charset, and FDSelect are copied verbatim. The Top DICT, FDArray font dicts, and per-FD Private DICTs are reassembled so their offset operands can be rewritten — all such operands use the fixed 5-byte longint encoding (29 + int32 big-endian) so section sizes are independent of the absolute offset values and the assembly can be done in a single forward pass.

Errors wrap one of the package sentinels (ErrTruncated, ErrCorruptTable, ErrUnknownFormat). On any error the caller should fall back to embedding the full font; the subset never partially succeeds.

func WinAnsiDecode

func WinAnsiDecode(s string) string

WinAnsiDecode converts a WinAnsiEncoding byte string back to Unicode.

func WinAnsiEncode

func WinAnsiEncode(s string) string

WinAnsiEncode converts a Unicode string to a byte string using WinAnsiEncoding (Windows-1252). Characters not in the encoding are replaced with a fallback (e.g. '?' or a close equivalent).

Text drawn with a Standard font should go through Standard.Encode, which uses the built-in encoding for Symbol and ZapfDingbats.

Types

type Anchor added in v0.7.0

type Anchor struct {
	X, Y int16
}

Anchor is an (x, y) point in font design units. Anchor Format 2 (indexed anchor point for hinting) and Format 3 (with Device tables) are parsed but their extra fields are discarded.

type BaseRecord added in v0.7.0

type BaseRecord struct {
	Anchors []Anchor
}

BaseRecord is the entry of a BaseArray: one anchor per mark class for a given base glyph. The slice is indexed by mark class; a class with no declared anchor yields a zero Anchor.

type ChainContextSubst added in v0.7.0

type ChainContextSubst struct {
	Backtrack [][]uint16
	Input     [][]uint16
	Lookahead [][]uint16
	Actions   []ChainSubstAction
}

ChainContextSubst is the unified runtime representation of an OpenType LookupType 6 rule. All three subtable formats (simple/class/coverage) are decompressed at parse time into this shape: each element of the Backtrack, Input, and Lookahead slices is a set of acceptable GIDs at that position. The Backtrack slice is stored in reverse order so that Backtrack[0] is the glyph immediately preceding Input[0]. Input[0] is the trigger glyph: the outer apply loop uses it as the dispatch key.

Reference: ISO 14496-22 §6.2 LookupType 6.

type ChainSubstAction added in v0.7.0

type ChainSubstAction struct {
	SequenceIndex   uint16 // zero-based position in the input sequence
	LookupListIndex uint16 // index into the GSUB LookupList
}

ChainSubstAction is one SubstLookupRecord entry inside a chaining contextual substitution rule: at a given position within the matched input sequence, invoke another GSUB lookup.

type CursiveRecord added in v0.8.0

type CursiveRecord struct {
	Entry, Exit       Anchor
	HasEntry, HasExit bool
	LookupFlag        uint16
}

CursiveRecord captures the entry/exit anchors a single glyph contributes to LookupType 3 cursive attachment. Either anchor may be absent (zero offset in the source EntryExitRecord); HasEntry/HasExit disambiguate "absent" from "present at (0,0)".

LookupFlag carries the parent Lookup table's lookupFlag uint16 so downstream consumers can interpret bits the draw path does not yet act on. Currently only the RIGHT_TO_LEFT bit (0x0001) is meaningful for cursive; ISO 14496-22 §5.2 also defines IGNORE_BASE_GLYPHS (0x0002), IGNORE_LIGATURES (0x0004), IGNORE_MARKS (0x0008), USE_MARK_FILTERING_SET (0x0010), and a MarkAttachmentType byte in the upper 8 bits. None of these are consumed yet; they are persisted here so a future fix can read them without re-parsing.

type EmbeddedFont

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

EmbeddedFont tracks which glyphs of a Face have been used in a document so that only those glyphs are embedded in the PDF via subsetting.

Concurrency: EmbeddedFont is not safe for concurrent use. EncodeString mutates an internal map of used glyphs on every call. Use one EmbeddedFont per goroutine, or serialize access externally.

EmbeddedFont holds the PDF objects needed to embed a TrueType font as a CIDFont (Type0 composite font) in a PDF document.

Object tree:

Type0 font dict (/Subtype /Type0)
  ├── /DescendantFonts → [CIDFont dict]
  │     └── /FontDescriptor dict
  │           └── /FontFile2 → compressed font stream
  ├── /ToUnicode → CMap stream
  └── /Encoding /Identity-H

func NewEmbeddedFont

func NewEmbeddedFont(face Face) *EmbeddedFont

NewEmbeddedFont creates an embeddable font from a parsed Face.

func (*EmbeddedFont) BuildObjects

func (ef *EmbeddedFont) BuildObjects(addObject func(core.PdfObject) *core.PdfIndirectReference) *core.PdfDictionary

BuildObjects builds the complete set of PDF objects for this embedded font. The caller is responsible for registering these as indirect objects.

Returns:

  • type0Dict: the top-level Type0 font dictionary (goes in page /Resources /Font)
  • objects: additional objects that must be registered (CIDFont, descriptor, font stream, ToUnicode CMap). The type0Dict references these via indirect references that the caller must wire up.

Because indirect references require object numbers (assigned by the Writer), this method returns a builder function that takes an "add object" callback.

func (*EmbeddedFont) EncodeGIDs added in v0.7.0

func (ef *EmbeddedFont) EncodeGIDs(gids []uint16, originalText string) []byte

EncodeGIDs encodes a glyph ID stream produced by a complex-script shaper (Devanagari and similar) as big-endian uint16 pairs for the Identity-H CIDFont encoding. Each GID in gids is recorded in the used-glyph set using originalText as the ActualText source: the ToUnicode CMap must still round-trip to real codepoints so that copy/paste and accessibility recover the pre-shaping text. When the shaper emits more glyphs than input runes (common for Indic conjuncts) or fewer (ligatures), we associate each GID with the first rune of originalText as a best-effort fallback; ActualText marked-content on the draw path provides the authoritative recovery.

func (*EmbeddedFont) EncodeString

func (ef *EmbeddedFont) EncodeString(s string) []byte

EncodeString converts a Unicode string to glyph IDs encoded as big-endian uint16 pairs (Identity-H encoding). It also records which glyphs are used for subsetting and ToUnicode generation.

func (*EmbeddedFont) Face

func (ef *EmbeddedFont) Face() Face

Face returns the underlying Face.

func (*EmbeddedFont) Kern

func (ef *EmbeddedFont) Kern(left, right rune) float64

Kern returns the kerning value between two runes in PDF text space units (thousandths of a unit of text space). Negative values mean glyphs should be closer together. Returns 0 if no kerning data is available.

func (*EmbeddedFont) MeasureGIDs added in v0.7.0

func (ef *EmbeddedFont) MeasureGIDs(gids []uint16, fontSize float64) float64

MeasureGIDs returns the width of a shaper-produced glyph ID stream in PDF points at the given font size. Unlike MeasureString, this does not walk grapheme clusters — the Indic shaper has already collapsed clusters into the final glyph stream, and every GID in the stream contributes its face advance verbatim. Kerning is not applied because OpenType GPOS mark-positioning (not the kern table) governs Indic cluster spacing, and the draw path handles GPOS separately.

func (*EmbeddedFont) MeasureString

func (ef *EmbeddedFont) MeasureString(text string, fontSize float64) float64

MeasureString implements TextMeasurer for embedded fonts. The returned width is in PDF points and accounts for any kerning pairs the font supplies via its kern table, so wrapping widths agree with the advances that drawWordEmbedded emits via TJ adjustments.

Cluster awareness: the advance is summed over extended grapheme clusters (UAX #29 §3.1.1), not per glyph. Within a cluster the base glyph contributes its full advance. Subsequent codepoints contribute zero unless they are SpacingMark (Devanagari-style vowel signs that take horizontal space); Extend (combining accents such as U+0301) and ZWJ contribute no advance, matching how GPOS mark-attachment positions them as zero-width glyphs over the base. Kerning is applied between cluster boundaries, never between a base and its marks.

func (*EmbeddedFont) MeasureStringPrefixes added in v0.10.0

func (ef *EmbeddedFont) MeasureStringPrefixes(text string, fontSize float64) []float64

MeasureStringPrefixes returns cumulative widths at every rune boundary of text, bit-identical to MeasureString(prefix, fontSize) for each prefix. See Standard.MeasureStringPrefixes for the prefix-stability argument.

func (*EmbeddedFont) NormalLineHeight added in v0.11.0

func (ef *EmbeddedFont) NormalLineHeight(fontSize float64) float64

NormalLineHeight computes CSS `line-height: normal` for this font at fontSize, derived from the font's own vertical metrics (ascent + descent + line-gap, scaled by UnitsPerEm) rather than a flat multiplier. This matches how browsers resolve `normal` — fonts that declare a large line-gap (common for many text faces) get proportionally more leading than fonts that don't.

func (*EmbeddedFont) PrefixFit added in v0.10.0

func (ef *EmbeddedFont) PrefixFit(text string, fontSize, maxWidth float64) (byteLen, runeLen int, width float64)

PrefixFit is the embedded-font counterpart of Standard.PrefixFit: it returns the byte length, rune count, and width of the longest leading run of text that fits maxWidth under the first-overflow rule, scanning only as far as the break point.

func (*EmbeddedFont) ResetGlyphs

func (ef *EmbeddedFont) ResetGlyphs()

ResetGlyphs clears the used-glyph tracker so the font can be reused in a new document without carrying over glyphs from a previous one.

type Face

type Face interface {
	// PostScriptName returns the font's PostScript name (used as /BaseFont).
	PostScriptName() string

	// UnitsPerEm returns the font's design units per em.
	UnitsPerEm() int

	// GlyphIndex returns the glyph ID for a Unicode rune.
	// Returns 0 (the .notdef glyph) if the rune is not in the font.
	GlyphIndex(r rune) uint16

	// GlyphAdvance returns the advance width of a glyph in font design units.
	GlyphAdvance(glyphID uint16) int

	// Ascent returns the typographic ascent in font design units.
	Ascent() int

	// Descent returns the typographic descent in font design units (negative).
	Descent() int

	// BBox returns the font's bounding box in font design units:
	// [xMin, yMin, xMax, yMax].
	BBox() [4]int

	// ItalicAngle returns the italic angle in degrees (0 for upright fonts).
	// Parsed from the post table.
	ItalicAngle() float64

	// CapHeight returns the cap height in font design units.
	// Parsed from the OS/2 table (sCapHeight field).
	// Returns 0 if the OS/2 table is missing or too short.
	CapHeight() int

	// StemV returns the dominant vertical stem width for PDF FontDescriptor.
	// Derived from the OS/2 table usWeightClass.
	// Returns 0 if the OS/2 table is missing.
	StemV() int

	// Kern returns the kerning adjustment between two glyphs in font design units.
	// A negative value means the glyphs should be moved closer together.
	// Returns 0 if no kerning data is available or the pair has no adjustment.
	Kern(left, right uint16) int

	// Flags returns the PDF font flags (ISO 32000 §9.8.2, Table 123).
	Flags() uint32

	// RawData returns the complete, unmodified font file bytes.
	// Used for embedding the full font in the PDF.
	RawData() []byte

	// NumGlyphs returns the total number of glyphs in the font.
	NumGlyphs() int

	// GSUB returns the font's parsed OpenType GSUB substitution tables,
	// or nil when the font has none. Used for Arabic positional shaping
	// and Indic conjunct formation.
	GSUB() *GSUBSubstitutions

	// GIDToUnicode returns a reverse glyph-ID-to-Unicode mapping built
	// from the cmap table, or nil when unavailable. The result is cached
	// after the first call.
	GIDToUnicode() map[uint16]rune

	// GPOS returns the font's parsed OpenType GPOS positioning tables,
	// or nil when the font has no recognized positioning data.
	GPOS() *GPOSAdjustments
}

Face represents a parsed font file and provides metric, encoding, and glyph-indexing operations used when embedding the font in a PDF.

Concurrency: Faces returned by ParseTTF/LoadTTF synchronize their internal lazy caches (table data, GSUB tables, GID-to-Unicode maps), so their methods are safe for concurrent use by multiple goroutines and a single Face may be shared across concurrently-rendered documents. EmbeddedFont, which wraps a Face, tracks per-document glyph usage and remains not safe for concurrent use — do not share one EmbeddedFont across concurrently-rendered documents.

Face is the abstraction over a parsed font file. It provides the data needed to embed a font in a PDF: glyph metrics, character mapping, and the raw font bytes.

The metric path is implemented in-tree (head, hhea, maxp, hmtx, OS/2, name, cmap). GSUB/GPOS/kern/post are parsed lazily by their respective callers from the raw table directory. The interface remains small so a future replacement parser can swap in without breaking callers.

func LoadFont

func LoadFont(path string) (Face, error)

LoadFont reads and parses a font file from disk, auto-detecting the format. Supports TTF, OTF, and WOFF1 fonts.

Errors returned by this function wrap one of the sentinel errors ErrUnknownFormat, ErrTruncated, or ErrCorruptTable so callers can match failure modes with errors.Is.

func LoadFontForLanguage added in v0.8.0

func LoadFontForLanguage(path, lang string) (Face, error)

LoadFontForLanguage reads and parses a font file from disk like LoadFont but, for TrueType Collections, selects the face whose name-table FontFamily best matches the supplied BCP-47 language tag. Empty lang behaves identically to LoadFont — face 0 for TTCs, the single face for standalone TTF/OTF/WOFF.

Useful for paths the caller knows ahead of time will resolve to a pan-CJK TTC (NotoSansCJK-Regular.ttc, msyh.ttc, simsun.ttc) when the document context specifies a target language. See ParseFontForLanguage for the BCP-47 tag matching rules.

func LoadTTF

func LoadTTF(path string) (Face, error)

LoadTTF reads and parses a TrueType font file from disk.

func ParseFont

func ParseFont(data []byte) (Face, error)

ParseFont parses a font from raw bytes, auto-detecting the format. Supports TTF, OTF, WOFF1, and TrueType Collection (TTC) fonts. For collections, the first face is selected — matching the convention used by browsers and font tools for url() references without a `#` fragment.

Programmatic callers who need a non-default face from a TTC (for example, the SC variant of NotoSansCJK rather than the JP variant at face 0) should use ParseFontForLanguage instead.

Errors returned by this function wrap one of the sentinel errors ErrUnknownFormat, ErrTruncated, or ErrCorruptTable so callers can match failure modes with errors.Is.

func ParseFontForLanguage added in v0.8.0

func ParseFontForLanguage(data []byte, lang string) (Face, error)

ParseFontForLanguage parses a font from raw bytes like ParseFont but, for TrueType Collections, picks the face whose name-table FontFamily best matches the given BCP-47 language tag. Empty lang (or any non-TTC input) behaves identically to ParseFont — face 0 for collections, the single face for standalone TTF/OTF/WOFF.

Pan-CJK font collections (NotoSansCJK, Source Han Sans, Hiragino, PingFang, msgothic.ttc, Apple's STHeiti family) ship with separate faces for Japanese, Korean, Simplified Chinese, and Traditional Chinese variants. Their FontFamily names embed regional tokens like "JP", "SC", "TC", "Hans", "Hant", "Japanese", "Korean". This function matches those tokens against the requested language; a match returns the corresponding face, no match falls back to face 0 (so existing behavior is unchanged when the hint is absent or doesn't apply).

Recognised language hints:

  • "zh-CN", "zh-Hans", "zh-SG" — Simplified Chinese (SC / Hans)
  • "zh-TW", "zh-Hant", "zh-HK", "zh-MO" — Traditional Chinese (TC / Hant)
  • "zh" alone — Simplified, matching the IETF/CLDR default-script
  • "ja" — Japanese (JP / Japanese / Jpan)
  • "ko" — Korean (KR / Korean / Kore)

Other languages and Latin TTCs (Helvetica.ttc, Courier.ttc) silently fall back to face 0 because their face names encode weight/style tokens rather than regional ones; callers that need a specific weight should use the existing weight/style API on [sfntFace], not language matching.

Errors returned by this function wrap one of the sentinel errors ErrUnknownFormat, ErrTruncated, or ErrCorruptTable so callers can match failure modes with errors.Is.

func ParseTTF

func ParseTTF(data []byte) (Face, error)

ParseTTF parses a TrueType (.ttf) or OpenType (.otf) font from raw bytes. Returns a Face that can be used for PDF embedding.

The metric tables (head, hhea, maxp, hmtx, OS/2, name, cmap) are decoded eagerly via Folio's in-tree parsers; opaque tables (glyf, loca, post, kern, GSUB, GPOS, CFF) are kept as raw byte slices and decoded on first use by their respective callers.

type Fallback added in v0.8.0

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

Fallback wraps an ordered list of EmbeddedFont pointers used to render mixed-script text without forcing the caller to pre-split runs by font. It is a coverage dispatcher only: PickFace returns the first face whose cmap covers a given rune, falling back to the first face when nothing covers it. Segmentation, shaping, and PDF emission stay in the layers that already own them.

Pointer identity matters. Fallback stores the original *EmbeddedFont pointers verbatim and never wraps or copies them. Subsetting, ToUnicode CMap generation, and the page-level font resource map all dedupe by pointer (one Type0 dict per *EmbeddedFont per document), so passing the same Fallback to many paragraphs aggregates used glyphs on the shared faces instead of inflating the resource count.

Concurrency: Fallback methods are read-only and safe to call from multiple goroutines. Each underlying EmbeddedFont still carries the non-concurrent invariant documented on its type.

func NewFallback added in v0.8.0

func NewFallback(faces ...*EmbeddedFont) *Fallback

NewFallback returns a Fallback over the given faces, in priority order. PickFace tries faces[0] first, then faces[1], and so on. Panics if no faces are provided: a fallback with no faces has no defined behavior and almost certainly indicates a caller error.

func (*Fallback) Faces added in v0.8.0

func (fb *Fallback) Faces() []*EmbeddedFont

Faces returns the underlying face slice in priority order. The returned slice aliases the Fallback's storage; callers must not mutate it.

func (*Fallback) PickFace added in v0.8.0

func (fb *Fallback) PickFace(r rune) *EmbeddedFont

PickFace returns the first face that has a glyph for r. If no face covers r, the first face is returned so the caller still has something to render with (the missing glyph will appear as .notdef tofu, which is the conventional indicator that the document needs a broader fallback chain).

type GPOSAdjustments added in v0.7.0

type GPOSAdjustments struct {
	// Pairs holds LookupType 2 adjustments keyed by (left, right) glyph
	// ID. Only the horizontal XAdvance is stored.
	Pairs map[GPOSFeature]map[[2]uint16]PairAdjustment

	// Marks holds LookupType 4 mark records keyed by mark glyph ID.
	Marks map[GPOSFeature]map[uint16]MarkRecord

	// Bases holds LookupType 4 base records keyed by base glyph ID.
	Bases map[GPOSFeature]map[uint16]BaseRecord

	// MarkMarks holds LookupType 6 top-mark records keyed by the
	// attaching (mark1) glyph ID. Shape mirrors Marks.
	MarkMarks map[GPOSFeature]map[uint16]MarkRecord

	// Mark2Bases holds LookupType 6 underlying-mark records keyed by
	// the receiving (mark2) glyph ID. Shape mirrors Bases: each entry
	// exposes one anchor per mark class of the attaching mark.
	Mark2Bases map[GPOSFeature]map[uint16]BaseRecord

	// Cursives holds LookupType 3 cursive attachment records keyed by
	// glyph ID. The shape is one record per coverage entry; consumers
	// pair them at runtime via CursiveOffset(prev, curr).
	Cursives map[GPOSFeature]map[uint16]CursiveRecord

	// LigatureMarks holds LookupType 5 mark records keyed by mark glyph
	// ID. Shape mirrors Marks but lives in its own slot so a font can
	// carry both LookupType 4 and LookupType 5 marks without aliasing.
	LigatureMarks map[GPOSFeature]map[uint16]MarkRecord

	// LigatureBases holds LookupType 5 ligature base records keyed by
	// ligature glyph ID. Each record exposes a per-component grid of
	// anchors indexed [component][markClass].
	LigatureBases map[GPOSFeature]map[uint16]LigatureRecord
}

GPOSAdjustments holds parsed GPOS positioning data grouped by feature tag. A nil map or nil outer struct means "feature absent".

func ParseGPOS added in v0.7.0

func ParseGPOS(data []byte) *GPOSAdjustments

ParseGPOS reads the GPOS table from raw font bytes and extracts LookupType 2 (Pair Positioning), LookupType 3 (Cursive Attachment), LookupType 4 (Mark-to-Base), LookupType 5 (Mark-to-Ligature), and LookupType 6 (Mark-to-Mark) data for the "kern", "curs", "mark", and "mkmk" features. Extension lookups (LookupType 9) are unwrapped for types 2, 3, 4, 5, and 6.

Script selection follows the same preference order as GSUB: "arab" and "latn" when present, "DFLT" as a fallback.

Returns nil if the font has no GPOS table or no matching data.

Reference: ISO 14496-22 §6.3, OpenType GPOS table.

func (*GPOSAdjustments) CursiveOffset added in v0.8.0

func (g *GPOSAdjustments) CursiveOffset(prevGID, currGID uint16, feature GPOSFeature) (dx, dy int16, ok bool)

CursiveOffset returns the (dx, dy) offset in FUnits needed to move the current glyph so its entry anchor coincides with the previous glyph's exit anchor. The result is prev.Exit - curr.Entry, which is the LTR convention from ISO 14496-22 §6.3 LookupType 3. Returns ok=false when either glyph is absent from the feature, when the previous glyph has no exit anchor declared, or when the current glyph has no entry anchor declared.

Returns the LTR-convention join delta. RTL handling requires reading the parent Lookup's RIGHT_TO_LEFT flag bit (0x0001), which inverts which anchor (entry vs exit) is the "joining" anchor and changes the Y-alignment rule. That flag is not yet parsed by ParseGPOS, so RTL cursive (Arabic and similar) will not render correctly until the lookup flag is consumed. TODO: plumb the lookup flag through the parser and apply it here.

func (*GPOSAdjustments) MarkLigatureOffset added in v0.8.0

func (g *GPOSAdjustments) MarkLigatureOffset(ligGID uint16, componentIdx int, markGID uint16, feature GPOSFeature) (dx, dy int16, ok bool)

MarkLigatureOffset returns the (dx, dy) offset in FUnits needed to move a mark glyph so its anchor coincides with the ligature base's anchor for the requested component and mark class. componentIdx is the zero-based component index (0 = leftmost component for LTR ligatures, in glyph order). Returns ok=false when either glyph is absent from the feature, when componentIdx is out of range for the ligature, or when the requested component has no anchor for the mark's class.

The formula is the direct anchor subtraction from ISO 14496-22 §6.3 LookupType 5: dx = ligAnchor.X - markAnchor.X, dy = ligAnchor.Y - markAnchor.Y.

func (*GPOSAdjustments) MarkMarkOffset added in v0.8.0

func (g *GPOSAdjustments) MarkMarkOffset(mark1GID, mark2GID uint16, feature GPOSFeature) (dx, dy int16, ok bool)

MarkMarkOffset returns the (dx, dy) offset in FUnits that positions the attaching mark1 glyph so its anchor coincides with mark2's anchor for the same class. mark1 is the mark riding on top; mark2 is the already-placed mark playing the "base" role. Returns ok=false when either glyph is absent from the feature's mark1/mark2 arrays, or when mark2 has no anchor declared for mark1's class.

Note: the parameter order is (mark1, mark2) to match the ISO 14496-22 §6.3 spec naming, which is the reverse of MarkOffset(base, mark). Callers porting from MarkOffset must swap the operands.

The formula mirrors LookupType 4: dx = mark2Anchor.X - mark1Anchor.X, dy = mark2Anchor.Y - mark1Anchor.Y.

func (*GPOSAdjustments) MarkOffset added in v0.7.0

func (g *GPOSAdjustments) MarkOffset(baseGID, markGID uint16, feature GPOSFeature) (dx, dy int16, ok bool)

MarkOffset returns the (dx, dy) offset in FUnits needed to move a mark glyph's origin so its anchor coincides with the base glyph's anchor for the same mark class. Returns ok=false when either glyph is absent from the feature's mark/base arrays, or when the base has no anchor declared for the mark's class.

The formula is the direct anchor subtraction from ISO 14496-22 §6.3 LookupType 4: dx = baseAnchor.X - markAnchor.X, dy = baseAnchor.Y - markAnchor.Y.

func (*GPOSAdjustments) PairAdjust added in v0.7.0

func (g *GPOSAdjustments) PairAdjust(left, right uint16) int16

PairAdjust returns the horizontal XAdvance adjustment in FUnits that the GPOS "kern" feature assigns to the pair (left, right), or 0 if the pair is absent. This is the GPOS-table analogue of the legacy kern table lookup.

type GPOSFeature added in v0.7.0

type GPOSFeature string

GPOSFeature identifies an OpenType GPOS feature tag.

const (
	// GPOSKern is the Pair Positioning feature. It is the GPOS equivalent
	// of the legacy TrueType kern table and the preferred source of pair
	// kerning in modern fonts. ISO 14496-22 §6.3 LookupType 2.
	GPOSKern GPOSFeature = "kern"

	// GPOSMark is the Mark-to-Base Positioning feature. It positions a
	// combining mark glyph (e.g. an Arabic harakah or Hebrew niqqud) on
	// an explicit anchor of a base glyph. ISO 14496-22 §6.3 LookupType 4.
	GPOSMark GPOSFeature = "mark"

	// GPOSMkmk is the Mark-to-Mark Positioning feature. It positions a
	// combining mark glyph on an explicit anchor of another combining
	// mark — the mechanism behind stacked diacritics such as Arabic
	// shadda + fatha, Hebrew dagesh + niqqud, and Vietnamese tone marks
	// on already-diacritic vowels. ISO 14496-22 §6.3 LookupType 6.
	GPOSMkmk GPOSFeature = "mkmk"

	// GPOSCurs is the Cursive Attachment feature. It chains glyphs along
	// the script baseline by joining the previous glyph's exit anchor to
	// the next glyph's entry anchor — the mechanism behind Arabic
	// nastaliq-style joining and similar connected scripts.
	// ISO 14496-22 §6.3 LookupType 3.
	GPOSCurs GPOSFeature = "curs"
)

type GSUBFeature added in v0.7.0

type GSUBFeature string

GSUBFeature identifies an OpenType GSUB feature tag.

const (
	GSUBInit GSUBFeature = "init" // initial form
	GSUBMedi GSUBFeature = "medi" // medial form
	GSUBFina GSUBFeature = "fina" // final form
	GSUBIsol GSUBFeature = "isol" // isolated form
	GSUBLiga GSUBFeature = "liga" // standard ligatures
	GSUBRlig GSUBFeature = "rlig" // required ligatures
	GSUBClig GSUBFeature = "clig" // contextual ligatures
	GSUBCalt GSUBFeature = "calt" // contextual alternates

	// Indic shaping features applied during phase 3 of the OpenType Indic
	// shaping engine. The ordering matches the Microsoft "Creating and
	// supporting OpenType fonts for the Indic scripts" specification so
	// downstream shapers can drive their apply loop from this list.
	GSUBNukt GSUBFeature = "nukt" // nukta forms
	GSUBAkhn GSUBFeature = "akhn" // akhand required ligatures (KSSA, JNYA)
	GSUBRphf GSUBFeature = "rphf" // reph form (initial ra + halant)
	GSUBRkrf GSUBFeature = "rkrf" // rakar form (consonant + halant + ra)
	GSUBBlwf GSUBFeature = "blwf" // below-base form
	GSUBHalf GSUBFeature = "half" // half form (pre-base consonants)
	GSUBPstf GSUBFeature = "pstf" // post-base form
	GSUBVatu GSUBFeature = "vatu" // vattu variants
	GSUBCjct GSUBFeature = "cjct" // conjunct form

	// Indic phase-5 positional / presentational features.
	GSUBPres GSUBFeature = "pres" // pre-base substitutions
	GSUBAbvs GSUBFeature = "abvs" // above-base substitutions
	GSUBBlws GSUBFeature = "blws" // below-base substitutions
	GSUBPsts GSUBFeature = "psts" // post-base substitutions
	GSUBHaln GSUBFeature = "haln" // halant forms
)

type GSUBSubstitutions added in v0.7.0

type GSUBSubstitutions struct {
	Single       map[GSUBFeature]map[uint16]uint16
	Ligature     map[GSUBFeature]map[uint16][]LigatureSubst
	ChainContext map[GSUBFeature]map[uint16][]ChainContextSubst
	// contains filtered or unexported fields
}

GSUBSubstitutions holds parsed GSUB lookups grouped by feature tag.

Single holds LookupType 1 substitutions: a per-feature map from source glyph ID to replacement glyph ID.

Ligature holds LookupType 4 substitutions: a per-feature map keyed by the first component glyph ID to a slice of candidate ligatures sharing that prefix. Slices are ordered so that longest matches appear first, which matches the OpenType greedy matching rule.

ChainContext holds LookupType 6 chaining contextual substitutions: a per-feature map keyed by the trigger glyph (Input[0]) to the set of rules that may fire when that glyph is seen.

func ParseGSUB added in v0.7.0

func ParseGSUB(data []byte) *GSUBSubstitutions

ParseGSUB reads the GSUB table from raw TrueType/OpenType font bytes and extracts Single (LookupType 1), Ligature (LookupType 4), and Chain Context (LookupType 6) substitutions for the features needed by the layout engine's shapers.

Script selection: "arab", "latn", "deva", "dev2", and "DFLT". The Devanagari "deva" / "dev2" tags feed the Indic shaper's phase-3 and phase-5 feature dispatch; see the Microsoft "Creating and supporting OpenType fonts for the Indic scripts" specification. Extension lookups (LookupType 7) are unwrapped transparently.

Returns nil if the font has no GSUB table or no matching features.

Reference: ISO 14496-22 §6.2, OpenType GSUB table.

func (*GSUBSubstitutions) ApplyChainContext added in v0.7.0

func (g *GSUBSubstitutions) ApplyChainContext(gids []uint16, feature GSUBFeature) []uint16

ApplyChainContext walks gids left-to-right and applies chaining contextual substitution rules for the given feature. At each position the trigger GID is used as a map key into the feature's rule table; each candidate rule is tested for backtrack, input, and lookahead matches and, on success, its SubstLookupRecord actions are dispatched.

Action dispatch supports LookupType 1 (Single), LookupType 4 (Ligature), and recursive LookupType 6 (ChainContext) targets. LookupType 7 (Extension) wrappers are transparently unwrapped at parse time. Recursion depth is bounded by maxChainDepth to defend against pathological self-referential rule sets.

Reference: ISO 14496-22 §6.2 LookupType 6.

func (*GSUBSubstitutions) ApplyLigature added in v0.7.0

func (g *GSUBSubstitutions) ApplyLigature(gids []uint16, feature GSUBFeature) []uint16

ApplyLigature scans gids left-to-right and replaces the longest matching ligature sequence with the ligature glyph. Greedy longest-match per ISO 14496-22 §6.2. Returns a new slice; the input is not modified.

type LigatureRecord added in v0.8.0

type LigatureRecord struct {
	Components [][]Anchor
	Present    [][]bool
}

LigatureRecord captures the per-component anchors a ligature base glyph exposes for LookupType 5 (Mark-to-Ligature). Components is indexed first by component index (0 = leftmost component for LTR ligatures, in glyph order) and then by mark class.

Present is a parallel grid that disambiguates "no anchor declared" (the source ligatureAnchorOffset was 0) from "anchor declared at (0, 0)". Consumers must check Present[component][markClass] before trusting the anchor value.

type LigatureSubst added in v0.7.0

type LigatureSubst struct {
	Components  []uint16 // component GIDs after the first (may be empty)
	LigatureGID uint16
}

LigatureSubst describes a single ligature substitution: a sequence of component glyph IDs (after the first) that, together with the first component used as the lookup key, are replaced by LigatureGID.

type MarkRecord added in v0.7.0

type MarkRecord struct {
	Class  uint16
	Anchor Anchor
}

MarkRecord is the entry of a MarkArray: the mark class the mark belongs to plus its attachment anchor.

type PairAdjustment added in v0.7.0

type PairAdjustment struct {
	XAdvance int16
}

PairAdjustment holds the XAdvance delta to apply to the first glyph of a kerning pair, expressed in font design units (FUnits). Only the horizontal advance is captured: the initial GPOS iteration ignores XPlacement, YPlacement, YAdvance, and any Device tables.

type Standard

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

Standard represents one of the 14 standard PDF fonts that every conforming viewer must support (ISO 32000 §9.6.2.2). These fonts require no embedding — only a reference by name.

func StandardFonts

func StandardFonts() []*Standard

StandardFonts returns all 14 standard fonts.

func (*Standard) Ascent added in v0.6.0

func (f *Standard) Ascent(fontSize float64) float64

Ascent returns the typographic ascent for the standard font, scaled to the given font size in points. Values are from the PDF spec (Appendix D).

func (*Standard) CanEncode added in v0.11.0

func (f *Standard) CanEncode(s string) bool

CanEncode reports whether every character in s survives Standard.Encode without substitution. It is the font-aware counterpart of CanEncodeWinAnsi, used to decide when text needs a fallback font.

func (*Standard) CanEncodeRune added in v0.11.0

func (f *Standard) CanEncodeRune(r rune) bool

CanEncodeRune reports whether r survives Standard.Encode without substitution. Used by the per-glyph font fallback splitter.

func (*Standard) Descent added in v0.6.0

func (f *Standard) Descent(fontSize float64) float64

Descent returns the typographic descent for the standard font, scaled to the given font size in points. The value is positive (distance below baseline).

func (*Standard) Dict

func (f *Standard) Dict() *core.PdfDictionary

Dict returns the PDF font dictionary for this standard font.

<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>

func (*Standard) Encode added in v0.11.0

func (f *Standard) Encode(s string) string

Encode converts a Unicode string to the byte string a content stream shows with this font. Symbol and ZapfDingbats use their built-in encodings, so "α" becomes 0x61 in Symbol and "✔" becomes 0x34 in ZapfDingbats; a raw built-in code is passed through unchanged (see encodeRune); any other character the font has no glyph for becomes '?' in Symbol and a space in ZapfDingbats (which has no question mark). Every other standard font uses WinAnsiEncode.

func (*Standard) Kern

func (f *Standard) Kern(left, right rune) float64

Kern returns the kerning adjustment between two characters in thousandths of a unit of text space. Standard PDF fonts have limited kerning data; this returns common kern pairs for Helvetica and Times families. Negative values mean the glyphs should be closer together.

func (*Standard) MeasureString

func (f *Standard) MeasureString(text string, fontSize float64) float64

MeasureString implements TextMeasurer for standard fonts. The returned width is in PDF points and accounts for any kerning pairs the font supplies via Kern(), so wrapping widths agree with the advances that drawWordStandard emits via TJ adjustments.

Cluster awareness: the advance is summed over extended grapheme clusters (UAX #29 §3.1.1), not per rune. Within a cluster the base rune contributes its full advance. Subsequent runes contribute zero unless they are SpacingMark (Devanagari-style vowel signs that take horizontal space); Extend (combining accents such as U+0301) and ZWJ contribute no advance, matching how they draw at zero offset on top of the base glyph. Kerning is applied between cluster boundaries, never between a base and its marks.

Uses the hardcoded width tables from the PDF spec (Appendix D) and the AFM-derived kern pairs in standardKernPairs.

func (*Standard) MeasureStringPrefixes added in v0.10.0

func (f *Standard) MeasureStringPrefixes(text string, fontSize float64) []float64

MeasureStringPrefixes returns cumulative widths at every rune boundary of text: element i is the width of the prefix holding the first i runes, bit-identical to MeasureString(prefix, fontSize) for that prefix. One walk computes all len(runes)+1 entries. Grapheme segmentation is prefix-stable, so recording the running total at each rune boundary reproduces the exact additions, in the same order, that an independent prefix measurement performs.

func (*Standard) Name

func (f *Standard) Name() string

Name returns the PDF BaseFont name.

func (*Standard) PrefixFit added in v0.10.0

func (f *Standard) PrefixFit(text string, fontSize, maxWidth float64) (byteLen, runeLen int, width float64)

PrefixFit scans text accumulating cumulative rune-boundary widths (each bit-identical to MeasureString of that prefix) and returns the byte length, rune count, and width of the longest leading run that fits maxWidth under the first-overflow rule used by word chunking: runes are added while the width including the next rune stays within maxWidth, always keeping at least one rune. The scan stops at the first overflow, so it is O(fit length), not O(len(text)).

type TextMeasurer

type TextMeasurer interface {
	// MeasureString returns the width of the given text in PDF points
	// at the specified font size.
	MeasureString(text string, fontSize float64) float64
}

TextMeasurer measures the width of text for layout purposes.

Jump to

Keyboard shortcuts

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