Documentation
¶
Overview ¶
Package fonts provides the Standard 14 Type 1 fonts that are built into all PDF readers.
The 14 Standard Fonts do not require embedding - they are guaranteed to be available in every compliant PDF viewer. This package provides font definitions, metrics, and PDF object generation for these fonts.
Standard 14 Fonts:
- Serif: Times-Roman, Times-Bold, Times-Italic, Times-BoldItalic
- Sans-Serif: Helvetica, Helvetica-Bold, Helvetica-Oblique, Helvetica-BoldOblique
- Monospace: Courier, Courier-Bold, Courier-Oblique, Courier-BoldOblique
- Symbol: Symbol, ZapfDingbats
Usage:
font := fonts.Helvetica var buf bytes.Buffer font.WriteFontObject(5, &buf) // Result: "5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>\nendobj\n"
Index ¶
- Variables
- func GenerateToUnicodeCMap(subset *FontSubset) ([]byte, error)
- func MeasureString(fontName string, text string, size float64) float64
- func SubsetFontName(baseName string, usedChars []rune) string
- type CmapSubtable
- type CmapTable
- type FontDescriptor
- type FontMetrics
- type FontSubset
- func (s *FontSubset) Build() error
- func (s *FontSubset) GetCharWidth(ch rune) uint16
- func (s *FontSubset) GetWidths() (firstChar, lastChar int, widths []int)
- func (s *FontSubset) MeasureString(text string, size float64) float64
- func (s *FontSubset) UseChar(ch rune)
- func (s *FontSubset) UseString(text string)
- type HMetric
- type HeadTable
- type HheaTable
- type HmtxTable
- type Standard14Font
- type TTFFont
- type TTFTable
Constants ¶
This section is empty.
Variables ¶
var ( // TimesRoman is the Times Roman font (Regular weight, Normal style). TimesRoman = &Standard14Font{ Name: "Times-Roman", Family: "Times", Weight: "Regular", Style: "Normal", IsSymbolic: false, } // TimesBold is the Times Bold font. TimesBold = &Standard14Font{ Name: "Times-Bold", Family: "Times", Weight: "Bold", Style: "Normal", IsSymbolic: false, } // TimesItalic is the Times Italic font. TimesItalic = &Standard14Font{ Name: "Times-Italic", Family: "Times", Weight: "Regular", Style: "Italic", IsSymbolic: false, } // TimesBoldItalic is the Times Bold Italic font. TimesBoldItalic = &Standard14Font{ Name: "Times-BoldItalic", Family: "Times", Weight: "Bold", Style: "Italic", IsSymbolic: false, } )
Standard 14 Type 1 Fonts - Serif Family (Times).
var ( // Helvetica is the Helvetica font (Regular weight, Normal style). Helvetica = &Standard14Font{ Name: "Helvetica", Family: "Helvetica", Weight: "Regular", Style: "Normal", IsSymbolic: false, } // HelveticaBold is the Helvetica Bold font. HelveticaBold = &Standard14Font{ Name: "Helvetica-Bold", Family: "Helvetica", Weight: "Bold", Style: "Normal", IsSymbolic: false, } // HelveticaOblique is the Helvetica Oblique font. HelveticaOblique = &Standard14Font{ Name: "Helvetica-Oblique", Family: "Helvetica", Weight: "Regular", Style: "Oblique", IsSymbolic: false, } // HelveticaBoldOblique is the Helvetica Bold Oblique font. HelveticaBoldOblique = &Standard14Font{ Name: "Helvetica-BoldOblique", Family: "Helvetica", Weight: "Bold", Style: "Oblique", IsSymbolic: false, } )
Standard 14 Type 1 Fonts - Sans-Serif Family (Helvetica).
var ( // Courier is the Courier font (Regular weight, Normal style). Courier = &Standard14Font{ Name: "Courier", Family: "Courier", Weight: "Regular", Style: "Normal", IsSymbolic: false, } // CourierBold is the Courier Bold font. CourierBold = &Standard14Font{ Name: "Courier-Bold", Family: "Courier", Weight: "Bold", Style: "Normal", IsSymbolic: false, } // CourierOblique is the Courier Oblique font. CourierOblique = &Standard14Font{ Name: "Courier-Oblique", Family: "Courier", Weight: "Regular", Style: "Oblique", IsSymbolic: false, } // CourierBoldOblique is the Courier Bold Oblique font. CourierBoldOblique = &Standard14Font{ Name: "Courier-BoldOblique", Family: "Courier", Weight: "Bold", Style: "Oblique", IsSymbolic: false, } )
Standard 14 Type 1 Fonts - Monospace Family (Courier).
var ( // Symbol is the Symbol font (symbolic characters, mathematical symbols). Symbol = &Standard14Font{ Name: "Symbol", Family: "Symbol", Weight: "Regular", Style: "Normal", IsSymbolic: true, } // ZapfDingbats is the ZapfDingbats font (symbolic characters, dingbats). ZapfDingbats = &Standard14Font{ Name: "ZapfDingbats", Family: "ZapfDingbats", Weight: "Regular", Style: "Normal", IsSymbolic: true, } )
Standard 14 Type 1 Fonts - Symbolic Fonts.
Functions ¶
func GenerateToUnicodeCMap ¶
func GenerateToUnicodeCMap(subset *FontSubset) ([]byte, error)
GenerateToUnicodeCMap generates a ToUnicode CMap for text extraction.
A ToUnicode CMap allows PDF viewers to extract correct Unicode text from documents using embedded fonts.
The CMap maps character codes (as used in the PDF content stream) to Unicode code points.
Reference: PDF 1.7 specification, Section 9.10 (ToUnicode CMaps).
func MeasureString ¶
MeasureString is a convenience function to measure a string width in points. Uses the specified font's metrics. Returns 0 if the font is not recognized.
func SubsetFontName ¶ added in v0.1.1
SubsetFontName generates a subset font name with random prefix.
PDF subset font names use a 6-letter uppercase prefix followed by '+'. Example: ABCDEF+OpenSans-Regular
The prefix should be unique to allow multiple subsets of the same font.
Types ¶
type CmapSubtable ¶
type CmapSubtable struct {
PlatformID uint16 // Platform ID (0=Unicode, 3=Windows)
EncodingID uint16 // Encoding ID
Format uint16 // Format number (0, 4, 6, 12, etc.)
Mapping map[rune]uint16 // Character to glyph ID mapping
}
CmapSubtable represents a single cmap subtable.
type CmapTable ¶
type CmapTable struct {
Subtables []*CmapSubtable // Platform-specific subtables
}
CmapTable represents the 'cmap' (character to glyph mapping) table.
The cmap table maps character codes to glyph indices. It may contain multiple subtables for different platforms/encodings.
Reference: TrueType specification, 'cmap' table.
type FontDescriptor ¶ added in v0.1.1
type FontDescriptor struct {
// FontName is the PostScript name of the font.
FontName string
// Flags is the font flags bitmap (PDF spec Table 123).
Flags uint32
// FontBBox is the bounding box [llx lly urx ury] in glyph space.
FontBBox [4]int
// ItalicAngle is the angle of italic text in degrees.
ItalicAngle float64
// Ascent is the maximum height above baseline.
Ascent int
// Descent is the maximum depth below baseline (negative).
Descent int
// CapHeight is the height of capital letters.
CapHeight int
// StemV is the dominant vertical stem width.
StemV int
// XHeight is the height of lowercase x (optional).
XHeight int
// Leading is the spacing between lines (optional).
Leading int
// FontFile2Ref is the object number of the embedded font stream.
// Set to 0 if font is not embedded.
FontFile2Ref int
}
FontDescriptor represents a PDF FontDescriptor dictionary.
The FontDescriptor specifies metrics and other attributes of a font. It is required for embedded fonts in PDF documents.
Reference: PDF Reference 1.7, Section 9.8.
func GenerateFontDescriptor ¶ added in v0.1.1
func GenerateFontDescriptor(ttf *TTFFont) *FontDescriptor
GenerateFontDescriptor creates a FontDescriptor from TTF font data.
This extracts all required metrics from the parsed TTF font and converts them to PDF glyph space (scaled by 1000/UnitsPerEm).
func (*FontDescriptor) ToPDFDict ¶ added in v0.1.1
func (fd *FontDescriptor) ToPDFDict(fontFile2ObjNum int) string
ToPDFDict generates the PDF FontDescriptor dictionary as bytes.
The output format:
<< /Type /FontDescriptor /FontName /FontName /Flags 32 /FontBBox [0 -200 1000 800] /ItalicAngle 0 /Ascent 800 /Descent -200 /CapHeight 700 /StemV 80 /FontFile2 X 0 R >>
type FontMetrics ¶
type FontMetrics struct {
// Ascender is the maximum height above the baseline.
Ascender int
// Descender is the maximum depth below the baseline (negative value).
Descender int
// CapHeight is the height of capital letters.
CapHeight int
// XHeight is the height of lowercase letters (typically 'x').
XHeight int
// DefaultWidth is used for characters without explicit width data.
DefaultWidth int
// CharWidths maps runes to their widths in font units.
// For WinAnsiEncoding fonts, this covers code points 0-255.
CharWidths map[rune]int
}
FontMetrics contains metric information for a font. All measurements are in font units (1000 units = 1 em).
func GetMetrics ¶
func GetMetrics(fontName string) *FontMetrics
GetMetrics returns the FontMetrics for a font by its PostScript name. Returns nil if the font is not recognized.
func (*FontMetrics) GetAscender ¶
func (m *FontMetrics) GetAscender() int
GetAscender returns the ascender value in font units.
func (*FontMetrics) GetCapHeight ¶
func (m *FontMetrics) GetCapHeight() int
GetCapHeight returns the cap height in font units.
func (*FontMetrics) GetCharWidth ¶
func (m *FontMetrics) GetCharWidth(ch rune) int
GetCharWidth returns the width of a character in font units (1000 units = 1 em). If the character is not found, returns the default width.
func (*FontMetrics) GetDescender ¶
func (m *FontMetrics) GetDescender() int
GetDescender returns the descender value in font units (negative).
func (*FontMetrics) GetXHeight ¶
func (m *FontMetrics) GetXHeight() int
GetXHeight returns the x-height in font units.
func (*FontMetrics) MeasureString ¶
func (m *FontMetrics) MeasureString(text string, size float64) float64
MeasureString returns the width of a string in points at the given font size. Formula: width_points = (sum of char widths) * size / 1000.
type FontSubset ¶
type FontSubset struct {
// BaseFont is the original font.
BaseFont *TTFFont
// UsedChars is the set of characters used in the document.
UsedChars map[rune]bool
// GlyphMapping maps old glyph IDs to new glyph IDs.
GlyphMapping map[uint16]uint16
// SubsetData is the compressed font data (for embedding).
SubsetData []byte
}
FontSubset represents a subset of a font containing only used glyphs.
Font subsetting reduces PDF file size by embedding only the glyphs that are actually used in the document, rather than the entire font.
Benefits:
- Smaller file size (especially for large CJK fonts)
- Faster loading
- Lower memory usage
func NewFontSubset ¶
func NewFontSubset(font *TTFFont) *FontSubset
NewFontSubset creates a new font subset from a TTF font.
func (*FontSubset) Build ¶
func (s *FontSubset) Build() error
Build builds the font subset.
This process:
- Identifies all glyphs used (via character mapping)
- Creates a new glyph ID mapping
- Builds subset font data
- Compresses the data
Returns an error if subsetting fails.
func (*FontSubset) GetCharWidth ¶
func (s *FontSubset) GetCharWidth(ch rune) uint16
GetCharWidth returns the width of a character in font units.
func (*FontSubset) GetWidths ¶
func (s *FontSubset) GetWidths() (firstChar, lastChar int, widths []int)
GetWidths returns an array of character widths for PDF /Widths array.
The /Widths array in PDF specifies the width of each character from firstChar to lastChar.
func (*FontSubset) MeasureString ¶
func (s *FontSubset) MeasureString(text string, size float64) float64
MeasureString returns the width of a string in points.
func (*FontSubset) UseChar ¶
func (s *FontSubset) UseChar(ch rune)
UseChar marks a character as used in the document.
func (*FontSubset) UseString ¶
func (s *FontSubset) UseString(text string)
UseString marks all characters in a string as used.
type HMetric ¶
type HMetric struct {
AdvanceWidth uint16 // Advance width in font units
LeftSideBearing int16 // Left side bearing in font units
}
HMetric represents horizontal metrics for a single glyph.
type HeadTable ¶
type HeadTable struct {
UnitsPerEm uint16 // Units per em square (typically 1000 or 2048)
XMin int16 // Minimum X coordinate
YMin int16 // Minimum Y coordinate
XMax int16 // Maximum X coordinate
YMax int16 // Maximum Y coordinate
}
HeadTable represents the 'head' (font header) table.
The head table contains global information about the font:
- Font version, creation date
- Units per em (scaling factor)
- Bounding box
- Index format flags
Reference: TrueType specification, 'head' table.
type HheaTable ¶
type HheaTable struct {
Ascender int16 // Typographic ascender
Descender int16 // Typographic descender
LineGap int16 // Typographic line gap
NumOfLongHorMetrics uint16 // Number of hMetric entries in hmtx table
}
HheaTable represents the 'hhea' (horizontal header) table.
The hhea table contains metrics for horizontal layout:
- Ascender, descender, line gap
- Number of horizontal metrics
Reference: TrueType specification, 'hhea' table.
type HmtxTable ¶
type HmtxTable struct {
Metrics []HMetric // Horizontal metrics for each glyph
}
HmtxTable represents the 'hmtx' (horizontal metrics) table.
The hmtx table contains advance widths and left side bearings for all glyphs in the font.
Reference: TrueType specification, 'hmtx' table.
type Standard14Font ¶
type Standard14Font struct {
// Name is the PostScript name of the font (e.g., "Helvetica", "Times-Roman").
Name string
// Family is the font family name (e.g., "Helvetica", "Times").
Family string
// Weight is the font weight (e.g., "Regular", "Bold").
Weight string
// Style is the font style (e.g., "Normal", "Oblique", "Italic").
Style string
// IsSymbolic indicates whether this is a symbolic font (Symbol, ZapfDingbats).
// Symbolic fonts use different encoding and character sets.
IsSymbolic bool
}
Standard14Font represents one of the 14 Type 1 fonts built into all PDF readers. These fonts do not require embedding and are guaranteed to be available.
func (*Standard14Font) GetMetrics ¶
func (f *Standard14Font) GetMetrics() *FontMetrics
GetMetrics returns the FontMetrics for a Standard14Font. Returns nil if the font is not recognized.
func (*Standard14Font) PDFName ¶
func (f *Standard14Font) PDFName() string
PDFName returns the PostScript name of the font for use in PDF objects. This is the /BaseFont value in the font dictionary.
func (*Standard14Font) WriteFontObject ¶
func (f *Standard14Font) WriteFontObject(objNum int, w io.Writer) error
WriteFontObject writes a PDF font object for this Standard 14 font. The object number is specified by objNum, and the output is written to w.
Format:
5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> endobj
Note: Symbolic fonts (Symbol, ZapfDingbats) do not include /Encoding.
type TTFFont ¶
type TTFFont struct {
// FilePath is the path to the font file.
FilePath string
// PostScriptName is the font's PostScript name (from name table).
PostScriptName string
// Tables contains all parsed font tables.
Tables map[string]*TTFTable
// UnitsPerEm is the number of font units per em square (from head table).
UnitsPerEm uint16
// GlyphWidths maps glyph IDs to their advance widths.
GlyphWidths map[uint16]uint16
// CharToGlyph maps Unicode code points to glyph IDs.
CharToGlyph map[rune]uint16
// FontData is the raw font file data (for embedding).
FontData []byte
// FontBBox is the font bounding box [xMin, yMin, xMax, yMax].
FontBBox [4]int16
// Ascender is the typographic ascender (from hhea).
Ascender int16
// Descender is the typographic descender (from hhea, negative).
Descender int16
// LineGap is the typographic line gap (from hhea).
LineGap int16
// ItalicAngle is the italic angle in degrees (from post table).
ItalicAngle float64
// UnderlinePosition is the underline position (from post table).
UnderlinePosition int16
// UnderlineThickness is the underline thickness (from post table).
UnderlineThickness int16
// IsFixedPitch indicates if the font is monospaced (from post table).
IsFixedPitch bool
// CapHeight is the height of capital letters (from OS/2).
CapHeight int16
// XHeight is the height of lowercase x (from OS/2).
XHeight int16
// WeightClass is the font weight (100-900, from OS/2).
WeightClass uint16
// WidthClass is the font width class (1-9, from OS/2).
WidthClass uint16
// FSType is the embedding licensing rights (from OS/2).
FSType uint16
// TypoAscender is the OS/2 typographic ascender.
TypoAscender int16
// TypoDescender is the OS/2 typographic descender.
TypoDescender int16
// StemV is the vertical stem width (estimated from weight).
StemV int16
// Flags is the PDF font flags bitmap.
Flags uint32
}
TTFFont represents a parsed TrueType/OpenType font.
TrueType fonts (.ttf) and OpenType fonts with TrueType outlines (.otf) share the same basic structure and can be parsed using the same logic.
The font file contains:
- Font directory with table entries
- Multiple tables (head, hhea, hmtx, cmap, glyf, loca, etc.)
- Glyph outlines
Reference: TrueType specification, Microsoft Typography.
func LoadTTF ¶
LoadTTF loads and parses a TrueType/OpenType font file.
This function:
- Reads the entire font file
- Parses the font directory
- Loads all required tables
- Extracts glyph metrics
- Builds character-to-glyph mapping
Returns an error if the file is not a valid TTF/OTF font.
func LoadTTFFromBytes ¶ added in v0.8.0
LoadTTFFromBytes parses a TrueType/OpenType font from an in-memory byte slice.
This is the counterpart to LoadTTF for cases where font data is already in memory — for example, when a font has been extracted from an existing PDF via Document.GetEmbeddedFonts.
The data slice is stored as FontData so the font can be re-embedded without re-reading from disk. FilePath is left empty; callers may set it after loading if the original path is known.
Returns an error if the bytes do not represent a valid TrueType or OpenType font with TrueType outlines.