user2588654 user2588654 -4 years ago 209
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

) 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 "", line 9, in <module>
contours = g.calculateContours(font)
File "/usr/local/lib/python2.7/dist-packages/ttfquery/", line 33, in calculateContours
charglyf = glyf[self.glyphName]
File "/usr/local/lib/python2.7/dist-packages/FontTools/fontTools/ttLib/tables/", 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)?

Answer Source

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, "!")

That is, replace

g = glyph.Glyph(char)


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

and your code should work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download