Skip to content
Search

FontTools

lastmod 2024-11-14created 2024-11-147 edits

A library to manipulate font files from Python

FontTools is an open-source library for manipulating font files, written in Python.

The library supports TrueType, OpenType, AFM, and many other font formats, and is widely used for analyzing, modifying, creating, and converting fonts.

FontTools has become an essential tool especially in font engineering and web font optimization.

Key features

  • Support for many font formats: can handle various font file formats such as TrueType, OpenType, and AFM.
  • Font subsetting: can optimize file size by generating subset font files that contain only the needed glyphs.
  • TTF/OTF conversion: can convert between TrueType and OpenType fonts.
  • XML-based font editing: can extract font data to XML, edit it, and compile it back into a font file.
  • Glyph data manipulation: can directly modify glyph shapes or metadata.

Install

pip install fonttools

Extracting glyph information

The following example code uses FontTools to extract information about specific glyphs from font files.

from fontTools.ttLib import TTFont

# Arial 폰트의 'A'와 맑은 고딕의 '가' 글리프 정보 출력
for font_name, sample_glyph in [('arial', 'A'), ('malgun', 'uniAC00')]:
    # 글리프의 정보 출력
    font = TTFont(rf'C:\Windows\Fonts\{font_name}.ttf')
    glyph = font['glyf'].get(sample_glyph)

    print(f"{font_name=}, {sample_glyph=}")
    print(f" 글리프 좌표 정보: {glyph.coordinates}")
    print(f" 윤곽선 수: {glyph.numberOfContours}\n")

    # 글꼴 파일 닫기
    font.close()

Checking Unicode character mappings

from fontTools.ttLib import TTFont

# TTF 파일 읽기
font_path = "NanumGothicCoding-Bold.ttf"
font = TTFont(font_path)

# 글리프 이름 가져오기
glyph_names = font.getGlyphOrder()

# 글리프 개수 출력
print("Total glyphs:", len(glyph_names))

# 글리프 목록 출력 (매우 많음)
# print("Glyph names:", glyph_names)

# cmap 테이블에서 유니코드 맵핑 확인
unicode_map = font['cmap'].getBestCmap()

# 유니코드와 글리프 이름 쌍 출력
for codepoint, glyph_name in unicode_map.items():
    print(f"U+{codepoint:04X}: {glyph_name}")

cmap (Character Map) Table

The cmap (Character Map) table is a table in TrueType and OpenType font files that stores the mapping between each Unicode code point and a glyph (the shape of a character).

This mapping is essential for rendering text data correctly on screen. In other words, given a Unicode code point, it is used to determine how the font displays that character.

Role of the cmap table

  • Character code mapping: the cmap table maps Unicode code points (e.g. U+0041, U+AC00) in the font file to actual glyph names or glyph IDs.
  • Glyph rendering: when an operating system or application renders a character, it consults the cmap table to find and render the glyph for that code point.
  • Support for various character encodings: a font can have several kinds of cmap subtables, so it can support various encodings besides Unicode (e.g. ASCII, Shift-JIS).

Structure of the cmap table

  • The cmap table consists of several subtables, each representing a particular character encoding format and mapping method.
  • Depending on the mapping method, subtables are divided into simple mapping tables, range mappings, and format-specific mappings (Format 4, Format 12, etc.).
    • Format 4: the most widely used format; maps glyphs in the BMP (Basic Multilingual Plane).
    • Format 12: supports mapping of extended Unicode (e.g. emoji or rare characters), using 32-bit values to cover many languages and character sets.

How to check

getBestCmap() finds the most suitable Unicode mapping table in the cmap table.

pyftsubset

OpenType font subsetter and optimizer

Use cases

  • Web font optimization: can generate font subsets containing only the needed glyphs to improve web page loading speed.
  • Font development and testing: useful when developing new fonts or modifying existing ones.
  • Education and research: can help analyze and study font structure and glyph data.

See also

Favorite site

References


  1. 44BITS_-_optimization_webfont_with_pyftsubnet.pdf ↩

author Zer0 sitemap