xref: /aosp_15_r20/external/fonttools/Snippets/cmap-format.py (revision e1fe3e4ad2793916b15cccdc4a7da52a7e1dd0e9)
1#! /usr/bin/env python3
2
3# Sample script to convert legacy cmap subtables to format-4
4# subtables.  Note that this is rarely what one needs.  You
5# probably need to just drop the legacy subtables if the font
6# already has a format-4 subtable.
7#
8# Other times, you would need to convert a non-Unicode cmap
9# legacy subtable to a Unicode one.  In those cases, use the
10# getEncoding() of subtable and use that encoding to map the
11# characters to Unicode...  TODO: Extend this script to do that.
12
13from fontTools.ttLib import TTFont
14from fontTools.ttLib.tables._c_m_a_p import CmapSubtable
15import sys
16
17if len(sys.argv) != 3:
18    print("usage: cmap-format.py fontfile.ttf outfile.ttf")
19    sys.exit(1)
20fontfile = sys.argv[1]
21outfile = sys.argv[2]
22font = TTFont(fontfile)
23
24cmap = font["cmap"]
25outtables = []
26for table in cmap.tables:
27    if table.format in [4, 12, 13, 14]:
28        outtables.append(table)
29    # Convert ot format4
30    newtable = CmapSubtable.newSubtable(4)
31    newtable.platformID = table.platformID
32    newtable.platEncID = table.platEncID
33    newtable.language = table.language
34    newtable.cmap = table.cmap
35    outtables.append(newtable)
36cmap.tables = outtables
37
38font.save(outfile)
39