Removing Unused Glyphs of a Font

Dec. 7, 2015, 11:38 a.m. Programming Simple Tools

As you might have know, CJK fonts are huge in size. If the characters to be used are known, the file size of the font file can be greatly reduced by removing the unused glyphs.

I'll probably encounter this issue when I use HaxeFlixel to display CJK characters in my next project. Then I Googled for a solution. Unfortunately, there is no such thing searchable in Google.

That's why I've written the script below with the use of FontForge:

#!/usr/bin/python2
import sys
import fontforge

if len(sys.argv) == 4:
    font = fontforge.open(sys.argv[1])

    f = open(sys.argv[2], "r")

    for i in f.read().decode("UTF-8"):
        font.selection[ord(i)] = True
    f.close()

    font.selection.invert()

    for i in font.selection.byGlyphs:
        font.removeGlyph(i)

    font.generate(sys.argv[3])
else:
    print "WARNING: Check the license of the source font\nbefore distributing the output font generated by this script.\nI'm not responsible for any legal issue caused by\ninappropriate use of this script!\n"
    print "Usage: {} [source font] [file with glyphs NOT to be removed] [output]".format(sys.argv[0])
    print "Example: {} /path/to/ukai.ttc chineseTranslation.txt ukaiStripped.ttf".format(sys.argv[0])

Mind you, ensure to check the license of the source font. It may not be legal to use this script under certain condition with certain source fonts. I'm not responsible for any legal issue cause by fonts generated with this script.

I've also posted this code to stackoverflow. Hopefully the internet would find it useful!


Comments