Tools to manipulate font files
—
Essential font loading, manipulation, and saving functionality using the TTFont class. Provides table-based access to all font data with lazy loading and extensive format support including TTF, OTF, WOFF, WOFF2, and TTX XML.
The primary class for font manipulation, providing dictionary-like access to OpenType tables and comprehensive font processing methods.
class TTFont:
def __init__(self, file=None, sfntVersion="\\000\\001\\000\\000", fontNumber=0, lazy=None, recalcBBoxes=True, recalcTimestamp=True, allowVID=False, ignoreDecompileErrors=False, transform=None, cfg=None):
"""
Load and create a font object.
Parameters:
- file: str or file-like, font file path or file object
- sfntVersion: bytes, SFNT version for new fonts
- fontNumber: int, font index in collection (0-based)
- lazy: bool, enable lazy table loading (default: True for files)
- recalcBBoxes: bool, recalculate bounding boxes on save
- recalcTimestamp: bool, update timestamp on save
- allowVID: bool, allow vertical ID usage
- ignoreDecompileErrors: bool, continue on table decompilation errors
- transform: Transform, apply transformation on load
- cfg: dict, configuration options
"""
def save(self, file, reorderTables=True):
"""
Save font to file.
Parameters:
- file: str or file-like, output file path or file object
- reorderTables: bool, reorder tables for optimal loading
"""
def saveXML(self, file, **kwargs):
"""
Export font as TTX XML format.
Parameters:
- file: str or file-like, output XML file
- kwargs: additional options for XML generation
"""
def importXML(self, file, **kwargs):
"""
Import font data from TTX XML format.
Parameters:
- file: str or file-like, input XML file
- kwargs: additional options for XML parsing
"""
def getGlyphOrder(self):
"""
Get ordered list of glyph names.
Returns:
List[str]: Glyph names in font order
"""
def setGlyphOrder(self, glyphOrder):
"""
Set glyph order for the font.
Parameters:
- glyphOrder: List[str], ordered glyph names
"""
def getGlyphSet(self):
"""
Get glyph drawing interface.
Returns:
GlyphSet: Object providing drawing access to glyphs
"""
def getBestCmap(self):
"""
Get best Unicode character map.
Returns:
Dict[int, str]: Unicode codepoint to glyph name mapping
"""
def getTableData(self, tag):
"""
Get raw binary data for font table.
Parameters:
- tag: str, 4-character OpenType table tag
Returns:
bytes: Raw table data
"""
def close(self):
"""Close font file and release resources."""
# Dictionary-like table access
def __getitem__(self, tag):
"""Access font table by tag (e.g., font['head'])."""
def __setitem__(self, tag, table):
"""Set font table by tag."""
def __delitem__(self, tag):
"""Delete font table by tag."""
def __contains__(self, tag):
"""Check if font contains table."""
def keys(self):
"""Get available table tags."""from fontTools.ttLib import TTFont
# Load a font
font = TTFont("arial.ttf")
# Access font tables
head_table = font['head']
print(f"Units per em: {head_table.unitsPerEm}")
print(f"Font revision: {head_table.fontRevision}")
# Character mapping
cmap = font.getBestCmap()
unicode_a = ord('A')
if unicode_a in cmap:
glyph_name = cmap[unicode_a]
print(f"Glyph for 'A': {glyph_name}")
# Glyph information
glyph_set = font.getGlyphSet()
glyph_order = font.getGlyphOrder()
print(f"Total glyphs: {len(glyph_order)}")
# Access specific glyph
if 'A' in glyph_set:
glyph = glyph_set['A']
print(f"Glyph 'A' width: {glyph.width}")
# Modify and save
font['head'].fontRevision = 1.001
font.save("modified_arial.ttf")
font.close()Handle TrueType Collections (.ttc files) containing multiple fonts.
class TTCollection:
def __init__(self, file=None, fontNumber=0, **kwargs):
"""
Load TrueType Collection.
Parameters:
- file: str or file-like, collection file path or file object
- fontNumber: int, specific font index to load (default: 0)
- kwargs: additional TTFont arguments
"""
def save(self, file):
"""
Save collection to file.
Parameters:
- file: str or file-like, output file path or file object
"""
def saveXML(self, fileOrPath, **kwargs):
"""
Export collection as TTX XML.
Parameters:
- fileOrPath: str or file-like, output XML file
- kwargs: XML generation options
"""
def close(self):
"""Close collection and release resources."""
# Access individual fonts
def __getitem__(self, index):
"""Get font by index."""
def __len__(self):
"""Get number of fonts in collection."""Utility functions for working with OpenType tables.
def newTable(tag):
"""
Create new font table instance.
Parameters:
- tag: str, 4-character OpenType table tag
Returns:
BaseTable: Empty table instance
"""
def getTableClass(tag):
"""
Get table class for OpenType tag.
Parameters:
- tag: str, 4-character OpenType table tag
Returns:
type: Table class for the tag
"""
def registerCustomTableClass(tag, tableClass, module=None):
"""
Register custom table implementation.
Parameters:
- tag: str, 4-character OpenType table tag
- tableClass: type, custom table class
- module: str, module name (optional)
"""from fontTools.ttLib import newTable, getTableClass
# Create new table
head_table = newTable('head')
head_table.magicNumber = 0x5F0F3CF5
head_table.unitsPerEm = 1000
# Get table class info
HeadTableClass = getTableClass('head')
print(f"Head table class: {HeadTableClass.__name__}")
# Register custom table (advanced usage)
class CustomTableClass:
def __init__(self):
self.data = b""
def decompile(self, data, ttFont):
self.data = data
def compile(self, ttFont):
return self.data
registerCustomTableClass('CUST', CustomTableClass)class TTLibError(Exception):
"""Base exception for TTLib operations."""
class TTLibFileIsCollectionError(TTLibError):
"""Raised when expecting single font but got collection."""TTFont supports context manager protocol for automatic resource cleanup:
# Recommended usage pattern
with TTFont("font.ttf") as font:
# Work with font
cmap = font.getBestCmap()
# Font automatically closed when exiting contextclose() to free resourcesInstall with Tessl CLI
npx tessl i tessl/pypi-fonttools