0
# Core Font Operations
1
2
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.
3
4
## Capabilities
5
6
### TTFont Class
7
8
The primary class for font manipulation, providing dictionary-like access to OpenType tables and comprehensive font processing methods.
9
10
```python { .api }
11
class TTFont:
12
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):
13
"""
14
Load and create a font object.
15
16
Parameters:
17
- file: str or file-like, font file path or file object
18
- sfntVersion: bytes, SFNT version for new fonts
19
- fontNumber: int, font index in collection (0-based)
20
- lazy: bool, enable lazy table loading (default: True for files)
21
- recalcBBoxes: bool, recalculate bounding boxes on save
22
- recalcTimestamp: bool, update timestamp on save
23
- allowVID: bool, allow vertical ID usage
24
- ignoreDecompileErrors: bool, continue on table decompilation errors
25
- transform: Transform, apply transformation on load
26
- cfg: dict, configuration options
27
"""
28
29
def save(self, file, reorderTables=True):
30
"""
31
Save font to file.
32
33
Parameters:
34
- file: str or file-like, output file path or file object
35
- reorderTables: bool, reorder tables for optimal loading
36
"""
37
38
def saveXML(self, file, **kwargs):
39
"""
40
Export font as TTX XML format.
41
42
Parameters:
43
- file: str or file-like, output XML file
44
- kwargs: additional options for XML generation
45
"""
46
47
def importXML(self, file, **kwargs):
48
"""
49
Import font data from TTX XML format.
50
51
Parameters:
52
- file: str or file-like, input XML file
53
- kwargs: additional options for XML parsing
54
"""
55
56
def getGlyphOrder(self):
57
"""
58
Get ordered list of glyph names.
59
60
Returns:
61
List[str]: Glyph names in font order
62
"""
63
64
def setGlyphOrder(self, glyphOrder):
65
"""
66
Set glyph order for the font.
67
68
Parameters:
69
- glyphOrder: List[str], ordered glyph names
70
"""
71
72
def getGlyphSet(self):
73
"""
74
Get glyph drawing interface.
75
76
Returns:
77
GlyphSet: Object providing drawing access to glyphs
78
"""
79
80
def getBestCmap(self):
81
"""
82
Get best Unicode character map.
83
84
Returns:
85
Dict[int, str]: Unicode codepoint to glyph name mapping
86
"""
87
88
def getTableData(self, tag):
89
"""
90
Get raw binary data for font table.
91
92
Parameters:
93
- tag: str, 4-character OpenType table tag
94
95
Returns:
96
bytes: Raw table data
97
"""
98
99
def close(self):
100
"""Close font file and release resources."""
101
102
# Dictionary-like table access
103
def __getitem__(self, tag):
104
"""Access font table by tag (e.g., font['head'])."""
105
106
def __setitem__(self, tag, table):
107
"""Set font table by tag."""
108
109
def __delitem__(self, tag):
110
"""Delete font table by tag."""
111
112
def __contains__(self, tag):
113
"""Check if font contains table."""
114
115
def keys(self):
116
"""Get available table tags."""
117
```
118
119
#### Usage Examples
120
121
```python
122
from fontTools.ttLib import TTFont
123
124
# Load a font
125
font = TTFont("arial.ttf")
126
127
# Access font tables
128
head_table = font['head']
129
print(f"Units per em: {head_table.unitsPerEm}")
130
print(f"Font revision: {head_table.fontRevision}")
131
132
# Character mapping
133
cmap = font.getBestCmap()
134
unicode_a = ord('A')
135
if unicode_a in cmap:
136
glyph_name = cmap[unicode_a]
137
print(f"Glyph for 'A': {glyph_name}")
138
139
# Glyph information
140
glyph_set = font.getGlyphSet()
141
glyph_order = font.getGlyphOrder()
142
print(f"Total glyphs: {len(glyph_order)}")
143
144
# Access specific glyph
145
if 'A' in glyph_set:
146
glyph = glyph_set['A']
147
print(f"Glyph 'A' width: {glyph.width}")
148
149
# Modify and save
150
font['head'].fontRevision = 1.001
151
font.save("modified_arial.ttf")
152
font.close()
153
```
154
155
### TTCollection Class
156
157
Handle TrueType Collections (.ttc files) containing multiple fonts.
158
159
```python { .api }
160
class TTCollection:
161
def __init__(self, file=None, fontNumber=0, **kwargs):
162
"""
163
Load TrueType Collection.
164
165
Parameters:
166
- file: str or file-like, collection file path or file object
167
- fontNumber: int, specific font index to load (default: 0)
168
- kwargs: additional TTFont arguments
169
"""
170
171
def save(self, file):
172
"""
173
Save collection to file.
174
175
Parameters:
176
- file: str or file-like, output file path or file object
177
"""
178
179
def saveXML(self, fileOrPath, **kwargs):
180
"""
181
Export collection as TTX XML.
182
183
Parameters:
184
- fileOrPath: str or file-like, output XML file
185
- kwargs: XML generation options
186
"""
187
188
def close(self):
189
"""Close collection and release resources."""
190
191
# Access individual fonts
192
def __getitem__(self, index):
193
"""Get font by index."""
194
195
def __len__(self):
196
"""Get number of fonts in collection."""
197
```
198
199
### Font Table Management
200
201
Utility functions for working with OpenType tables.
202
203
```python { .api }
204
def newTable(tag):
205
"""
206
Create new font table instance.
207
208
Parameters:
209
- tag: str, 4-character OpenType table tag
210
211
Returns:
212
BaseTable: Empty table instance
213
"""
214
215
def getTableClass(tag):
216
"""
217
Get table class for OpenType tag.
218
219
Parameters:
220
- tag: str, 4-character OpenType table tag
221
222
Returns:
223
type: Table class for the tag
224
"""
225
226
def registerCustomTableClass(tag, tableClass, module=None):
227
"""
228
Register custom table implementation.
229
230
Parameters:
231
- tag: str, 4-character OpenType table tag
232
- tableClass: type, custom table class
233
- module: str, module name (optional)
234
"""
235
```
236
237
#### Usage Examples
238
239
```python
240
from fontTools.ttLib import newTable, getTableClass
241
242
# Create new table
243
head_table = newTable('head')
244
head_table.magicNumber = 0x5F0F3CF5
245
head_table.unitsPerEm = 1000
246
247
# Get table class info
248
HeadTableClass = getTableClass('head')
249
print(f"Head table class: {HeadTableClass.__name__}")
250
251
# Register custom table (advanced usage)
252
class CustomTableClass:
253
def __init__(self):
254
self.data = b""
255
256
def decompile(self, data, ttFont):
257
self.data = data
258
259
def compile(self, ttFont):
260
return self.data
261
262
registerCustomTableClass('CUST', CustomTableClass)
263
```
264
265
### Error Handling
266
267
```python { .api }
268
class TTLibError(Exception):
269
"""Base exception for TTLib operations."""
270
271
class TTLibFileIsCollectionError(TTLibError):
272
"""Raised when expecting single font but got collection."""
273
```
274
275
### Context Manager Support
276
277
TTFont supports context manager protocol for automatic resource cleanup:
278
279
```python
280
# Recommended usage pattern
281
with TTFont("font.ttf") as font:
282
# Work with font
283
cmap = font.getBestCmap()
284
# Font automatically closed when exiting context
285
```
286
287
## Supported Font Formats
288
289
- **TrueType**: .ttf files with TrueType outlines
290
- **OpenType**: .otf files with CFF/PostScript outlines
291
- **WOFF**: Web Open Font Format (compressed TTF/OTF)
292
- **WOFF2**: Web Open Font Format 2.0 (improved compression)
293
- **TTX**: XML representation of binary font data
294
- **TrueType Collections**: .ttc files containing multiple fonts
295
- **Variable Fonts**: Fonts with variation axes
296
297
## Performance Considerations
298
299
- **Lazy Loading**: Tables are only parsed when accessed, improving load performance
300
- **Memory Management**: Use context managers or explicit `close()` to free resources
301
- **Table Caching**: Parsed tables are cached for repeated access
302
- **Selective Loading**: Load only needed tables by accessing specific keys
303
- **Batch Operations**: Process multiple fonts efficiently using consistent patterns