# ttFont: Read and write font contents

## Overview

`ttLib.ttFont` is the primary fontTools interface for inspecting, constructing, or deconstructing TrueType and OpenType fonts.

The `fontTools.ttLib.ttFont.TTFont` class provides access to font-level data, including font metrics, substitution and positioning features, and metadata, through a set of table converters. A `TTFont` may be instantiated from a single font file, or it may be a member of a `TTCollection`. `TTFont` objects can also be constructed from scratch.

## glyphSets and ttGlyphs

In addition to font-wide data, `ttLib.ttFont` provides access to individual glyphs through a `TTFont` instance’s `.glyphSet[]` attribute. A `.glyphSet` is a dict-like object that is indexed by glyph names. Users can use the glyphSet to interact with each glyph’s contours, components, points, and glyph metrics.

Informally, some fontTools code or documentation will make reference to the individual glyphs in a `.glyphSet` as a “ttGlyph” or the like. This is convenient terminology, particularly for discussion. However, it is important to note that there is not a “ttGlyph” class. Instead, the `.glyphSet` attribute of a `TTFont` serves as an abstraction layer that provides a uniform interface to the glyphs, regardless of whether the `TTFont` instance in use comes from a font file with TrueType-flavored glyphs (and, therefore, has a glyf table containing glyph contours) or a font with PostScript-flavored outlines (and, therefore, with a `CFF` or `CFF2` table containing the glyph contours).

Regardless of the flavor, each “ttGlyph” entry in the `.glyphSet` includes the corresponding Bezier outlines and components from the `glyf` or `CFF`/`CFF2` table and the glyph’s metrics. Horizontal metrics are drawn from the font’s `hmtx` table, and vertical metrics (if any) are drawn from the `vmtx` table. These attributes are:

> width

>   The advance width of the glyph

> lsb

>   The left sidebearing of the glyph

> height

>   (For vertical-layout fonts) The advance height of the glyph

> tsb

>   (for vertical-layout fonts) The top sidebearing of the glyph

Note that these attributes do not describe the bounding box of the glyph filled shape, because the filled area might include negative coordinate values or extend beyond the advance width due to overhang.

The bounds of the glyph are accessible as `xMin`, `xMax`, `yMin`, and `yMax` attributes.

For implementation details regarding the different flavors of “ttGlyph”, see the ttGlyphSet documentation.

These glyph objects also implement the Pen Protocol by providing `.draw()` and `.drawPoints()` methods. See the pens package documenation for more.

## Package contents

class fontTools.ttLib.ttFont.TTFont(file: str | os.PathLike[str] | BinaryIO | None = None, res_name_or_index: str | int | None = None, sfntVersion: str = '\x00\x01\x00\x00', flavor: str | None = None, checkChecksums: int = 0, verbose: bool | None = None, recalcBBoxes: bool = True, allowVID: Any = NotImplemented, ignoreDecompileErrors: bool = False, recalcTimestamp: bool = True, fontNumber: int = -1, lazy: bool | None = None, quiet: bool | None = None, _tableCache: MutableMapping[tuple[Tag, bytes], DefaultTable] | None = None, cfg: Mapping[str, Any] | AbstractConfig = {})

  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:

      >>>
      >> 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 the tables documentation. To add a table to the font, use the `newTable()` function:

      >>>
      >> 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):

      >>
      >> 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, use `OTTO`.

    - flavor (str) – Set this to `woff` when creating a WOFF file or `woff2` 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 and `hhea`/`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 the `head` 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.

  glyphOrder: list[str]
  disassembleInstructions: bool
  bitmapGlyphDataFormat: str
  verbose: bool | None
  quiet: bool | None
  lazy: bool | None
  recalcBBoxes: bool
  recalcTimestamp: bool
  tables: dict[Tag, DefaultTable | GlyphOrder]
  cfg: AbstractConfig
  ignoreDecompileErrors: bool
  reader: SFNTReader | None
  sfntVersion: str
  flavor: str | None
  flavorData: Any | None
  close() → None

    If we still have a reader object, close it.

  save(file: str | os.PathLike[str] | BinaryIO, reorderTables: bool | None = True) → None

    Save the font to disk.

    Parameters:

      - file – Similarly to the constructor, can be either a pathname or a writable binary 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).

  class XMLSavingOptions

    Bases: `TypedDict`

    writeVersion: bool
    quiet: bool | None
    tables: Sequence[str | bytes] | None
    skipTables: Sequence[str] | None
    splitTables: bool
    splitGlyphs: bool
    disassembleInstructions: bool
    bitmapGlyphDataFormat: str
  saveXML(fileOrPath: str | os.PathLike[str] | BinaryIO | TextIO, newlinestr: str = '\n', **kwargs: Unpack[XMLSavingOptions]) → None

    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: str | os.PathLike[str] | BinaryIO, quiet: bool | None = None) → None

    Import a TTX file (an XML-based text format), so as to recreate a font object.

  isLoaded(tag: str | bytes) → bool

    Return true if the table identified by `tag` has been decompiled and loaded into memory.

  has_key(tag: str | bytes) → bool

    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.

  keys() → list[str]

    Returns the list of tables in the font, along with the `GlyphOrder` pseudo-table.

  ensureDecompiled(recurse: bool | None = None) → None

    Decompile all the tables, even if a TTFont was opened in ‘lazy’ mode.

  get(tag: Literal['BASE']) → B_A_S_E_.table_B_A_S_E_ | None
  get(tag: Literal['CBDT']) → C_B_D_T_.table_C_B_D_T_ | None
  get(tag: Literal['CBLC']) → C_B_L_C_.table_C_B_L_C_ | None
  get(tag: Literal['CFF ']) → C_F_F_.table_C_F_F_ | None
  get(tag: Literal['CFF2']) → C_F_F__2.table_C_F_F__2 | None
  get(tag: Literal['COLR']) → C_O_L_R_.table_C_O_L_R_ | None
  get(tag: Literal['CPAL']) → C_P_A_L_.table_C_P_A_L_ | None
  get(tag: Literal['DSIG']) → D_S_I_G_.table_D_S_I_G_ | None
  get(tag: Literal['EBDT']) → E_B_D_T_.table_E_B_D_T_ | None
  get(tag: Literal['EBLC']) → E_B_L_C_.table_E_B_L_C_ | None
  get(tag: Literal['FFTM']) → F_F_T_M_.table_F_F_T_M_ | None
  get(tag: Literal['GDEF']) → G_D_E_F_.table_G_D_E_F_ | None
  get(tag: Literal['GMAP']) → G_M_A_P_.table_G_M_A_P_ | None
  get(tag: Literal['GPKG']) → G_P_K_G_.table_G_P_K_G_ | None
  get(tag: Literal['GPOS']) → G_P_O_S_.table_G_P_O_S_ | None
  get(tag: Literal['GSUB']) → G_S_U_B_.table_G_S_U_B_ | None
  get(tag: Literal['GVAR']) → G_V_A_R_.table_G_V_A_R_ | None
  get(tag: Literal['HVAR']) → H_V_A_R_.table_H_V_A_R_ | None
  get(tag: Literal['JSTF']) → J_S_T_F_.table_J_S_T_F_ | None
  get(tag: Literal['LTSH']) → L_T_S_H_.table_L_T_S_H_ | None
  get(tag: Literal['MATH']) → M_A_T_H_.table_M_A_T_H_ | None
  get(tag: Literal['META']) → M_E_T_A_.table_M_E_T_A_ | None
  get(tag: Literal['MVAR']) → M_V_A_R_.table_M_V_A_R_ | None
  get(tag: Literal['SING']) → S_I_N_G_.table_S_I_N_G_ | None
  get(tag: Literal['STAT']) → S_T_A_T_.table_S_T_A_T_ | None
  get(tag: Literal['SVG ']) → S_V_G_.table_S_V_G_ | None
  get(tag: Literal['TSI0']) → T_S_I__0.table_T_S_I__0 | None
  get(tag: Literal['TSI1']) → T_S_I__1.table_T_S_I__1 | None
  get(tag: Literal['TSI2']) → T_S_I__2.table_T_S_I__2 | None
  get(tag: Literal['TSI3']) → T_S_I__3.table_T_S_I__3 | None
  get(tag: Literal['TSI5']) → T_S_I__5.table_T_S_I__5 | None
  get(tag: Literal['TSIB']) → T_S_I_B_.table_T_S_I_B_ | None
  get(tag: Literal['TSIC']) → T_S_I_C_.table_T_S_I_C_ | None
  get(tag: Literal['TSID']) → T_S_I_D_.table_T_S_I_D_ | None
  get(tag: Literal['TSIJ']) → T_S_I_J_.table_T_S_I_J_ | None
  get(tag: Literal['TSIP']) → T_S_I_P_.table_T_S_I_P_ | None
  get(tag: Literal['TSIS']) → T_S_I_S_.table_T_S_I_S_ | None
  get(tag: Literal['TSIV']) → T_S_I_V_.table_T_S_I_V_ | None
  get(tag: Literal['TTFA']) → T_T_F_A_.table_T_T_F_A_ | None
  get(tag: Literal['VARC']) → V_A_R_C_.table_V_A_R_C_ | None
  get(tag: Literal['VDMX']) → V_D_M_X_.table_V_D_M_X_ | None
  get(tag: Literal['VORG']) → V_O_R_G_.table_V_O_R_G_ | None
  get(tag: Literal['VVAR']) → V_V_A_R_.table_V_V_A_R_ | None
  get(tag: Literal['Debg']) → D__e_b_g.table_D__e_b_g | None
  get(tag: Literal['Feat']) → F__e_a_t.table_F__e_a_t | None
  get(tag: Literal['Glat']) → G__l_a_t.table_G__l_a_t | None
  get(tag: Literal['Gloc']) → G__l_o_c.table_G__l_o_c | None
  get(tag: Literal['OS/2']) → O_S_2f_2.table_O_S_2f_2 | None
  get(tag: Literal['Silf']) → S__i_l_f.table_S__i_l_f | None
  get(tag: Literal['Sill']) → S__i_l_l.table_S__i_l_l | None
  get(tag: Literal['ankr']) → _a_n_k_r.table__a_n_k_r | None
  get(tag: Literal['avar']) → _a_v_a_r.table__a_v_a_r | None
  get(tag: Literal['bsln']) → _b_s_l_n.table__b_s_l_n | None
  get(tag: Literal['cidg']) → _c_i_d_g.table__c_i_d_g | None
  get(tag: Literal['cmap']) → _c_m_a_p.table__c_m_a_p | None
  get(tag: Literal['cvar']) → _c_v_a_r.table__c_v_a_r | None
  get(tag: Literal['cvt ']) → _c_v_t.table__c_v_t | None
  get(tag: Literal['feat']) → _f_e_a_t.table__f_e_a_t | None
  get(tag: Literal['fpgm']) → _f_p_g_m.table__f_p_g_m | None
  get(tag: Literal['fvar']) → _f_v_a_r.table__f_v_a_r | None
  get(tag: Literal['gasp']) → _g_a_s_p.table__g_a_s_p | None
  get(tag: Literal['gcid']) → _g_c_i_d.table__g_c_i_d | None
  get(tag: Literal['glyf']) → _g_l_y_f.table__g_l_y_f | None
  get(tag: Literal['gvar']) → _g_v_a_r.table__g_v_a_r | None
  get(tag: Literal['hdmx']) → _h_d_m_x.table__h_d_m_x | None
  get(tag: Literal['head']) → _h_e_a_d.table__h_e_a_d | None
  get(tag: Literal['hhea']) → _h_h_e_a.table__h_h_e_a | None
  get(tag: Literal['hmtx']) → _h_m_t_x.table__h_m_t_x | None
  get(tag: Literal['kern']) → _k_e_r_n.table__k_e_r_n | None
  get(tag: Literal['lcar']) → _l_c_a_r.table__l_c_a_r | None
  get(tag: Literal['loca']) → _l_o_c_a.table__l_o_c_a | None
  get(tag: Literal['ltag']) → _l_t_a_g.table__l_t_a_g | None
  get(tag: Literal['maxp']) → _m_a_x_p.table__m_a_x_p | None
  get(tag: Literal['meta']) → _m_e_t_a.table__m_e_t_a | None
  get(tag: Literal['mort']) → _m_o_r_t.table__m_o_r_t | None
  get(tag: Literal['morx']) → _m_o_r_x.table__m_o_r_x | None
  get(tag: Literal['name']) → _n_a_m_e.table__n_a_m_e | None
  get(tag: Literal['opbd']) → _o_p_b_d.table__o_p_b_d | None
  get(tag: Literal['post']) → _p_o_s_t.table__p_o_s_t | None
  get(tag: Literal['prep']) → _p_r_e_p.table__p_r_e_p | None
  get(tag: Literal['prop']) → _p_r_o_p.table__p_r_o_p | None
  get(tag: Literal['sbix']) → _s_b_i_x.table__s_b_i_x | None
  get(tag: Literal['trak']) → _t_r_a_k.table__t_r_a_k | None
  get(tag: Literal['vhea']) → _v_h_e_a.table__v_h_e_a | None
  get(tag: Literal['vmtx']) → _v_m_t_x.table__v_m_t_x | None
  get(tag: Literal['GlyphOrder']) → GlyphOrder
  get(tag: str | bytes) → DefaultTable | GlyphOrder | Any | None
  get(tag: str | bytes, default: _VT_co) → DefaultTable | GlyphOrder | Any | _VT_co

    Returns the table if it exists or (optionally) a default if it doesn’t.

  setGlyphOrder(glyphOrder: list[str]) → None

    Set the glyph order

    Parameters:

      glyphOrder ([str]) – List of glyph names in order.

  getGlyphOrder() → list[str]

    Returns a list of glyph names ordered by their position in the font.

  getGlyphNames() → list[str]

    Get a list of glyph names, sorted alphabetically.

  getGlyphNames2() → list[str]

    Get a list of glyph names, sorted alphabetically, but not case sensitive.

  getGlyphName(glyphID: int) → str

    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.

  getGlyphNameMany(lst: Sequence[int]) → list[str]

    Converts a list of glyph IDs into a list of glyph names.

  getGlyphID(glyphName: str) → int

    Returns the ID of the glyph with the given name.

  getGlyphIDMany(lst: Sequence[str]) → list[int]

    Converts a list of glyph names into a list of glyph IDs.

  getReverseGlyphMap(rebuild: bool = False) → dict[str, int]

    Returns a mapping of glyph names to glyph IDs.

  getTableData(tag: str | bytes) → bytes

    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: bool = True, location: Mapping[str, _NumberT] | None = None, normalized: bool = False, recalcBounds: bool = True) → _TTGlyphSet

    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 the `glyf` table.

    If the font contains both a `CFF ``/``CFF2` and a `glyf` table, you can use the `preferCFF` argument to specify which one should be taken. If the font contains both a `CFF `` 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: Mapping[str, float]) → dict[str, float]

    Normalize a `location` from the font’s defined axes space (also known as user space) into the normalized (-1..+1) space. It applies `avar` mapping if the font contains an `avar` 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: Sequence[tuple[int, int]] = ((3, 10), (0, 6), (0, 4), (3, 1), (0, 3), (0, 2), (0, 1), (0, 0))) → dict[int, str] | None

    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.

  reorderGlyphs(new_glyph_order: list[str]) → None

class fontTools.ttLib.ttFont.GlyphOrder(tag: str | None = None)

  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.

  toXML(writer: XMLWriter, ttFont: TTFont) → None
  fromXML(name: str, attrs: dict[str, str], content: list[Any], ttFont: TTFont) → None

fontTools.ttLib.ttFont.getTableModule(tag: str | bytes) → ModuleType | None

  Fetch the packer/unpacker module for a table. Return None when no module is found.

fontTools.ttLib.ttFont.registerCustomTableClass(tag: str | bytes, moduleName: str, className: str | None = None) → None

  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: str | bytes) → None

  Unregister the custom packer/unpacker class for a table.

fontTools.ttLib.ttFont.getCustomTableClass(tag: str | bytes) → type[DefaultTable] | None

  Return the custom table class for tag, if one has been registered with ‘registerCustomTableClass()’. Else return None.

fontTools.ttLib.ttFont.getTableClass(tag: str | bytes) → type[DefaultTable]

  Fetch the packer/unpacker class for a table.

fontTools.ttLib.ttFont.getClassTag(klass: type[DefaultTable]) → str | bytes

  Fetch the table tag for a class object.

fontTools.ttLib.ttFont.newTable(tag: str | bytes) → DefaultTable

  Return a new instance of a table.

fontTools.ttLib.ttFont.tagToIdentifier(tag: str | bytes) → str

  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.identifierToTag(ident: str) → str

  the opposite of tagToIdentifier()

fontTools.ttLib.ttFont.tagToXML(tag: str | bytes) → str

  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.xmlToTag(tag: str) → str

  The opposite of tagToXML()

fontTools.ttLib.ttFont.sortedTagList(tagList: Sequence[str], tableOrder: Sequence[str] | None = None) → list[str]

  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: BinaryIO, outFile: BinaryIO, tableOrder: Sequence[str] | None = None, checkChecksums: bool = False) → None

  Rewrite a font file, ordering the tables as recommended by the OpenType specification 1.4.

fontTools.ttLib.ttFont.maxPowerOfTwo(x: int) → int

  Return the highest exponent of two, so that (2 ** exponent) <= x. Return 0 if x is 0.

fontTools.ttLib.ttFont.getSearchRange(n: int, itemSize: int = 16) → tuple[int, int, int]

  Calculate searchRange, entrySelector, rangeShift.