Skip to content
Jennifer Programming Language

font - TrueType / OpenType font parsing

Import with import "font.j" as font;. A pure-Jennifer TrueType / OpenType parser: read a .ttf / .otf from bytes and expose its metrics, character map, and glyph outlines. No Go and no dependency (the bytes type and the bitwise operators read the big-endian tables), so it runs on both binaries.

Both outline backends ship: the TrueType glyf backend (simple + composite glyphs, quadratic curves) and the CFF / PostScript backend for OpenType OTTO fonts (a Type2 charstring interpreter with global / local subroutines and CID-keyed FDArray / FDSelect, so CJK fonts outline too), detected on parse. It parses head, cmap (formats 4 and 12), maxp / hhea / hmtx, OS/2 (vertical metrics), the legacy kern table, loca / glyf or CFF , and name.

jennifer
use io;
import "font.j" as font;

def f as font.Font init font.open("/usr/share/fonts/TTF/DejaVuSans.ttf");
io.printf("%s, %d upem\n", font.name($f), font.unitsPerEm($f));
io.printf("<path d=\"%s\"/>\n", font.glyphPath($f, 65));   # outline of 'A'

Runnable: examples/modules/font_demo.j (a word rendered to an SVG).

Surface

CallReturnsNotes
font.parse(b)FontParse a font from bytes (.ttf or .otf).
font.open(path)FontRead a font file and parse it.
font.unitsPerEm(f)intThe em-square size - the coordinate scale of every metric and outline.
font.name(f)stringThe font family name.
font.advance(f, codepoint)intThe horizontal advance width of a codepoint's glyph, in font units.
font.kern(f, left, right)intThe kern-table pair adjustment between two codepoints (0 when absent).
font.ascender(f)intTypographic ascender (OS/2 sTypoAscender, else hhea).
font.descender(f)intTypographic descender (negative).
font.lineGap(f)intTypographic line gap (line height = ascender - descender + lineGap).
font.capHeight(f)intCap height (OS/2 sCapHeight; 0 when unavailable).
font.xHeight(f)intx-height (OS/2 sxHeight; 0 when unavailable).
font.glyphPath(f, codepoint)stringThe glyph outline as an SVG path d string.
font.glyph(f, codepoint)GlyphThe raw outline: contours of on / off-curve points, advance, and bounding box.
font.glyphId(f, codepoint)intThe glyph id the character map gives a codepoint (0, .notdef, when the font lacks it) - what a PDF embeds under Identity encoding.
font.glyphIds(f, codepoints)list of intglyphId for a whole list of int in one call; faster than a loop for a long text.
font.advanceGid(f, gid)intThe advance width of a glyph id, in font units (for a PDF W widths array).
font.advances(f, gids)list of intadvanceGid for a whole list of int of glyph ids in one call; faster than a loop for a long text.
font.numGlyphs(f)intThe number of glyphs in the font.
font.isCff(f)boolWhether the outlines are CFF / PostScript (an OpenType OTTO font) rather than TrueType glyf.
font.bbox(f)list of intThe font bounding box [xMin, yMin, xMax, yMax] in font units (for a PDF FontBBox).
font.data(f)bytesThe raw font file bytes as parsed (for embedding the font program, e.g. a PDF FontFile2).

A codepoint the font lacks maps to glyph 0 (.notdef). A character map that gives a codepoint a glyph id past numGlyphs is a malformed font: the lookup (glyphId, glyphIds, advance, glyph, glyphPath, kern) throws kind "font".

Coordinates and outlines

Everything is in font units - divide by unitsPerEm (typically 1000 or 2048) to get em fractions, then multiply by your point size. Fonts store y pointing up, so flip y for screen rendering (an SVG transform="scale(1,-1)" around the whole word does it).

font.glyphPath emits an SVG path: M / L for straight segments, Q (quadratic Bezier) for TrueType curves, and C (cubic Bezier) for CFF curves - each backend's native curve type. For the raw outline, font.glyph returns a Glyph (whose points are always quadratic - a CFF cubic is approximated as two quadratics there, while glyphPath keeps the exact cubic):

StructFields
Glyphadvance, xMin, yMin, xMax, yMax (int), contours (list of Contour)
Contourpoints (list of Point)
Pointx, y (int), onCurve (bool; an off-curve point is a quadratic control point)

Composite glyphs (an accented letter built from a base plus a mark) are resolved into a single set of contours, with each component's translation and scale applied.

Laying out a string

Walk the string, outline each glyph, and advance the pen by its advance width:

jennifer
use io;
use convert;
use strings;
import "font.j" as font;

def f as font.Font init font.open("/usr/share/fonts/TTF/DejaVuSans.ttf");
def x as int init 0;
for (def ch in strings.chars("Hello")) {
    def cp as int init convert.toCodepoint($ch);
    # one SVG path per glyph, shifted right by the pen position
    io.printf("<path transform=\"translate(%d,0)\" d=\"%s\"/>\n", $x, font.glyphPath($f, $cp));
    $x = $x + font.advance($f, $cp);
}

Pair kerning from the legacy kern table is available via font.kern(f, left, right) (add it to the pen advance); vertical metrics come from font.ascender / descender / lineGap / capHeight / xHeight.

jennifer
use io;
import "font.j" as font;

def f as font.Font init font.open("/usr/share/fonts/TTF/DejaVuSans.ttf");
def prev as int init 65;   # 'A'
def cp as int init 86;     # 'V'
def x as int init font.advance($f, $prev) + font.kern($f, $prev, $cp);   # kerned advance
io.printf("pen after A: %d units\n", $x);

Scope

In: TrueType glyf and OpenType CFF outlines (including CID-keyed CJK fonts, subroutines, and the flex operators), cmap formats 4 and 12, hmtx advances, OS/2 vertical metrics, and legacy kern-table pair kerning. Out: kerning / shaping from GPOS / GSUB (modern fonts put kerning there; the legacy kern table is read), hinting, colour / emoji tables, CFF2 and variable-font axes.

A hostile font cannot hang the outliner: charstring subroutine recursion is bounded (a runaway self-call raises a catchable kind "limit" error, not an infinite loop), the composite-glyph depth and total component count are capped (kind "limit" too), and every table loop is finite. A malformed font - a bad offset, a truncated table - fails with Error{kind: "font"} from parse or from the accessor that reads the bad part (glyph, glyphPath, advance, glyphIds, kern, ...), never with a generic runtime fault.

The tests parse tiny committed fixtures (modules/testdata/font_fixture.ttf and font_fixture_cff.otf, regenerable with scripts/gen-font-fixture.py); the CFF backend is cross-checked against fontTools (pixel-exact outlines, IoU 1.0) over ~170 glyphs on real system fonts, including a CID-keyed CJK font, and a hand-crafted recursive font pins the guard.

Performance

A multi-megabyte CJK CFF font opens in ~100 ms, because parse only reads the table directory and headers. Glyph access scales with the glyph, not the font: a single CharStrings / subr INDEX entry is read in O(1) (never walking the whole 65k-glyph INDEX), the format-12 cmap is binary-searched, and CFF subroutines are fetched on demand, so a CJK glyph outlines in a fraction of a second. There is no need to cache or serialise a parsed Font: it is the raw file bytes plus a small table of offsets, so re-opening the file is as fast as reloading a cache.

Academy talks

TalkWhat it shows
Inside a document pipeline: doctree, MyST, reST and fontsembedding TrueType fonts, outlines and kerning

API reference

Every exported function, struct and constant of font, with its signature, generated from the module's doc comments: the font API reference.