Run it

Node Guide

Subset a TrueType face to the glyphs one string needs with subsetForPdf, print the original and subset sizes and glyph counts, and prove the subset re-reads and still maps every character. node kind.

Uses @awacloud/fonts (AGPL-3.0-only) over @awacloud/fw (Apache-2.0). This example's code is AGPL-3.0-only. No font file is committed here: bring your own, or use Liberation Sans (SIL Open Font License 1.1) from @awacloud/oconv-fonts.

When to use it

Embedding a real typeface in a generated PDF without shipping the whole font program: a 300 KB face becomes a few KB carrying only the glyphs the document draws. The same subset routine is what the office PDF writers use when they embed a face.

Copy-paste steps

  1. npm install @awacloud/fonts (it depends on @awacloud/fw).
  2. Copy main.js and run bun main.js path/to/Face.ttf "The text to keep" (or node main.js …): four lines — glyph counts, byte sizes, the hash-prefixed PDF BaseFont name, and the mapping check.
  3. Call subset(bytes, text) from your own code; result.subset is the TrueType subset to embed as FontFile2, and subsetForPdf's full result also carries the toUnicodeCmap, widths and fontDescriptor a PDF needs.

What it shows

  • Wiring: one ModuleRuntime with @awacloud/fonts's fw_require and modules — the package's manifest also registers the four helpers embedSubsetForPdf depends on, so a host needs nothing else.
  • The subset: subsetForPdf(font, codePoints) keeps glyph 0, the glyphs the code points map to and the components of composite glyphs, renumbers them, rewrites glyf, loca, hmtx, maxp, hhea, emits a format-4 cmap for the kept code points, and returns subsetBytes, gidMap, glyphMap, widths, toUnicodeCmap, postScriptName (six-letter hash prefix, the PDF convention) and fontDescriptor.
  • Proof by re-reading: the subset goes back through fonts.read; the test checks the byte and glyph counts shrink, that every character of the text maps to a glyph in the re-read subset (strict lookup), and that a character the face lacks is reported as missing instead of silently mapping to .notdef.
  • Not shown: CFF (.otf with PostScript outlines) and variable fonts, which this subsetter does not carry; building the PDF font dictionaries around the result (see @awacloud/pdf's embedding route).

Code

main.js

javascriptAGPL-3.0-only59 lines

// SPDX-License-Identifier: AGPL-3.0-only
// Run: bun main.js <font.ttf> "<text>"   (or node main.js <font.ttf> "<text>")
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { fw_require, modules } from '@awacloud/fonts';

const rt = new ModuleRuntime();
rt.registerAll([...fw_require, ...modules]);
const FONTS = rt.resolve('fonts');
const { subsetForPdf } = rt.resolve('embedSubsetForPdf');

/**
 * Subset a TrueType face to the glyphs one string needs (plus `.notdef` and
 * the components of composite glyphs), the way a PDF writer embeds a font.
 * @param {Uint8Array} bytes a `.ttf`
 * @param {string} text
 * @returns {{ originalBytes: number, subsetBytes: number, originalGlyphs: number, subsetGlyphs: number,
 *   postScriptName: string, missing: string[], subset: Uint8Array }}
 *   `missing` lists the characters the re-read subset cannot map (expected empty).
 */
export function subset(bytes, text) {
    const font = FONTS.read(bytes);
    const codePoints = [...new Set([...text].map((c) => /** @type {number} */ (c.codePointAt(0))))];
    const result = subsetForPdf(font, codePoints);
    const back = FONTS.read(result.subsetBytes); // the subset is itself a valid font
    const missing = [...new Set([...text])].filter(
        (c) => back.glyphIndexForCodePoint(/** @type {number} */ (c.codePointAt(0)), { strict: true }) < 0,
    );
    return {
        originalBytes: bytes.length, subsetBytes: result.subsetBytes.length,
        originalGlyphs: font.numGlyphs, subsetGlyphs: back.numGlyphs,
        postScriptName: result.postScriptName, missing, subset: result.subsetBytes,
    };
}

/** Stable report lines. @param {ReturnType<typeof subset>} r */
export function report(r) {
    const percent = Math.round((100 * r.subsetBytes) / r.originalBytes);
    return [
        `glyphs: ${r.originalGlyphs} → ${r.subsetGlyphs}`,
        `bytes: ${r.originalBytes} → ${r.subsetBytes} (${percent} %)`,
        `PDF BaseFont: ${r.postScriptName}`,
        r.missing.length
            ? `missing in the subset: ${r.missing.join(' ')}`
            : 'every character of the text maps to a glyph in the subset',
    ];
}

/** @param {string[]} [argv] */
export async function main(argv = process.argv.slice(2)) {
    const [file, text = 'Hello, world!'] = argv;
    if (!file) return ['usage: bun main.js <font.ttf> "<text>"'];
    return report(subset(new Uint8Array(readFileSync(file)), text));
}

if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
    for (const line of await main()) console.log(line);
}