Retrieve Unicode Values in FontForge with Python
FontForge includes a native Python scripting module that allows you
to inspect, modify, and automate font generation tasks. When working
with glyph metadata, you can easily inspect character encodings through
specific glyph attributes. This guide explains how to open a font file,
iterate over its glyphs, and retrieve both primary and multiple Unicode
values using the fontforge Python library.
Accessing Glyph Unicode Attributes
When a font is loaded via the fontforge module, each
glyph is represented as a glyph object. FontForge provides
two main attributes for accessing Unicode values:
glyph.unicode: Returns the primary Unicode encoding point as an integer. If the glyph has no assigned Unicode code point, it returns-1.glyph.unicodes: Returns a tuple of all Unicode code points assigned to the glyph (useful for glyphs mapped to multiple codepoints).
Python Script Example
The following script opens a font file, iterates over every glyph,
and prints both the glyph name and its corresponding Unicode code points
in standard hexadecimal notation (U+XXXX).
import fontforge
# Open the font file
font = fontforge.open("path/to/font.ttf")
for glyph in font.glyphs():
# Check if the glyph has a valid Unicode encoding
if glyph.unicode != -1:
# Convert decimal integer to hexadecimal Unicode representation
hex_unicode = f"U+{glyph.unicode:04X}"
char_repr = chr(glyph.unicode)
# Check for multiple codepoints mapped to the same glyph
all_unicodes = [f"U+{u:04X}" for u in glyph.unicodes]
print(f"Glyph Name: {glyph.glyphname}")
print(f" Primary Codepoint: {hex_unicode} ({char_repr})")
print(f" All Codepoints: {', '.join(all_unicodes)}")
else:
print(f"Glyph Name: {glyph.glyphname} (No Unicode assigned)")
# Close the font to free memory
font.close()Retrieving a Specific Glyph by Name or Unicode
If you do not need to iterate through the entire font, you can access a glyph directly by indexing the font object using its name or decimal Unicode value:
import fontforge
font = fontforge.open("path/to/font.ttf")
# Access by glyph name
glyph_by_name = font["A"]
print(f"'A' Unicode: U+{glyph_by_name.unicode:04X}")
# Access by decimal Unicode value (65 corresponds to 'A')
glyph_by_code = font[65]
print(f"Codepoint 65 Name: {glyph_by_code.glyphname}")
font.close()