Skip to content

Instantly share code, notes, and snippets.

@taskie
Created March 28, 2016 09:28
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save taskie/a7c7897479a90b975147 to your computer and use it in GitHub Desktop.
Save taskie/a7c7897479a90b975147 to your computer and use it in GitHub Desktop.
fontforge script to generate subsets of fonts
#!/usr/bin/env fontforge -lang=py -script
# -*- coding: utf-8 -*-
import fontforge
import sys
import os
def _select_codepoint(codepoint, selection, more=True):
more_str = 'more' if more else 'less'
if isinstance(codepoint, tuple) and len(codepoint) == 2:
first, last = codepoint
if isinstance(first, int) and isinstance(last, int):
selection.select((more_str, 'ranges', 'unicode'), first, last)
elif isinstance(first, unicode) and isinstance(last, unicode):
selection.select((more_str, 'ranges', 'unicode'), ord(first), ord(last))
else:
message = 'invalid codepoint type: ' + str(codepoint)
raise Exception(message)
elif isinstance(codepoint, int):
selection.select((more_str, 'unicode'), codepoint)
elif isinstance(codepoint, unicode):
for c in codepoint:
selection.select((more_str, 'unicode'), ord(c))
else:
message = 'invalid codepoint type: ' + str(codepoint)
raise Exception(message)
def _clear_unneeded_glyphs(font, codepoints):
font.selection.all()
for codepoint in codepoints:
_select_codepoint(codepoint, font.selection, more=False)
font.clear()
def generate_webfonts(input, outdir, codepoints):
if not os.path.exists(outdir):
os.mkdir(outdir)
if not os.path.isdir(outdir):
message = 'last argument is not directory: ' + outdir
raise Exception(message)
font = fontforge.open(input)
_clear_unneeded_glyphs(font, codepoints)
filename = os.path.split(input)[-1]
basename, ext = os.path.splitext(filename)
for newext in [ext, '.woff', '.eot']:
output = os.path.join(outdir, basename + newext)
font.generate(output)
font.close()
if __name__ == '__main__':
codepoints = [(0x0000, 0x03FF), (0x2200, 0x22FF)]
if len(sys.argv) > 2:
for input in sys.argv[1:-1]:
generate_webfonts(input, sys.argv[-1], codepoints)
else:
print('usage: ' + sys.argv[0] + ' inputs... outdir')
exit(1)
@saqib-ahmed
Copy link

Wow. Just what I was looking for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment