font

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 10 Imported by: 1 module, 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 reads font dictionaries and answers the two questions text extraction asks of a font: what does this character code mean, and how far does it advance the text position (ISO 32000-2 §9.5 through §9.7).

Those two questions are why this package exists as a unit. They are usually treated separately — a decoder here, a metrics table there — and separating them is how extractors end up with correct characters in the wrong order, or with the 4,069-character "word" that a single dropped advance produces. Both answers come from the same dictionary and both must agree about which code is being discussed, so both live behind one Font.

A Font is read once per font dictionary and used for every glyph on every page that references it, so the expensive work — parsing a /ToUnicode CMap, walking a /W array, applying /Differences — happens in Load and never again.

This package resolves codes to text and widths. It does not position glyphs: composing the text matrix and inferring inter-word spaces from the gap between advances belongs to extract, because those depend on state this package cannot see. What this package guarantees is that the advance it reports is the one the font actually declares, which is the input that decision needs.

Index

Constants

This section is empty.

Variables

View Source
var ErrGlyphBudget = errors.New("font: glyph outline budget exhausted")

ErrGlyphBudget reports that a charstring or TrueType glyph ran past the work budget its caller gave.

Exported because the caller owns the budget and so owns the refusal: a renderer bounds a page's total glyph-building work, across both formats, and needs to tell that apart from a glyph that is malformed. The message names neither format, because the caller's budget is one number shared between them.

Functions

func IsStandard

func IsStandard(fontName string) bool

IsStandard reports whether a font name is one of the standard 14 this package carries metrics for, which is what decides whether a font with no /Widths is still usable.

func StandardWidth

func StandardWidth(fontName, glyph string) (int, bool)

StandardWidth returns the advance of a glyph in one of the standard 14 fonts.

The font name is matched after alias resolution and after any subset prefix is stripped, so "ABCDEF+Arial,Bold" resolves. Reporting false rather than a plausible default is deliberate: the caller falls back to the font descriptor's /MissingWidth, and inventing a width here would silently misplace text.

Types

type CFF added in v1.0.0

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

A CFF font program — what /FontFile3 holds for /Type1C and /CIDFontType0C — parsed far enough to hand out glyph outlines.

What this parses

The Compact Font Format of Adobe Technical Note #5176: the header, the first font of the Name INDEX and its Top DICT, the String and Global Subr INDEXes, the charset, the built-in encoding, the Private DICT's local subroutines, and — for a CID-keyed font — the FDArray and FDSelect that give each glyph its own Private DICT and FontMatrix. The charstrings themselves are Type 2 (Technical Note #5177) and are interpreted in charstring.go.

What it refuses, and why at parse time

Every refusal is a place where drawing would need a guess. A font that names SyntheticBase borrows its glyphs from another font the file does not carry; CharstringType 1 is a different interpreter; CFF2 and an OpenType wrapper are different containers; and the predefined Expert charset and encoding are tables no font in the corpus uses and this package does not hold. Refusing them here, in one place, means a reader of this file sees the whole unsupported set at once and a caller gets the reason before it has drawn anything.

Which choices follow FreeType

pdfium draws CFF through FreeType, so where the specification leaves a malformed table's meaning open, the reading here is FreeType's (cffload.c): a charset range that would run past SID 65535 is trimmed rather than rejected, an encoding code assigned twice keeps its last GID, and a name or CID that more than one glyph claims resolves to the lowest GID. A reader that chose differently would draw a different glyph than the yardstick for the same bytes, which is a comparison failure that looks like a rasterizer bug.

func ParseCFF added in v1.0.0

func ParseCFF(data []byte) (*CFF, error)

ParseCFF reads a bare CFF program far enough to yield outlines.

func (*CFF) CIDKeyed added in v1.0.0

func (c *CFF) CIDKeyed() bool

CIDKeyed reports whether the program's charset holds CIDs rather than glyph names.

func (*CFF) GIDForCID added in v1.0.0

func (c *CFF) GIDForCID(cid uint32) (uint16, bool)

GIDForCID maps a CID to a glyph: through the inverted charset for a CID-keyed font, lowest GID winning, and as the glyph index itself below the glyph count for one that is not — which is FreeType's reading of a CIDFontType0 font whose program was not built CID-keyed.

func (*CFF) GIDForCode added in v1.0.0

func (c *CFF) GIDForCode(code byte) (uint16, bool)

GIDForCode maps a code through the built-in encoding. A code the encoding leaves unassigned answers false rather than GID 0, which is .notdef and not an answer.

func (*CFF) GIDForName added in v1.0.0

func (c *CFF) GIDForName(name string) (uint16, bool)

GIDForName maps a glyph name to the lowest GID the charset gives it, as FreeType's cff_get_name_index does. A CID-keyed font has no names and answers false.

func (*CFF) NumGlyphs added in v1.0.0

func (c *CFF) NumGlyphs() int

NumGlyphs is the glyph count of the CharStrings INDEX.

func (*CFF) Outline added in v1.0.0

func (c *CFF) Outline(gid uint16, budget int) (Outline, int, error)

Outline returns a glyph's contours in 1/1000 em, and how many charstring operations it took.

budget bounds those operations, operands and operators both. A charstring cannot loop, but subroutines nest ten deep and each can call others many times, so the work one glyph asks for is exponential in its size; past the budget the answer is ErrGlyphBudget. An empty outline — a space — is nil with no error.

type FaceRequest added in v1.0.0

type FaceRequest struct {
	// Name is /BaseFont with any subset prefix stripped.
	Name string

	// Style is what SubstituteStyle concluded from the name and the descriptor.
	Style Style

	// Why is the reason a substitute is needed, for a caller that wants to log or decline by
	// case: a standard-14 font with no descriptor at all is a different situation from a
	// descriptor that declares a face and embeds no program.
	Why string
}

FaceRequest describes a font that needs a substitute.

Both the name and the inferred style, because a caller may be able to do better than the style: one that happens to hold the actual Arial should use it for "ArialMT" rather than a metric-compatible stand-in, and only the name can tell it so. A caller with no opinion about names reads Style alone.

type FaceSource added in v1.0.0

type FaceSource interface {
	// Face returns a program for the request, or false to decline.
	//
	// Declining is a legitimate answer and not an error: a source carrying no symbol face should
	// decline a request for one rather than return a text face, because substituting Latin letters
	// for mathematics draws a page that looks like text and says something else.
	Face(FaceRequest) (*TrueType, bool)
}

FaceSource supplies a font program to stand in for one a document did not embed.

Why this is an interface, and why it is in this package

Which face substitutes for Helvetica is policy, not parsing. A proofing tool wants metric compatibility with the original; an archival pipeline may be required to use a face it has licensed; a caller rendering for search does not care at all. A parser that chose for everyone would be making a typographic decision on evidence it does not have — and it would put the bytes of several faces into every binary that imports it, including the ones that never render.

It lives here rather than in the renderer because a substitute font is font data, and because the implementation has to be able to depend on this package without depending on a rasterizer: when the interface was in render/native, the one implementation in this repo imported it and no test in render/native could import the implementation back.

type Family added in v1.0.0

type Family uint8

Family is the broad shape of a typeface, which is as much as a substitute can honour.

Three and not more, because three is what the evidence supports. A font with no embedded program offers a name, a descriptor and a width array; from those, "sans or serif or monospaced" is answerable and "Garamond rather than Caslon" is not. A fourth value for script or display faces would be a category nothing could be assigned to with confidence.

const (
	// FamilySans is a face without serifs: Helvetica, Arial, Verdana.
	FamilySans Family = iota
	// FamilySerif is a face with them: Times, Georgia, Garamond.
	FamilySerif
	// FamilyMono is a fixed-pitch face: Courier, Consolas.
	FamilyMono
	// FamilySymbol is a face whose codes are not characters — Symbol, ZapfDingbats, a dingbat
	// or icon font. It is its own family because no text face can stand in for one: substituting
	// Liberation Sans for Symbol draws Latin letters where the page shows mathematics, which is
	// a page that looks like text and says something else entirely.
	FamilySymbol
)

func (Family) String added in v1.0.0

func (f Family) String() string

type Font

type Font struct {
	// Kind decides how Decode splits bytes into codes.
	Kind Kind

	// BaseFont is the /BaseFont name, with any subset prefix intact. Extraction
	// reports it, and the standard-14 metrics match against it.
	BaseFont string

	// Subtype is the font dictionary's /Subtype.
	Subtype string

	// Vertical reports a vertical writing mode, from a CMap name ending in -V.
	// Advances then apply to the y axis, which is the difference between reading
	// a vertical Japanese document and stacking every glyph at one point.
	Vertical bool
	// contains filtered or unexported fields
}

Font is a loaded font dictionary, ready to decode codes and report advances.

Its fields are read-only after Load. Nothing here holds a Store, so a Font outlives the document handle it was read from and is safe to share across goroutines.

func Load

func Load(s objects.Store, d objects.Dict) *Font

Load reads a font dictionary.

It never fails on a defective dictionary. A font with no /Widths, no /ToUnicode, and an unrecognized /Encoding still yields a usable Font: codes decode to nothing and advances fall back to the default, which loses text but keeps the rest of the page. Returning an error instead would abandon a whole document over one bad font, and defective font dictionaries are common in exactly the files that most need extracting.

func (*Font) BaseEncoding added in v1.0.0

func (f *Font) BaseEncoding() string

BaseEncoding returns the base encoding a simple font names, as written, or "" when it names none.

func (*Font) Bold

func (f *Font) Bold() bool

Bold, Italic, Monospaced, and Serif report the font's typographic traits.

func (*Font) CMap

func (f *Font) CMap() *cmap.CMap

CMap returns the font's encoding CMap, or nil for a simple font. Exposed so a caller can ask how a string splits without decoding it.

func (*Font) Decode

func (f *Font) Decode(s []byte) []Glyph

Decode splits a PDF string into glyphs.

Splitting and decoding happen together because they cannot be separated correctly: how many bytes the next code occupies is a question only the font's CMap can answer, and a caller that splits first has already had to guess. This is the specific mistake behind extracted text that has plausible characters in an implausible order.

func (*Font) GIDForCID added in v1.0.0

func (f *Font) GIDForCID(cid uint32) (uint16, bool)

GIDForCID maps a composite font's CID to a glyph index.

/CIDToGIDMap is a name or a stream (§9.7.4.2). Identity — the only defined name, and what all 67 CIDFontType2 fonts in this repo's corpus use — makes the two equal. A stream is a big-endian array of glyph indices, and a CID past its end has no glyph rather than glyph 0: glyph 0 is a real glyph, the one a font draws for "not found", so returning it would silently put a box on the page where the font said nothing.

func (*Font) GlyphName

func (f *Font) GlyphName(code byte) string

GlyphName returns the glyph name a simple font's code maps to, or "" for a composite font or an unmapped code. Diagnostic: it is what `probe` reports and what makes an encoding problem legible.

func (*Font) HasDifferences added in v1.0.0

func (f *Font) HasDifferences() bool

HasDifferences reports whether a simple font's /Encoding dictionary has a /Differences array, whether or not it assigns any code.

Assignment used to be the test, and it is wrong for §9.6.5.4's TrueType route (C21): CPDF_SimpleFont::LoadDifferences (cpdf_simplefont.cpp) resizes its char_names_ table to 256 for any /Differences array before reading it, and cpdf_truetypefont.cpp's by-name test reads char_names_.empty() — so an array that assigns nothing still moves pdfium off the by-code route this package would otherwise take. ttRoute reads this method to refuse that font instead of drawing it by the wrong route.

func (*Font) HasEncoding added in v1.0.0

func (f *Font) HasEncoding() bool

HasEncoding reports whether a simple font's /Encoding is a name or a dictionary.

func (*Font) HasToUnicode

func (f *Font) HasToUnicode() bool

HasToUnicode reports whether the font carries a /ToUnicode CMap. This is the signal that decides whether a page's text is recoverable at all, which is what routes a page to OCR.

func (*Font) Irregular added in v1.0.0

func (f *Font) Irregular() string

Irregular names the first entry of a simple font's dictionaries that pdfium reads under a looser type or a wider range than this package does, or "" when there is none.

Load stays lenient regardless: this only records the entry, and never fails Load over it. It exists because render/native's survey has to refuse a page wherever the two readers would select a different glyph, and a value pdfium reads that this package's stricter getters silently drop is exactly that case — the getters answer "what did the font state", not "did this and pdfium state the same thing".

func (*Font) Italic

func (f *Font) Italic() bool

func (*Font) Monospaced

func (f *Font) Monospaced() bool

func (*Font) Name

func (f *Font) Name() string

Name returns the /BaseFont name with any subset prefix stripped.

The prefix is stripped because it identifies the subset, not the typeface: the same font subset twice in one document gets two different prefixes, and a consumer grouping runs by font name would treat them as unrelated and break a paragraph at every subset boundary. BaseFont keeps the prefix for callers that want the name exactly as written.

func (*Font) Nonsymbolic added in v1.0.0

func (f *Font) Nonsymbolic() bool

Nonsymbolic reports a simple font's nonsymbolic flag: bit 6 of the descriptor's /Flags, set when /Flags is absent, or for a font with no descriptor, whether it is not Symbol or ZapfDingbats.

func (*Font) Serif added in v1.0.0

func (f *Font) Serif() bool

func (*Font) SpaceWidth

func (f *Font) SpaceWidth() float64

SpaceWidth returns the advance of the space glyph, or 0 when the font has none.

Exposed because it is the denominator of the space-inference threshold, which is what turns glyph positions back into words. A consumer comparing gaps in absolute units gets a threshold that is wrong at every font size, so the comparison has to be relative to this.

func (*Font) StatedGlyphName added in v1.0.0

func (f *Font) StatedGlyphName(code byte) string

StatedGlyphName returns the glyph name a simple font's encoding states for code: the one /Differences assigns, or the one in the base encoding the font names when this package carries that table.

It differs from GlyphName where the name is this package's inference rather than the font's statement — the StandardEncoding assumed for a font that names no base, most of all — and is empty there. Text extraction can live with that guess; selecting a glyph by it draws the wrong glyph wherever the program's built-in encoding differs, so a renderer has to know which it has.

func (*Font) SubstituteStyle added in v1.0.0

func (f *Font) SubstituteStyle() Style

SubstituteStyle is the style a face standing in for this font should have.

What the evidence is, and what it is not

This is typeface inference and not character inference, and the distinction matters because the two have opposite inputs. A font needing substitution has *no outlines at all* — the program is absent, which is the whole reason a substitute is needed — so there is nothing to measure the shape of. What there is: the /BaseFont name, the descriptor's /Flags, /StemV, /FontWeight and /ItalicAngle, and the /Widths array. Load has already reduced those to the bold, italic, mono and serif traits, weighing name against descriptor where they disagree, which is why this function reads traits rather than dictionaries.

Why there is no confidence score

Every branch below is a rule over stated evidence, so the answer is determined rather than estimated. A probability attached to a determined answer reads as humility and acts as noise: a caller cannot do anything different with 0.9 than with 1.0 here, because there is no second candidate to weigh it against. Confidence belongs on an inference that ranks candidates, which is character inference from an outline — a different problem, on a different population, and not this one.

func (*Font) Symbolic added in v1.0.0

func (f *Font) Symbolic() bool

Symbolic reports a simple font's symbolic flag: bit 3 of the descriptor's /Flags, or for a font with no descriptor, whether it is Symbol or ZapfDingbats.

func (*Font) Text

func (f *Font) Text(code uint32) string

Text returns what a character code means, without measuring it. Decode is the normal entry point; this exists for callers that already know the code.

func (*Font) TextSource added in v1.0.0

func (f *Font) TextSource(code uint32) (string, Source)

TextSource returns what a code means and how that was determined.

The pair rather than a second traversal, because the source falls out of the same lookup: Text is this with the evidence dropped, and a caller that wants both should not decode twice to get them.

func (*Font) Width

func (f *Font) Width(code, cid uint32) float64

Width returns a glyph's horizontal advance in glyph space units.

Both the code and the CID are taken because the two font kinds index their metrics differently — a simple font by code offset from /FirstChar, a composite font by CID — and a caller holding a Glyph has both.

type Glyph

type Glyph struct {
	// Code is the character code as written, big-endian.
	Code uint32

	// Bytes is how many bytes Code occupied in the string. Always 1 for a simple
	// font; one to four for a composite one.
	Bytes int

	// CID is the glyph identifier the code maps to, for a composite font. Equal to
	// Code for a simple font, where the two are the same thing.
	CID uint32

	// Text is what the glyph means, which may be several characters for a ligature
	// or empty when the font gives no way to tell. Empty is a real answer and not
	// an error: a symbolic font with no /ToUnicode has genuinely undecodable codes.
	// What a consumer writes for one is its own policy, and the extractor writes
	// doc.Unmapped, which the Markdown sink tags [err] (ADR 0042).
	Text string

	// Source says how Text was arrived at, which Text itself cannot.
	//
	// It answers a question nothing could answer before: how much of a document's text is *known*
	// rather than assumed. A page whose characters all came from /ToUnicode and one where half came
	// from a base encoding guessed off the symbolic flag are equally plausible on screen and not
	// equally trustworthy, and a consumer auditing extraction quality has no other way to tell them
	// apart. ADR 0018 records why this is here before any inference is: an inference route would
	// add a value rather than change what an existing one means.
	//
	// Empty Text always has SourceNone, and a non-empty Text never does.
	Source Source

	// Width is the horizontal advance in 1/1000 em, whatever the font's kind. The
	// caller scales it by font size and any horizontal scaling.
	//
	// 1/1000 is the glyph space of every font kind except Type 3, whose glyph space
	// is whatever its /FontMatrix says (§9.6.4). Those advances are converted into
	// these units when the font loads, so a caller never asks what kind it holds —
	// and must not apply a /FontMatrix again.
	Width float64
}

Glyph is one character code decoded: what it means, how far it advances, and what it was written as.

All four fields travel together because the caller needs them together. A consumer inferring inter-word spaces compares Width against the gap it measures in device space, and one that cannot also see Bytes cannot tell a two-byte code 32 (which /Tw must not affect) from a single-byte space (which it must). Keeping them in one struct is what stops that rule from being lost.

type Kind

type Kind int

Kind distinguishes the two ways a font addresses glyphs, which is the single most consequential fact about it: a simple font takes one byte per glyph, a composite font takes a variable number decided by its CMap. Assuming the wrong one does not produce an error, it produces a plausible-looking stream of wrong glyphs.

const (
	// Simple is a Type1, TrueType, Type3, or MMType1 font: single-byte codes
	// resolved through an encoding.
	Simple Kind = iota

	// Composite is a Type0 font: codes of one to four bytes resolved through a
	// CMap to CIDs.
	Composite
)

type Outline added in v1.0.0

type Outline []Seg

Outline is a glyph's contours, in 1/1000 em with y up.

The same units as Glyph.Width, and for the same reason its comment gives: a caller must not have to ask what kind of font it holds. TrueType's own units are whatever `head` says — usually 1000 or 2048 — and converting here rather than exporting unitsPerEm means a consumer cannot forget to, which is a silent scale error of a factor of two on half the fonts in the world.

type Point added in v1.0.0

type Point struct{ X, Y float64 }

Point is a position in glyph space.

type Seg added in v1.0.0

type Seg struct {
	Op SegOp
	P  [3]Point
}

Seg is one segment of an outline.

type SegOp added in v1.0.0

type SegOp uint8

SegOp is what a segment of an outline does.

const (
	// SegMove starts a contour at P[0].
	SegMove SegOp = iota
	// SegLine draws to P[0].
	SegLine
	// SegQuad draws a quadratic Bézier with control P[0] to P[1]. TrueType's native curve.
	SegQuad
	// SegCubic draws a cubic Bézier with controls P[0], P[1] to P[2]. Type 1 and CFF's native
	// curve, declared here so one outline type serves both and a rasterizer implements each
	// curve once.
	SegCubic
	// SegClose closes the current contour.
	SegClose
)

type Source added in v1.0.0

type Source uint8

Source is how a glyph's text was determined.

Ordered by how much the file actually stated, most explicit first, so that a consumer comparing two glyphs can rank them: a /ToUnicode entry was written for this document, where an encoding is a table chosen by name and applies to whatever the font's codes happen to be.

const (
	// SourceNone means the font gave no way to tell, and Text is empty. A real answer, not an
	// error: a symbolic font with no /ToUnicode has genuinely undecodable codes.
	SourceNone Source = iota
	// SourceToUnicode means a /ToUnicode CMap mapped the code. The font's own statement about
	// what its codes mean, written for this document.
	SourceToUnicode
	// SourceEncoding means a simple font's encoding table mapped the code — a named base encoding,
	// possibly overlaid with /Differences. An inference from a name rather than a statement about
	// this font, which is why it ranks below /ToUnicode and why the two are worth telling apart.
	SourceEncoding
)

func (Source) String added in v1.0.0

func (s Source) String() string

type Style added in v1.0.0

type Style struct {
	Family       Family
	Bold, Italic bool
}

Style is the canonical face to substitute for a font with no embedded program.

The split of responsibility this type exists to draw: *this package* decides the style, from the font's own evidence, deterministically. A *caller* decides which actual face a style maps to, because that is policy — a proofing tool wants metric compatibility with Arial, an archival pipeline may want a face it has licensed, and neither answer belongs in a parser.

func (Style) String added in v1.0.0

func (s Style) String() string

type TrueType added in v1.0.0

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

A TrueType font program, parsed far enough to hand out glyph outlines.

Why this is here and not in the rasterizer

A glyph program is font data, and `font` is the package that reads font data. The rasterizer asks for an outline the way `extract` asks for a width, and neither knows what a `loca` table is. The alternative — a rasterizer that parses fonts — would put the same tables in two packages the first time anything else needed a glyph.

Why the bytes are a parameter rather than something Font holds

Font is loaded once per font dictionary and cached for a document's life, by every consumer: `extract` holds one per reference for a thousand pages. A font *program* is tens of kilobytes subsetted and megabytes when it is not, and extraction never looks at one. Holding it on Font would make every text run pay for every outline nobody reads, and holding a Store on Font to load it later would tie a cached font's lifetime to a file handle. So the caller reads /FontFile2 when it wants outlines and parses it here, and caches the result where it knows how long it needs it.

What this parses, and what it refuses

`head` for unitsPerEm and the `loca` format, `maxp` for the glyph count, `loca` and `glyf` for the outlines, `cmap` for the character lookups a simple font needs. Not `CFF ` — a FontFile3 program has cubic charstrings and its own interpreter, which is cff.go and charstring.go rather than a variation on this one. Not hinting: an outline is scaled and filled, which is what a 200-dpi page wants and what every renderer does above about 12 pixels per em.

func ParseTrueType added in v1.0.0

func ParseTrueType(data []byte) (*TrueType, error)

ParseTrueType reads a TrueType or OpenType program far enough to yield outlines.

func (*TrueType) GIDForRune added in v1.0.0

func (t *TrueType) GIDForRune(r rune) (uint16, bool)

GIDForRune maps a character to a glyph through the font's own cmap.

The Windows Unicode subtable first and the Macintosh Roman one second, which is the order §9.6.5.4 gives for a non-symbolic TrueType font: (3,1) is what every modern producer writes, and (1,0) is what an old one wrote instead.

func (*TrueType) GIDInSubtable added in v1.0.0

func (t *TrueType) GIDInSubtable(platform, encoding uint16, code uint32) (uint16, bool)

GIDInSubtable looks code up in the cmap subtable for platform and encoding, and reports false for a program without one, or a code it maps to no glyph.

func (*TrueType) HasCmap added in v1.0.0

func (t *TrueType) HasCmap() bool

HasCmap reports whether the program carries any cmap subtable.

func (*TrueType) HasSubtable added in v1.0.0

func (t *TrueType) HasSubtable(platform, encoding uint16) bool

HasSubtable reports whether the program carries a cmap subtable for platform and encoding.

func (*TrueType) NumGlyphs added in v1.0.0

func (t *TrueType) NumGlyphs() int

NumGlyphs is the glyph count `maxp` declares.

func (*TrueType) Outline added in v1.0.0

func (t *TrueType) Outline(gid uint16, budget int) (Outline, int, error)

Outline returns a glyph's contours in 1/1000 em, and how much work it took.

budget bounds that work the way CFF.Outline's bounds a charstring's: 1 for every glyph visited, composite components included, plus a simple glyph's own contour count and its point count, charged whether or not those points end up drawing a segment — the contour count first, and before a byte of the contour ends is read, so a corrupt count cannot size an allocation for free. Past the budget the answer is ErrGlyphBudget, wrapped so errors.Is works.

An empty glyph and an unreadable one are different answers. A space has an entry in `loca` with zero length, which is not ink and not an error, so it is nil with no error. A glyph whose data is malformed, or that places a component by point matching, is an error: drawing nothing there would be a silent gap where the font meant a letter, so the caller refuses instead.

The outline comes back translated by -pp1.x, the way TT_Load_Glyph (ttgload.c:2665-2670) translates the assembled outline once, at the top, so "(0,0) is the glyph's origin" regardless of the gap between where glyf places it and where hmtx says its left edge is. pp1 is resolved by outline() in the same traversal that builds the outline — see its comment — so this is the only place the shift is applied; a component is never shifted inside the recursion. The translate does not depend on hinting (TT_Load_Glyph applies it either way), but its amount does: this is the unhinted design-space shift, which is what pdfium draws above 50 device pixels per em — cfx_renderdevice.cpp:1243 sends that text to DrawTextPath, whose LoadGlyphPath loads every non-tricky font with FT_LOAD_NO_HINTING (cfx_face.cpp:1268-1271). At 50 or fewer, pdfium rasterizes through RenderGlyph instead, which loads a TrueType font hinted (cfx_face.cpp:1145-1147), and hinting rounds pp1 to the pixel grid before the translate; nothing in this package rounds anything, so a small glyph can land up to a pixel from where pdfium puts it.

func (*TrueType) PostNamesGlyphs added in v1.0.0

func (t *TrueType) PostNamesGlyphs() bool

PostNamesGlyphs reports whether the program's `post` table should be treated as naming its glyphs: present, per the directory rules ParseTrueType applies, and then either its 32-byte header cannot be confirmed at all — fewer than 32 bytes are physically readable from the table's own offset, so whether it declares FormatType 3.0 ("no PostScript name information here") is unknown — or the header that is readable declares some other FormatType. Only a present table with a confirmed 3.0 header answers false.

A caller with no surviving cmap subtable needs this: FreeType synthesizes a Unicode charmap from those names when nothing else survived tt_face_build_cmaps (sfobjs.c:1206-1230), and reads a symbolic font's code through it before ever falling back to using the code as a glyph index.

func (*TrueType) UnitsPerEm added in v1.0.0

func (t *TrueType) UnitsPerEm() float64

UnitsPerEm is the program's own grid, exposed for a caller that has to reconcile it with a /FontMatrix. Outlines are already converted, so a renderer does not need it.

type Type1 added in v1.0.0

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

A Type 1 font program — what /FontFile holds — parsed far enough to hand out glyph outlines.

What this parses

The Adobe Type 1 Font Format's PFA form: the clear-text part up to eexec, then the eexec- encrypted Private part, from which it takes the Subrs, the CharStrings, lenIV, and the built-in encoding the clear-text part declares. The charstrings themselves are Type 1 and are interpreted in type1charstring.go.

Whose reading

pdfium hands the stream to FreeType, and FreeType does not run PostScript: it walks the tokens looking for the keys it knows (type1/t1load.c, parse_dict), and a key that is not one of them is skipped, whatever it would have done in a PostScript interpreter. The walk here is FreeType's, token for token — its skipper (psaux/psobjs.c, ps_parser_skip_PS_token), its eexec search and whitespace rule (type1/t1parse.c, T1_Get_Private_Dict), its readings of the Subrs and CharStrings entries — since a program read any other way draws other glyphs than the yardstick does.

What it refuses

It refuses where FreeType and the format part ways, and where drawing would need machinery that is not here: the PFB segment form and hex eexec, which no corpus program uses; a FontMatrix other than [0.001 0 0 0.001 0 0], which FreeType applies and a scaled em would need carried through; PaintType other than 0, which asks for a stroked outline FreeType fills; a multiple master or synthetic font; a built-in encoding other than an array of 256 or StandardEncoding; a Subrs or CharStrings entry the declared count has no room for, or a subroutine or glyph name defined twice, where FreeType keeps one of the two by table mechanics PostScript does not share; and a number where FreeType would read the radix or fractional form of one as an integer.

func ParseType1 added in v1.0.0

func ParseType1(data []byte) (*Type1, error)

ParseType1 parses a PFA Type 1 program.

func (*Type1) ClearTextLength added in v1.0.0

func (t *Type1) ClearTextLength() int

ClearTextLength is where the encrypted part starts: the offset /Length1 states in the stream dictionary.

func (*Type1) GIDForCode added in v1.0.0

func (t *Type1) GIDForCode(code byte) (uint16, bool)

GIDForCode maps a code through the built-in encoding. A code the encoding leaves unassigned, or assigns a name no glyph has, answers false, as FreeType's charmap answers glyph 0.

func (*Type1) GIDForName added in v1.0.0

func (t *Type1) GIDForName(name string) (uint16, bool)

GIDForName maps a glyph name to its glyph. Names are unique, since a program defining one twice is refused.

func (*Type1) NumGlyphs added in v1.0.0

func (t *Type1) NumGlyphs() int

NumGlyphs is the glyph count, a .notdef FreeType synthesizes included.

func (*Type1) Outline added in v1.0.0

func (t *Type1) Outline(gid uint16, budget int) (Outline, int, error)

Outline returns a glyph's contours in 1/1000 em, and how many charstring operations it took; budget bounds them as it does for CFF. An empty outline — a space — is nil with no error.

Directories

Path Synopsis
Package cmap reads PDF CMaps: the code-to-CID mappings of composite fonts and the code-to-Unicode mappings of /ToUnicode streams (ISO 32000-2 §9.7.5, §9.10.3).
Package cmap reads PDF CMaps: the code-to-CID mappings of composite fonts and the code-to-Unicode mappings of /ToUnicode streams (ISO 32000-2 §9.7.5, §9.10.3).
Package encoding maps simple-font character codes to glyph names and Unicode.
Package encoding maps simple-font character codes to glyph names and Unicode.

Jump to

Keyboard shortcuts

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