Add a New Glyph to a Font in FontForge with Python

FontForge provides a built-in Python module that allows you to automate font manipulation, including programmatically creating and adding new glyphs to existing or new fonts. This guide outlines the steps required to open a font file, create an empty glyph container at a target Unicode code point, draw vector outlines using FontForge's pen API, set horizontal metrics, and export the modified font to a usable file format.

Step 1: Initialize the Font and Glyph

To modify a font, open an existing font file or create a blank one using the fontforge module. Once the font object is loaded, allocate a new glyph using createChar(), specifying the desired Unicode value and an optional glyph name.

import fontforge

# Open an existing font or create a new one
font = fontforge.open("source_font.ttf")

# Define target Unicode codepoint and glyph name
codepoint = 0xE000  # Private Use Area example
glyph_name = "custom_square"

# Create the glyph slot
glyph = font.createChar(codepoint, glyph_name)

Step 2: Draw Outlines Using the Glyph Pen

FontForge supports drawing vector contours directly into a glyph using its glyphPen interface. You can draw lines, Bézier curves, and closed paths by defining coordinates.

# Initialize the drawing pen
pen = glyph.glyphPen()

# Draw a 500x500 square
pen.moveTo((100, 0))
pen.lineTo((600, 0))
pen.lineTo((600, 500))
pen.lineTo((100, 500))
pen.closePath()

# Release the pen to commit paths to the glyph
pen = None

For curved shapes, use pen.curveTo((cx1, cy1), (cx2, cy2), (x, y)) to define cubic Bézier segments.

Step 3: Set Metrics and Fix Contour Direction

After drawing the outline, set the advance width so that subsequent characters are placed correctly when rendered. It is also good practice to correct contour directions to ensure proper filling according to font winding rules.

# Set the advance width
glyph.width = 700

# Normalize path winding direction for correct rendering
glyph.correctDirection()

Step 4: Export the Updated Font

Finally, generate the output font file to apply the changes to disk.

# Save changes to a new font file
font.generate("updated_font.ttf")

# Close the font object to free resources
font.close()

Running the Script

Run this script directly through the FontForge command-line interpreter:

fontforge -script add_glyph.py

Alternatively, if your system Python environment has the FontForge bindings compiled and configured in sys.path, you can execute the script using standard Python:

python add_glyph.py