How to Work with Font Tables in Python

How to Work with Font Tables in Python

This guide shows how to read named TTF tables, retrieve raw binary table bytes, and write modified table data using TtfFont in Aspose.Font FOSS for Python. TrueType fonts store all data in binary tables identified by 4-character tags. Aspose.Font FOSS exposes TtfTableSet for named table access and TtfFont.get_table_bytes() / TtfFont.set_table_bytes() for raw binary access.

Step-by-Step Guide

Step 1: Install the Package

Install the Aspose.Font FOSS package from PyPI using the pip command below:

pip install "aspose-font>=1.0.0"

Step 2: Import Required Classes

Import FontLoader and TtfFont to load a font file and access its table set:

from aspose_font.loader import FontLoader
from aspose_font.ttf.font import TtfFont

Step 3: Access Named Tables

Load a TTF file with FontLoader.open() and access named tables via the ttf_tables property:

ttf_font: TtfFont = FontLoader.open("Roboto-Regular.ttf")
tables = ttf_font.ttf_tables
print("kern present:", tables.kern is not None)
print("cmap present:", tables.cmap is not None)

Step 4: Read Raw Table Bytes

Read the raw binary data for a specific table by passing its 4-character tag to get_table_bytes():

ttf_font: TtfFont = FontLoader.open("Roboto-Regular.ttf")
raw = ttf_font.get_table_bytes("name")
print(f"name table: {len(raw)} bytes")

Step 5: Write Modified Table Bytes

Write modified binary data back to a named table using set_table_bytes() with the tag and byte payload:

ttf_font: TtfFont = FontLoader.open("Roboto-Regular.ttf")
modified = b"..."  # your modified binary data
ttf_font.set_table_bytes("GSUB", modified)

Common Issues and Fixes

AttributeError: Font has no attribute ttf_tablesttf_tables is on TtfFont, not the base Font class. Use ttf_font: TtfFont = FontLoader.open(...) to get a typed reference.

get_table_bytes returns empty bytes — The tag must be exactly 4 characters (pad with spaces if needed, e.g. "kern" not "KRN").

Frequently Asked Questions

Which named tables are exposed on TtfTableSet?

head, hhea, maxp, os2, name, post, cmap, loca, hmtx, and kern.

Can I add a new table to a font?

Yes. Pass any valid 4-byte tag and byte data to TtfFont.set_table_bytes(tag, data).

See Also