svg2ttf.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/fontforge -script
  2. import sys
  3. import os.path
  4. import json
  5. import fontforge
  6. IMPORT_OPTIONS = ('removeoverlap', 'correctdir')
  7. try:
  8. unicode
  9. except NameError:
  10. unicode = str
  11. def loadConfig(filename='font.json'):
  12. with open(filename) as f:
  13. return json.load(f)
  14. def setProperties(font, config):
  15. props = config['props']
  16. lang = props.pop('lang', 'English (US)')
  17. family = props.pop('family', None)
  18. style = props.pop('style', 'Regular')
  19. props['encoding'] = props.get('encoding', 'UnicodeFull')
  20. if family is not None:
  21. font.familyname = family
  22. font.fontname = family + '-' + style
  23. font.fullname = family + ' ' + style
  24. for k, v in config['props'].items():
  25. if hasattr(font, k):
  26. if isinstance(v, list):
  27. v = tuple(v)
  28. setattr(font, k, v)
  29. else:
  30. font.appendSFNTName(lang, k, v)
  31. for t in config.get('sfnt_names', []):
  32. font.appendSFNTName(str(t[0]), str(t[1]), unicode(t[2]))
  33. def addGlyphs(font, config):
  34. for k, v in config['glyphs'].items():
  35. g = font.createMappedChar(int(k, 0))
  36. # Get outlines
  37. src = '%s.svg' % k
  38. if not isinstance(v, dict):
  39. v = {'src': v or src}
  40. src = '%s%s%s' % (config.get('input', '.'),
  41. os.path.sep, v.pop('src', src))
  42. g.importOutlines(src, IMPORT_OPTIONS)
  43. g.removeOverlap()
  44. # Copy attributes
  45. for k2, v2 in v.items():
  46. if hasattr(g, k2):
  47. if isinstance(v2, list):
  48. v2 = tuple(v2)
  49. setattr(g, k2, v2)
  50. def main(config_file):
  51. config = loadConfig(config_file)
  52. os.chdir(os.path.dirname(config_file) or '.')
  53. font = fontforge.font()
  54. setProperties(font, config)
  55. addGlyphs(font, config)
  56. for outfile in config['output']:
  57. sys.stderr.write('Generating %s...\n' % outfile)
  58. font.generate(outfile)
  59. if __name__ == '__main__':
  60. if len(sys.argv) > 1:
  61. main(sys.argv[1])
  62. else:
  63. sys.stderr.write("\nUsage: %s something.json\n" % sys.argv[0])