user2588654 - 9 months ago 58
Python Question

# Retrieving bounding box and bezier curve data for all glyphs in a .ttf font file in python

I am interested in extracting the quadratic bezier curve information of all glyphs in a given ttf file. Currently, using the ttfquery library in python, I am able to extract the contours of a given glyph (such as

a
) in the following manner:

from ttfquery import describe
from ttfquery import glyphquery
import ttfquery.glyph as glyph

char = "a"
font_url = "/usr/share/fonts/truetype/liberation/LiberationSerif-Regular.ttf"
font = describe.openFont(font_url)
g = glyph.Glyph(char)
contours = g.calculateContours(font)
for contour in contours:
for point, flag in contour:
print point, flag


This works well for alphabetical characters, but it provides the following key error for numbers, punctuation, spaces, etc:

Traceback (most recent call last):
File "demo.py", line 9, in <module>
contours = g.calculateContours(font)
File "/usr/local/lib/python2.7/dist-packages/ttfquery/glyph.py", line 33, in calculateContours
charglyf = glyf[self.glyphName]
File "/usr/local/lib/python2.7/dist-packages/FontTools/fontTools/ttLib/tables/_g_l_y_f.py", line 185, in __getitem__
glyph = self.glyphs[glyphName]
KeyError: '!'


What is a reliable way get both the the bezier curve points as well as the bounding box of each glyph (which I am currently calculating indirectly using the min and max x and y values retrieved from the contours)?

Glyphs are not necessarily named after a character. There is a structure in a TTF file though that maps characters to glyphs, the cmap. ttyquery has an API to access that map:

>>> ttfquery.glyphquery.glyphName(font, "!")
"exclam"


That is, replace

g = glyph.Glyph(char)


with

g = glyph.Glyph(ttfquery.glyphquery.glyphName(f, char))