Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
fontTools
https://fonttools.readthedocs.io/en/latest/
Admin
fontTools is a family of libraries and utilities for manipulating fonts in Python.
Tokens:
1,076,407
Snippets:
4,188
Trust Score:
9.6
Update:
1 month ago
Context
Chat
Benchmark
57.5
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Initialize subsetter options Source: https://fonttools.readthedocs.io/en/latest/_modules/fontTools/subset.html The __init__ method sets default configuration values for the subsetting process, including table handling, glyph retention, and font metadata recalculation. ```python def __init__(self, **kwargs): self.drop_tables = self._drop_tables_default[:] self.no_subset_tables = self._no_subset_tables_default[:] self.passthrough_tables = False # keep/drop tables we can't subset self.hinting_tables = self._hinting_tables_default[:] self.legacy_kern = False # drop 'kern' table if GPOS available self.layout_closure = True self.layout_features = self._layout_features_default[:] self.layout_scripts = ["*"] self.ignore_missing_glyphs = False self.ignore_missing_unicodes = True self.hinting = True self.glyph_names = False self.legacy_cmap = False self.symbol_cmap = False self.name_IDs = [ 0, 1, 2, 3, 4, 5, 6, ] # https://github.com/fonttools/fonttools/issues/1170#issuecomment-364631225 self.name_legacy = False self.name_languages = [0x0409] # English self.obfuscate_names = False # to make webfont unusable as a system font self.retain_gids = False self.notdef_glyph = True # gid0 for TrueType / .notdef for CFF self.notdef_outline = False # No need for notdef to have an outline really self.recommended_glyphs = False # gid1, gid2, gid3 for TrueType self.recalc_bounds = False # Recalculate font bounding boxes self.recalc_timestamp = False # Recalculate font modified timestamp self.prune_unicode_ranges = True # Clear unused 'ulUnicodeRange' bits self.prune_codepage_ranges = True # Clear unused 'ulCodePageRange' bits self.recalc_average_width = False # update 'xAvgCharWidth' self.recalc_max_context = False # update 'usMaxContext' self.canonical_order = None # Order tables as recommended self.flavor = None # May be 'woff' or 'woff2' self.with_zopfli = False # use zopfli instead of zlib for WOFF 1.0 self.desubroutinize = False # Desubroutinize CFF CharStrings self.harfbuzz_repacker = USE_HARFBUZZ_REPACKER.default self.verbose = False self.timing = False self.xml = False self.font_number = -1 self.pretty_svg = False self.lazy = True self.bidi_closure = True self.set(**kwargs) ``` -------------------------------- ### Build Multiple Substitution Subtable Source: https://fonttools.readthedocs.io/en/latest/otlLib/index.html Example of using buildMultipleSubstSubtable to map input glyphs to a list of output glyphs. ```python # sub uni06C0 by uni06D5.fina hamza.above # sub uni06C2 by uni06C1.fina hamza.above; subtable = buildMultipleSubstSubtable({ "uni06C0": [ "uni06D5.fina", "hamza.above"], "uni06C2": [ "uni06D1.fina", "hamza.above"] }) ``` -------------------------------- ### main function Source: https://fonttools.readthedocs.io/en/latest/_modules/fontTools/subset.html The main entry point for the OpenType font subsetter and optimizer. ```python @timer("make one with everything (TOTAL TIME)") def main(args=None): """OpenType font subsetter and optimizer""" from os.path import splitext from fontTools import configLogger if args is None: args = sys.argv[1:] if "--help" in args: print(__doc__) return 0 options = Options() try: args = options.parse_opts( args, ignore_unknown=[ "gids", "gids-file", "glyphs", "glyphs-file", "text", "text-file", "unicodes", "unicodes-file", "output-file", ], ) except options.OptionError as e: usage() print("ERROR:", e, file=sys.stderr) return 2 if len(args) < 2: usage() return 1 configLogger(level=logging.INFO if options.verbose else logging.WARNING) if options.timing: timer.logger.setLevel(logging.DEBUG) else: timer.logger.disabled = True fontfile = args[0] args = args[1:] subsetter = Subsetter(options=options) outfile = None glyphs = [] gids = [] unicodes = [] wildcard_glyphs = False wildcard_unicodes = False text = "" for g in args: if g == "*": wildcard_glyphs = True continue if g.startswith("--output-file="): outfile = g[14:] continue if g.startswith("--text="): text += g[7:] continue if g.startswith("--text-file="): with open(g[12:], encoding="utf-8-sig") as f: text += f.read().replace("\n", "") continue if g.startswith("--unicodes="): if g[11:] == "*": wildcard_unicodes = True else: unicodes.extend(parse_unicodes(g[11:])) continue if g.startswith("--unicodes-file="): with open(g[16:]) as f: for line in f.readlines(): unicodes.extend(parse_unicodes(line.split("#")[0])) continue if g.startswith("--gids="): gids.extend(parse_gids(g[7:])) continue if g.startswith("--gids-file="): with open(g[12:]) as f: for line in f.readlines(): gids.extend(parse_gids(line.split("#")[0])) continue if g.startswith("--glyphs="): if g[9:] == "*": wildcard_glyphs = True else: glyphs.extend(parse_glyphs(g[9:])) continue if g.startswith("--glyphs-file="): with open(g[14:]) as f: for line in f.readlines(): glyphs.extend(parse_glyphs(line.split("#")[0])) continue glyphs.append(g) dontLoadGlyphNames = not options.glyph_names and not glyphs lazy = options.lazy font = load_font( fontfile, options, dontLoadGlyphNames=dontLoadGlyphNames, lazy=lazy ) if outfile is None: ext = "." + options.flavor.lower() if options.flavor is not None else None outfile = makeOutputFileName( fontfile, extension=ext, overWrite=True, suffix=".subset" ) with timer("compile glyph list"): if wildcard_glyphs: glyphs.extend(font.getGlyphOrder()) if wildcard_unicodes: for t in font["cmap"].tables: if t.isUnicode(): unicodes.extend(t.cmap.keys()) if t.format == 14: unicodes.extend(t.uvsDict.keys()) assert "" not in glyphs log.info("Text: '%s'" % text) log.info("Unicodes: %s", unicodes) log.info("Glyphs: %s", glyphs) log.info("Gids: %s", gids) subsetter.populate(glyphs=glyphs, gids=gids, unicodes=unicodes, text=text) subsetter.subset(font) save_font(font, outfile, options) if options.verbose: import os log.info("Input font:% 7d bytes: %s" % (os.path.getsize(fontfile), fontfile)) log.info("Subset font:% 7d bytes: %s" % (os.path.getsize(outfile), outfile)) if options.xml: font.saveXML(sys.stdout) font.close() ``` -------------------------------- ### Build Ligature Substitution Subtable Source: https://fonttools.readthedocs.io/en/latest/otlLib/index.html Example of using buildLigatureSubstSubtable to map tuples of input glyphs to a single output ligature glyph. ```python # sub f f i by f_f_i; # sub f i by f_i; subtable = buildLigatureSubstSubtable({ ("f", "f", "i"): "f_f_i", ("f", "i"): "f_i", }) ``` -------------------------------- ### fontTools.otlLib.builder.buildDevice Source: https://fonttools.readthedocs.io/en/latest/otlLib/index.html Builds a Device record for size-specific adjustments. ```APIDOC ## fontTools.otlLib.builder.buildDevice(deltas) ### Description Builds a Device record specifying size-specific adjustments to value records and anchors. ### Parameters - **deltas** (dict) - Required - A dictionary mapping pixels-per-em sizes to the delta adjustment in pixels. ### Returns - **otTables.Device** - The constructed device record object, or None if no deltas are supplied. ``` -------------------------------- ### populate method Source: https://fonttools.readthedocs.io/en/latest/_modules/fontTools/subset.html Populates the requested glyphs and unicodes for subsetting. ```python def populate(self, glyphs=[], gids=[], unicodes=[], text=""): self.unicodes_requested.update(unicodes) if isinstance(text, bytes): text = text.decode("utf_8") text_utf32 = text.encode("utf-32-be") nchars = len(text_utf32) // 4 for u in struct.unpack(">%dL" % nchars, text_utf32): self.unicodes_requested.add(u) self.glyph_names_requested.update(glyphs) self.glyph_ids_requested.update(gids) ``` -------------------------------- ### Main Execution Function for Variable Font Instantiation Source: https://fonttools.readthedocs.io/en/latest/_modules/fontTools/varLib/instancer.html The main entry point that loads the variable font and applies the instantiation process based on parsed arguments. ```python [docs] def main(args=None): """Partially instantiate a variable font""" infile, axisLimits, options = parseArgs(args) log.info("Restricting axes: %s", axisLimits) log.info("Loading variable font") varfont = TTFont( infile, recalcTimestamp=options.recalc_timestamp, recalcBBoxes=options.recalc_bounds, ) isFullInstance = options.static or { axisTag for axisTag, limit in axisLimits.items() if limit is None or limit[0] == limit[2] }.issuperset(axis.axisTag for axis in varfont["fvar"].axes) varfont = instantiateVariableFont( varfont, axisLimits, inplace=True, optimize=options.optimize, overlap=options.overlap, updateFontNames=options.update_name_table, downgradeCFF2=options.downgrade_cff2, static=options.static, ) ``` -------------------------------- ### writeLib(libDict, validate=None) Source: https://fonttools.readthedocs.io/en/latest/_modules/fontTools/ufoLib.html Writes the lib.plist file for the UFO. Requires a dictionary containing the library data. ```APIDOC ## writeLib(libDict, validate=None) ### Description Writes the lib.plist file. This method requires a lib dictionary as an argument. ### Parameters - **libDict** (LibDict) - Required - The dictionary containing library data. - **validate** (bool) - Optional - Whether to validate the data structure. Defaults to the class's validate value. ``` -------------------------------- ### fontTools.otlLib.builder.buildMarkLigPosSubtable Source: https://fonttools.readthedocs.io/en/latest/otlLib/index.html Builds a single MarkLigPos (GPOS5) subtable. ```APIDOC ## fontTools.otlLib.builder.buildMarkLigPosSubtable(marks, ligs, glyphMap) ### Description Builds a mark-to-ligature lookup subtable. ### Parameters - **marks** (dict) - Required - Mapping of glyph names to mark class and anchor. - **ligs** (dict) - Required - Mapping of ligature names to arrays of anchor dictionaries. - **glyphMap** (dict) - Required - A glyph name to ID map. ### Returns - **otTables.MarkLigPos** - The constructed subtable object. ```