Tools to manipulate font files
npx @tessl/cli install tessl/pypi-fonttools@4.59.0FontTools is a comprehensive Python library for manipulating fonts, providing tools to work with TrueType, OpenType, AFM and Type 1 fonts. The library includes the TTX tool that can convert fonts to and from XML text format, enabling font analysis and modification. It supports font file parsing, glyph manipulation, font subsetting, and various font format conversions.
pip install fonttoolsimport fontToolsCommon for font manipulation:
from fontTools.ttLib import TTFontFor font building from scratch:
from fontTools.fontBuilder import FontBuilderfrom fontTools.ttLib import TTFont
# Load a font file
font = TTFont("font.ttf")
# Access font tables
head_table = font['head']
print(f"Font revision: {head_table.fontRevision}")
# Get glyph information
glyph_set = font.getGlyphSet()
glyph_names = font.getGlyphOrder()
print(f"Number of glyphs: {len(glyph_names)}")
# Get character mapping
cmap = font.getBestCmap()
print(f"Unicode mappings: {len(cmap)} characters")
# Save font
font.save("modified_font.ttf")
font.close()FontTools uses a modular architecture organized around OpenType table manipulation:
This design enables both low-level font manipulation and high-level font processing workflows, making FontTools the foundation for font-related projects in the Python ecosystem.
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.
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): ...
def save(self, file, reorderTables=True): ...
def saveXML(self, file): ...
def importXML(self, file): ...
def getGlyphOrder(self): ...
def setGlyphOrder(self, glyphOrder): ...
def getGlyphSet(self): ...
def getBestCmap(self): ...
def close(self): ...Build fonts from scratch using a builder pattern, supporting both TrueType and CFF/PostScript font creation with comprehensive table setup methods.
class FontBuilder:
def __init__(self, unitsPerEm=None, font=None, isTTF=True): ...
def setupGlyphOrder(self, glyphOrder): ...
def setupCharacterMap(self, cmap): ...
def setupGlyf(self, glyphs): ...
def setupCFF(self, psName, charStrings, charStringsType=2): ...
def setupHorizontalMetrics(self, metrics): ...
def setupNameTable(self, nameStrings, mac=True): ...Font optimization, subsetting, and merging tools for reducing file sizes and combining multiple fonts into collections.
class Subsetter:
def __init__(self, options=None): ...
def subset(self, font): ...
class Merger:
def __init__(self, options=None): ...
def merge(self, fontfiles): ...Build and manipulate variable fonts using design space documents, supporting multi-axis font variations and instance generation.
def build(designspace, master_finder=lambda s: s, exclude=[], optimize=True, **kwargs): ...
def load_designspace(designspace): ...
def load_masters(designspace, master_finder): ...
class DesignSpaceDocument:
def read(self, path): ...
def write(self, path): ...
def addAxisDescriptor(self, descriptor): ...Standardized drawing interface for glyph construction, manipulation, and rendering with specialized pen implementations for different use cases.
class AbstractPen:
def moveTo(self, pt): ...
def lineTo(self, pt): ...
def curveTo(self, *points): ...
def qCurveTo(self, *points): ...
def closePath(self): ...
def endPath(self): ...
class TTGlyphPen(BasePen): ...
class BoundsPen(BasePen): ...
class TransformPen(BasePen): ...Miscellaneous utilities for text processing, geometric transformations, XML handling, and various font-related calculations.
class Transform:
def __init__(self, a=1, b=0, c=0, d=1, e=0, f=0): ...
def transform(self, x, y): ...
def scale(self, x, y=None): ...
def rotate(self, angle): ...
def translate(self, x, y): ...
def calcBounds(array): ...
def roundFunc(value, func=round): ...FontTools provides a unified command-line interface through the fonttools command:
# Convert font to TTX XML format
fonttools ttx font.ttf
# Subset a font to specific characters
fonttools subset font.ttf --text="Hello World"
# Merge multiple fonts
fonttools merge font1.ttf font2.ttf
# Build variable font from design space
fonttools varLib design.designspaceFontTools defines specific exception hierarchies for different operations:
TTLibError: Base exception for font loading/saving errorsSubsettingError: Font subsetting operation failuresFeatureLibError: OpenType feature compilation errorsPenError: Drawing operation errorsDesignSpaceDocumentError: Design space processing errors# Core types used throughout FontTools
GlyphOrder = List[str]
CharacterMap = Dict[int, str] # Unicode codepoint to glyph name
Metrics = Dict[str, Tuple[int, int]] # glyph name to (advance width, left side bearing)
Point = Tuple[float, float]
BoundingBox = Tuple[float, float, float, float] # xMin, yMin, xMax, yMax