ttFont: Read/write OpenType and TrueType fonts
- class fontTools.ttLib.ttFont.TTFont(file=None, res_name_or_index=None, sfntVersion='\x00\x01\x00\x00', flavor=None, checkChecksums=0, verbose=None, recalcBBoxes=True, allowVID=NotImplemented, ignoreDecompileErrors=False, recalcTimestamp=True, fontNumber=-1, lazy=None, quiet=None, _tableCache=None, cfg={})[source]
Bases:
object
Represents a TrueType font.
The object manages file input and output, and offers a convenient way of accessing tables. Tables will be only decompiled when necessary, ie. when they’re actually accessed. This means that simple operations can be extremely fast.
Example usage: .. code-block:: pycon
>>> >> from fontTools import ttLib >> tt = ttLib.TTFont("afont.ttf") # Load an existing font file >> tt['maxp'].numGlyphs 242 >> tt['OS/2'].achVendID 'B&H' >> tt['head'].unitsPerEm 2048
For details of the objects returned when accessing each table, see tables. To add a table to the font, use the
newTable()
function: .. code-block:: pycon>>> >> os2 = newTable("OS/2") >> os2.version = 4 >> # set other attributes >> font["OS/2"] = os2
TrueType fonts can also be serialized to and from XML format (see also the ttx binary): .. code-block:: pycon
>> >> tt.saveXML(“afont.ttx”) Dumping ‘LTSH’ table… Dumping ‘OS/2’ table… […]
>> tt2 = ttLib.TTFont() # Create a new font object >> tt2.importXML(“afont.ttx”) >> tt2[‘maxp’].numGlyphs 242
The TTFont object may be used as a context manager; this will cause the file reader to be closed after the context
with
block is exited:with TTFont(filename) as f: # Do stuff
- Parameters:
file – When reading a font from disk, either a pathname pointing to a file, or a readable file object.
res_name_or_index – If running on a Macintosh, either a sfnt resource name or an sfnt resource index number. If the index number is zero, TTLib will autodetect whether the file is a flat file or a suitcase. (If it is a suitcase, only the first ‘sfnt’ resource will be read.)
sfntVersion (str) – When constructing a font object from scratch, sets the four-byte sfnt magic number to be used. Defaults to
\\\
(TrueType). To create an OpenType file, useOTTO
.flavor (str) – Set this to
woff
when creating a WOFF file orwoff2
for a WOFF2 file.checkChecksums (int) – How checksum data should be treated. Default is 0 (no checking). Set to 1 to check and warn on wrong checksums; set to 2 to raise an exception if any wrong checksums are found.
recalcBBoxes (bool) – If true (the default), recalculates
glyf
,CFF ``, ``head
bounding box values andhhea
/vhea
min/max values on save. Also compiles the glyphs on importing, which saves memory consumption and time.ignoreDecompileErrors (bool) – If true, exceptions raised during table decompilation will be ignored, and the binary data will be returned for those tables instead.
recalcTimestamp (bool) – If true (the default), sets the
modified
timestamp in thehead
table on save.fontNumber (int) – The index of the font in a TrueType Collection file.
lazy (bool) – If lazy is set to True, many data structures are loaded lazily, upon access only. If it is set to False, many data structures are loaded immediately. The default is
lazy=None
which is somewhere in between.
- save(file, reorderTables=True)[source]
Save the font to disk.
- Parameters:
file – Similarly to the constructor, can be either a pathname or a writable file object.
reorderTables (Option[bool]) – If true (the default), reorder the tables, sorting them by tag (recommended by the OpenType specification). If false, retain the original font order. If None, reorder by table dependency (fastest).
- saveXML(fileOrPath, newlinestr='\n', **kwargs)[source]
Export the font as TTX (an XML-based text file), or as a series of text files when splitTables is true. In the latter case, the ‘fileOrPath’ argument should be a path to a directory. The ‘tables’ argument must either be false (dump all tables) or a list of tables to dump. The ‘skipTables’ argument may be a list of tables to skip, but only when the ‘tables’ argument is false.
- importXML(fileOrPath, quiet=None)[source]
Import a TTX file (an XML-based text format), so as to recreate a font object.
- isLoaded(tag)[source]
Return true if the table identified by
tag
has been decompiled and loaded into memory.
- has_key(tag)[source]
Test if the table identified by
tag
is present in the font.As well as this method,
tag in font
can also be used to determine the presence of the table.
- ensureDecompiled(recurse=None)[source]
Decompile all the tables, even if a TTFont was opened in ‘lazy’ mode.
- get(tag, default=None)[source]
Returns the table if it exists or (optionally) a default if it doesn’t.
- setGlyphOrder(glyphOrder)[source]
Set the glyph order
- Parameters:
glyphOrder ([str]) – List of glyph names in order.
- getGlyphName(glyphID)[source]
Returns the name for the glyph with the given ID.
If no name is available, synthesises one with the form
glyphXXXXX`
where`XXXXX
is the zero-padded glyph ID.
- getTableData(tag)[source]
Returns the binary representation of a table.
If the table is currently loaded and in memory, the data is compiled to binary and returned; if it is not currently loaded, the binary data is read from the font file and returned.
- getGlyphSet(preferCFF=True, location=None, normalized=False, recalcBounds=True)[source]
Return a generic GlyphSet, which is a dict-like object mapping glyph names to glyph objects. The returned glyph objects have a
.draw()
method that supports the Pen protocol, and will have an attribute named ‘width’.If the font is CFF-based, the outlines will be taken from the
CFF `` or ``CFF2
tables. Otherwise the outlines will be taken from theglyf
table.If the font contains both a
CFF ``/``CFF2
and aglyf
table, you can use thepreferCFF
argument to specify which one should be taken. If the font contains both aCFF `` and a ``CFF2
table, the latter is taken.If the
location
parameter is set, it should be a dictionary mapping four-letter variation tags to their float values, and the returned glyph-set will represent an instance of a variable font at that location.If the
normalized
variable is set to True, that location is interpreted as in the normalized (-1..+1) space, otherwise it is in the font’s defined axes space.
- normalizeLocation(location)[source]
Normalize a
location
from the font’s defined axes space (also known as user space) into the normalized (-1..+1) space. It appliesavar
mapping if the font contains anavar
table.The
location
parameter should be a dictionary mapping four-letter variation tags to their float values.Raises
TTLibError
if the font is not a variable font.
- getBestCmap(cmapPreferences=((3, 10), (0, 6), (0, 4), (3, 1), (0, 3), (0, 2), (0, 1), (0, 0)))[source]
Returns the ‘best’ Unicode cmap dictionary available in the font or
None
, if no Unicode cmap subtable is available.By default it will search for the following (platformID, platEncID) pairs in order:
(3, 10), # Windows Unicode full repertoire (0, 6), # Unicode full repertoire (format 13 subtable) (0, 4), # Unicode 2.0 full repertoire (3, 1), # Windows Unicode BMP (0, 3), # Unicode 2.0 BMP (0, 2), # Unicode ISO/IEC 10646 (0, 1), # Unicode 1.1 (0, 0) # Unicode 1.0
This particular order matches what HarfBuzz uses to choose what subtable to use by default. This order prefers the largest-repertoire subtable, and among those, prefers the Windows-platform over the Unicode-platform as the former has wider support.
This order can be customized via the
cmapPreferences
argument.
- class fontTools.ttLib.ttFont.GlyphOrder(tag=None)[source]
Bases:
object
A pseudo table. The glyph order isn’t in the font as a separate table, but it’s nice to present it as such in the TTX format.
- fontTools.ttLib.ttFont.getTableModule(tag)[source]
Fetch the packer/unpacker module for a table. Return None when no module is found.
- fontTools.ttLib.ttFont.registerCustomTableClass(tag, moduleName, className=None)[source]
Register a custom packer/unpacker class for a table.
The ‘moduleName’ must be an importable module. If no ‘className’ is given, it is derived from the tag, for example it will be
table_C_U_S_T_
for a ‘CUST’ tag.The registered table class should be a subclass of
fontTools.ttLib.tables.DefaultTable.DefaultTable
- fontTools.ttLib.ttFont.unregisterCustomTableClass(tag)[source]
Unregister the custom packer/unpacker class for a table.
- fontTools.ttLib.ttFont.getCustomTableClass(tag)[source]
Return the custom table class for tag, if one has been registered with ‘registerCustomTableClass()’. Else return None.
- fontTools.ttLib.ttFont.tagToIdentifier(tag)[source]
Convert a table tag to a valid (but UGLY) python identifier, as well as a filename that’s guaranteed to be unique even on a caseless file system. Each character is mapped to two characters. Lowercase letters get an underscore before the letter, uppercase letters get an underscore after the letter. Trailing spaces are trimmed. Illegal characters are escaped as two hex bytes. If the result starts with a number (as the result of a hex escape), an extra underscore is prepended. Examples: .. code-block:: pycon
>>> >> tagToIdentifier('glyf') '_g_l_y_f' >> tagToIdentifier('cvt ') '_c_v_t' >> tagToIdentifier('OS/2') 'O_S_2f_2'
- fontTools.ttLib.ttFont.tagToXML(tag)[source]
Similarly to tagToIdentifier(), this converts a TT tag to a valid XML element name. Since XML element names are case sensitive, this is a fairly simple/readable translation.
- fontTools.ttLib.ttFont.sortedTagList(tagList, tableOrder=None)[source]
Return a sorted copy of tagList, sorted according to the OpenType specification, or according to a custom tableOrder. If given and not None, tableOrder needs to be a list of tag names.
- fontTools.ttLib.ttFont.reorderFontTables(inFile, outFile, tableOrder=None, checkChecksums=False)[source]
Rewrite a font file, ordering the tables as recommended by the OpenType specification 1.4.