• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#! /usr/bin/env python3
2
3# Example script to decompose the composite glyphs in a TTF into
4# non-composite outlines.
5
6
7import sys
8from fontTools.ttLib import TTFont
9from fontTools.pens.recordingPen import DecomposingRecordingPen
10from fontTools.pens.ttGlyphPen import TTGlyphPen
11
12try:
13    import pathops
14except ImportError:
15    sys.exit(
16        "This script requires the skia-pathops module. "
17        "`pip install skia-pathops` and then retry."
18    )
19
20
21if len(sys.argv) != 3:
22    print("usage: decompose-ttf.py fontfile.ttf outfile.ttf")
23    sys.exit(1)
24
25src = sys.argv[1]
26dst = sys.argv[2]
27
28with TTFont(src) as f:
29    glyfTable = f["glyf"]
30    glyphSet = f.getGlyphSet()
31
32    for glyphName in glyphSet.keys():
33        if not glyfTable[glyphName].isComposite():
34            continue
35
36        # record TTGlyph outlines without components
37        dcPen = DecomposingRecordingPen(glyphSet)
38        glyphSet[glyphName].draw(dcPen)
39
40        # replay recording onto a skia-pathops Path
41        path = pathops.Path()
42        pathPen = path.getPen()
43        dcPen.replay(pathPen)
44
45        # remove overlaps
46        path.simplify()
47
48        # create new TTGlyph from Path
49        ttPen = TTGlyphPen(None)
50        path.draw(ttPen)
51        glyfTable[glyphName] = ttPen.glyph()
52
53    f.save(dst)
54