# 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=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={})

  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.

  close()

    If we still have a reader object, close it.

  save(file, reorderTables=True)

    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)

    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)

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

  isLoaded(tag)

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

  has_key(tag)

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

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

  ensureDecompiled(recurse=None)

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

  get(tag, default=None)

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

  setGlyphOrder(glyphOrder)

    Set the glyph order

    Parameters:

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

  getGlyphOrder()

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

  getGlyphNames()

    Get a list of glyph names, sorted alphabetically.

  getGlyphNames2()

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

  getGlyphName(glyphID)

    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)

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

  getGlyphID(glyphName)

    Returns the ID of the glyph with the given name.

  getGlyphIDMany(lst)

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

  getReverseGlyphMap(rebuild=False)

    Returns a mapping of glyph names to glyph IDs.

  getTableData(tag)

    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)

    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)

    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=((3, 10), (0, 6), (0, 4), (3, 1), (0, 3), (0, 2), (0, 1), (0, 0)))

    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)

class fontTools.ttLib.ttFont.GlyphOrder(tag=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, ttFont)
  fromXML(name, attrs, content, ttFont)

fontTools.ttLib.ttFont.getTableModule(tag)

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

fontTools.ttLib.ttFont.registerCustomTableClass(tag, moduleName, className=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)

  Unregister the custom packer/unpacker class for a table.

fontTools.ttLib.ttFont.getCustomTableClass(tag)

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

fontTools.ttLib.ttFont.getTableClass(tag)

  Fetch the packer/unpacker class for a table.

fontTools.ttLib.ttFont.getClassTag(klass)

  Fetch the table tag for a class object.

fontTools.ttLib.ttFont.newTable(tag)

  Return a new instance of a table.

fontTools.ttLib.ttFont.tagToIdentifier(tag)

  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)

  the opposite of tagToIdentifier()

fontTools.ttLib.ttFont.tagToXML(tag)

  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)

  The opposite of tagToXML()

fontTools.ttLib.ttFont.sortedTagList(tagList, tableOrder=None)

  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)

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

fontTools.ttLib.ttFont.maxPowerOfTwo(x)

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

fontTools.ttLib.ttFont.getSearchRange(n, itemSize=16)

  Calculate searchRange, entrySelector, rangeShift.