Subset a font to the glyphs of a string, for PDF embedding
Shrink a font to the glyphs one text needs before embedding it in a PDF.
AGPL-3.0-onlyNode
Package: @awacloud/fonts
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
npm install @awacloud/fonts(it depends on@awacloud/fw).- Copy
main.jsand runbun main.js path/to/Face.ttf "The text to keep"(ornode main.js …): four lines — glyph counts, byte sizes, the hash-prefixed PDFBaseFontname, and the mapping check. - Call
subset(bytes, text)from your own code;result.subsetis the TrueType subset to embed asFontFile2, andsubsetForPdf's full result also carries thetoUnicodeCmap,widthsandfontDescriptora PDF needs.
What it shows
- Wiring: one
ModuleRuntimewith@awacloud/fonts'sfw_requireandmodules— the package's manifest also registers the four helpersembedSubsetForPdfdepends 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, rewritesglyf,loca,hmtx,maxp,hhea, emits a format-4cmapfor the kept code points, and returnssubsetBytes,gidMap,glyphMap,widths,toUnicodeCmap,postScriptName(six-letter hash prefix, the PDF convention) andfontDescriptor. - 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 (strictlookup), and that a character the face lacks is reported as missing instead of silently mapping to.notdef. - Not shown: CFF (
.otfwith 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
// 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);
}