In short
A four-page booklet that shows off three typefaces. It shows why all the fonts must finish loading before the pages are laid out, or lines break in the wrong places.
What you'll build
House Specimen Nº 3, from the imaginary Pellow Lane Press, is a four-page type specimen for three faces. On the cover, an ultramarine field holds a white Ag in Noto Serif Display italic at 240 pt and two mono lines that name the three faces; the title sits below the field. Page 2 runs Ysabeau Office down a waterfall from 7 to 14 pt, then sets Spanish, Polish and Czech pangrams whose ż, ř and ů need a second font file. Page 3 is the audit: an IBM Plex Mono table, filled in by the pen, of the ten faces the booklet declares, the six its pages are set in and the files the browser fetched for each. Page 4 sets page 1's first paragraph twice, from an early build and from the last. The early build ran before the browser had a single font file, so its lines end in other places and some run past the measure.
This recipe answers
- Why do my line breaks change, or PDF words overlap, and how do I load fonts correctly?
- How do I use my own brand or licensed fonts in the layout and embed them in the PDF?
- How do I find out what is wrong with my document (warnings, overflow, non-converging layout)?
The short answer
// buildDocumentWithFonts starts with prepareFonts: it reads the config and the text for every
// face they ask for (text, headings, chips, table, captions, opener, running heads), in each
// weight and slant, and loads them for the characters the document sets. The page declares its
// files (declareFaces), so they load through document.fonts; a face nothing declares would be
// asked of a resolve(family, weight, style) option. Then it builds, reads the faces the pages
// are set in, loads any that the config did not name and builds again.
let report; // { loaded, missing, synthesized }: lists of { family, weight, style }
const build = () => buildDocumentWithFonts(content(), config(),
{ onFonts: (found) => { report = found; } }); // what the last look at the pages found
kitStatus('Loading fonts…'); // the kit's bar: it also reports any error thrown below
const early = buildDocument(content(), config()); // on purpose: the page has no font yet (page 4)
declareFaces(FONTS);
const fitted = await build(); // every face loaded before a line is measured
audit = auditOf(fitted, report); // page 3's table
drawProof(early, fitted); // page 4's picture
const doc = await build(); // nothing left to load: the same pages, table and picture filled in
showPages(doc, { title: 'Load every font before layout' });
One call loads every face the config and the text ask for, then builds
Ingredients
- Features
- Fonts before layoutBody typePages on a canvasFigures and tables as resourcesFigures exactly hereTables from dataTable styleCaption styleCustom resource typesDesigned openersHeading attributesAnchoring design elementsParagraph stylesInline chipsTrim sizeMirrored marginsSemantic colour paletteRunning heads and foliosHeads by page role
- Type
- Ysabeau Office, Noto Serif Display, IBM Plex Mono (SIL OFL 1.1)
- Assets
- None: every picture is drawn in code
Method
#1 · Declare every file without fetching it
const SUBSETS = { // the characters each file covers, copied from the family's @font-face CSS
latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
+ 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
+ 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,'
+ 'U+A720-A7FF' };
const FILES = new Map(); // FontFace → the subset its file covers, for the audit
function declareFaces(fonts) { // Fontsource's static files stand in for your own /fonts/ folder
for (const { family, weight, style } of facesOf(fonts)) {
const id = family.toLowerCase().replaceAll(' ', '-');
for (const [subset, unicodeRange] of Object.entries(SUBSETS)) {
const file = `${id}@5/files/${id}-${subset}-${weight}-${style}.woff2`;
// Adding a face fetches nothing: the file downloads when a load or a line needs it.
const face = new FontFace(family, `url(https://cdn.jsdelivr.net/npm/@fontsource/${file})`,
{ weight: `${weight}`, style, unicodeRange });
FILES.set(face, subset);
document.fonts.add(face);
}
}
}
A FontFace is one file, as an @font-face rule is, so a face with a latin and a latin-ext file is declared with two FontFace objects that share a family, weight and style and differ in unicodeRange, copied from the family's CSS. Adding them to document.fonts downloads nothing: the browser fetches a file when a load() call or a line of text needs its characters. Postext loads the faces a page declares through document.fonts; a face nothing declares is asked of the resolve option, which is how the other recipes get their Fontsource files from the kit. customFonts in a config only describes the files of a .postext bundle, so a page built from Markdown declares its own or hands over a resolve.
#2 · Load the faces, then build
The code is the short answer above. buildDocumentWithFonts begins with prepareFonts, which reads the config and the text for every face they ask for, in each weight and slant, and loads them with the document's own characters as the sample, so the latin-ext files arrive with the Polish and Czech pangrams (Loading fonts before layout). It then builds, reads the faces the pages are set in, loads any that the config did not name and builds again. onFonts receives the report of that last look: the faces found loaded, the ones missing, and the ones the browser would have synthesized from another weight or slant. The pen builds three times because the booklet prints its own evidence: once too early, once with the faces, and a last time with the table and the picture filled in.
#3 · Build the audit from the report
const SET = { loaded: 'yes', synthesized: 'faked', missing: 'in a fallback' }; // the report
const nameOf = (f) => `${f.family.replaceAll('"', '')} ${f.weight} ${f.style}`; // or a FontFace
function auditOf(doc, report) {
const found = Object.keys(SET).flatMap((kind) => report[kind].map((f) => [nameOf(f), kind]));
const inPages = new Map(found);
const loaded = [...FILES].filter(([face]) => face.status === 'loaded');
const faces = new Map([...facesOf(FONTS), ...Object.keys(SET).flatMap((kind) => report[kind])]
.map((f) => [nameOf(f), f])); // the declared faces, then any the pages set without a file
const rows = [...faces].map(([name, f], i, all) => [
i && all[i - 1][1].family === f.family ? '' : f.family, // each family named once
`${f.weight}${f.style === 'italic' ? ' italic' : ''}`, SET[inPages.get(name)] ?? 'no',
loaded.filter(([face]) => nameOf(face) === name).map(([, subset]) => subset).join(' · ')
|| 'none'].map((cell) => ({ content: cell })));
// What else to read in a finished layout: its content warnings, its passes, its warnings.
return { rows, note: `${report.loaded.length} of ${rows.length} faces set in the pages · `
+ `${loaded.length} of ${FILES.size} files fetched · fontFallback warnings: `
+ `${fallbacksIn(doc) || 'none'} · ${doc.converged ? '' : 'not '}converged · layout warnings: `
+ `${doc.warnings?.length || 'none'}` };
}
The table starts from the faces FONTS declares and adds what the report says of each: set in the pages, faked by the browser, or set in a fallback. The last column lists the files whose FontFace reached loaded. Sixteen of the twenty were fetched: Postext loads all four faces of the text family, since ** and * can ask for them in any paragraph, and the two mono italics, which no setting names, were never downloaded. The note reads three more things from the finished document: contentWarnings, where a face measured in a fallback is listed as fontFallback; converged, true when the layout's passes settled; and warnings. Check all three before you show or export a page.
#4 · Keep an early build as evidence
const STRIP = { lines: 8, overrun: 10 }; // page 1's first paragraph; mm shown past the measure
const PROOF = { // px: two strips a lead apart, cut at 300 dpi
width: Math.round(((MEASURE + STRIP.overrun) / 25.4) * 2 * DPI),
height: Math.round((((2 * STRIP.lines + 1) * LEAD) / 72) * 2 * DPI) };
const proof = { moved: 0, total: 0, faces: 0 }; // lines the early build broke elsewhere, of all
const fallbacksIn = (doc) => // a build lists each face its font set could not give
(doc.contentWarnings ?? []).filter((w) => w.kind === 'fontFallback').length;
const proofFigure = () => ({ id: 'proof', typeId: 'figure', kind: 'bitmap', createdAt: 0,
updatedAt: 0, placement: here,
bitmap: { fileId: 'proof.png', format: 'png', width: PROOF.width, height: PROOF.height },
caption: 'The first paragraph of page 1 as the early build set it, measured before the fonts '
+ 'had arrived (above), and as the last build set it (below). The early build broke '
+ `${proof.moved} of its ${proof.total} lines of text elsewhere, and its own warnings name `
+ `${proof.faces} faces set in a fallback. The rule marks the measure.`,
altText: `Two strips of the same ${STRIP.lines} lines of text. In the upper strip the lines `
+ 'break in other places and some run past a vertical rule; in the lower one every line '
+ 'stops short of it.' });
function drawProof(first, last) {
const linesOf = (doc) => doc.blocks.filter((b) => b.type === 'paragraph')
.map((b) => b.lines.map((l) => l.text));
const [before, after] = [first, last].map(linesOf);
proof.total = before.flat().length;
proof.faces = fallbacksIn(first);
proof.moved = before.flatMap((lines, i) => lines.filter((t, j) => t !== after[i]?.[j])).length;
const canvas = Object.assign(document.createElement('canvas'), PROOF);
const ctx = canvas.getContext('2d');
const strip = (PROOF.height * STRIP.lines) / (2 * STRIP.lines + 1);
const edge = Math.round((PROOF.width * MEASURE) / (MEASURE + STRIP.overrun));
// The renderer clips each column 2 pt past its edge, which would cut the early build's lines
// at the measure: paint a copy of page 1 whose column reaches across the whole strip.
const wide = (column) => ({ ...column,
bbox: { ...column.bbox, width: column.bbox.width + (STRIP.overrun / 25.4) * DPI } });
[first, last].forEach((doc, i) => {
const page = document.createElement('canvas');
renderPageToCanvas({ ...doc.pages[0], columns: doc.pages[0].columns.map(wide) }, doc, page,
{ scale: 2 }); // 300 dpi
const { x, y } = doc.pages[0].columns[0].blocks.find((b) => b.type === 'paragraph').bbox;
ctx.drawImage(page, 2 * x, 2 * y, PROOF.width, strip,
0, i * (PROOF.height - strip), PROOF.width, strip);
});
ctx.fillStyle = `${palette.ultramarine}1f`; // a pale wash over the margin past the measure
ctx.fillRect(edge, 0, PROOF.width - edge, PROOF.height);
ctx.fillStyle = palette.ultramarine; // a hairline at the measure, and each strip's name
ctx.fillRect(edge, 0, 2, PROOF.height);
ctx.font = `700 ${(7 / 72) * 2 * DPI}px "IBM Plex Mono"`; // 7 pt, loaded by now
['early', 'last'].forEach((name, i) => // on the last line of each strip
ctx.fillText(name, edge + 12, (i ? PROOF.height : strip) - 16));
registerResourceImage('proof.png', canvas);
}
The pen calls buildDocument once before it declares a single face, so that build measures every word in the browser's fallback. Once the real faces are in, the pen paints it again and compares it line by line with the last build; the count of lines in the caption comes from that comparison, and the count of faces from the early build's own fontFallback warnings. A plain line measured in a narrower fallback runs past the measure until the column's clip, 2 pt past its edge, cuts off its last letters, so the pen paints page 1 with a widened column to show the whole overrun. The canvas and postext-pdf draw each run of a justified or mixed-style line where the layout measured it, so a real face wider than the fallback prints over the next word, and the words of a PDF built before its fonts arrived overlap. Nothing of the early build passes to the next one: prepareFonts finds the new faces in document.fonts and drops the widths measured in their families, so no call to clearMeasurementCache() is needed.
#5 · A waterfall on the text's rhythm
const bodyText = () => ({
fontFamily: TEXT, fontSize: pt(11), lineHeight: pt(LEAD), color: col('ink'),
boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
textAlign: 'left', firstLineIndent: pt(0), paragraphSpacing: true }); // ragged and spaced
// Every waterfall size and pangram is two leads (31 pt) deep, on the text's 15.5 pt rhythm.
const line = (size) => ({ fontSize: pt(size), lineHeight: pt(2 * LEAD) });
const paragraphStyles = () => [
...[7, 8, 9, 10, 11, 12, 14].map((size) => ({ id: `s${size}`, ...line(size) })),
{ id: 'pangram', ...line(13) },
{ id: 'colophon', fontSize: pt(7), lineHeight: pt(10), fontFamily: MONO, color: col('muted') }];
// Size labels: boxless mono chips. A Plex Mono letter is 0.6 em wide, so a one-digit label gets
// half a letter each side and the samples start on one edge.
const tag = { fontFamily: MONO, fontSize: pt(7), color: col('ultramarine'),
backgroundEnabled: false, borderWidth: pt(0), paddingX: pt(0), gap: mm(2.5) };
const chipStyles = () => [{ id: 'size', ...tag }, { id: 'size-1', ...tag, paddingX: em(0.3) }];
Ysabeau Office sets the text at 11 on 15.5 pt, with a blank line between paragraphs instead of an indent. The text is ragged, so every word space keeps its natural width. Bold, italic and references are set in ink; left alone, they would take the main colour. Every waterfall size and pangram is a paragraph style two leads (31 pt) deep, so the page keeps the text's 15.5 pt rhythm. The size labels are mono chips, and the one-digit sizes get half a letter of padding on each side, so every sample starts on the same edge.
#6 · Three faces on one cover
const Y = { kicker: 14, glyphs: 17, label: FIELD - 12, title: FIELD + 10, // mm from the top edge
end: FIELD + 42 }; // where the opener ends: under the title, the lead and a line of air
const ITALIC_FOOT = 5; // mm: the italic A's foot reaches this far left of the glyphs' origin
const at = (x, y, width) => ({ anchor: { to: 'page', edge: 'top-left' },
offset: { x: mm(x), y: mm(y) }, ...(width && { size: { width: mm(width) } }) });
const text = (id, content, style, placement) => ({ kind: 'text', id, content, align: 'left',
overflow: 'wrap', ...style, placement }); // a running head wraps too, never '…'
const cover = () => ({ level: 1, fontSize: pt(30), italic: true, // headings.levels[0]
breakBefore: { enabled: true, parity: 'odd' }, // the cover is a recto
span: 'page', // the heading is set across the page; its field hangs from the bleed
advancedDesign: { enabled: true, minHeight: mm(Y.end - MARGIN.top), // from the top margin
slot: { elements: [
{ kind: 'box', id: 'field', style: { backgroundColor: col('ultramarine') }, placement: {
anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill', height: mm(FIELD) } } },
text('kicker', '{attr.kicker}', { ...label, fontWeight: 700, color: col('paper') },
at(MARGIN.inner, Y.kicker)),
text('glyphs', '{attr.glyphs}', { ...display, fontSize: pt(240), lineHeight: 1,
color: col('paper') }, at(MARGIN.inner + ITALIC_FOOT, Y.glyphs)),
text('label', '{attr.label}', { ...label, color: col('mist') }, at(MARGIN.inner, Y.label)),
text('faces', '{attr.faces}', { ...label, color: col('mist') },
{ anchor: { to: '#label', edge: 'below' }, offset: { y: mm(1.2) } }),
text('title', '{titleText}', { ...display, fontSize: pt(30), lineHeight: 1.05,
color: col('ink') }, at(MARGIN.inner, Y.title, PAGE.width - 2 * MARGIN.inner)),
text('lead', '{attr.lead}', { fontFamily: TEXT, italic: true, fontSize: pt(12),
lineHeight: 1.35, color: col('ink') }, { anchor: { to: '#title', edge: 'below' },
offset: { y: mm(3) }, size: { width: mm(MEASURE) } }),
] } } });
The cover is the H1 level's design: the letters of the heading's glyphs attribute in the display face at 240 pt, and under them two mono lines that name that face and the text and label faces, as on a type foundry's specimen sheet. span: 'page' sets the heading across the page, and the field hangs from the top-left corner of the bleed, so it runs off the top edge. minHeight counts from the top margin and reserves the room down to Y.end, 42 mm below the field; without it the text starts a line higher, tight under the lead.
The whole recipe
// ═══ Postext Cookbook · Nº 026 · Type specimen with every font loaded before layout ═════════
// https://postext.dev/en/cookbook/fonts-before-layout
// Code: MIT · Text: original (CC BY 4.0) · Picture: cut from the pen's own early and last builds
// Fonts: Ysabeau Office, Noto Serif Display, IBM Plex Mono (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import { buildDocument, buildDocumentWithFonts, renderPageToCanvas, defaultResourceTypes,
registerResourceImage } from 'https://esm.sh/postext';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'fonts-before-layout';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
const PAGE = { width: 180, height: 240 }; // mm
const MARGIN = { top: 22, bottom: 24, inner: 20, outer: 48 }; // mm: inner is the spine side
const MEASURE = PAGE.width - MARGIN.inner - MARGIN.outer; // 112 mm: about 70 letters at 11 pt
const FIELD = 122; // mm from the top edge: the ultramarine field of the opener
const LEAD = 15.5; // pt: the body leading and the step of every vertical space
const DPI = 150; // the page's resolution: the proof on page 4 is cut at twice this
const [TEXT, DISPLAY, MONO] = ['Ysabeau Office', 'Noto Serif Display', 'IBM Plex Mono'];
const palette = { ink: '#16161a', ultramarine: '#3246d3', mist: '#c9d0f6', // mist: 4.6:1 on
rule: '#cfc9bd', muted: '#6b6a70', paper: '#ffffff' }; // ultramarine, for labels on the field
// Every colour is linked to its palette entry; main-color catches any default left unstated.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = () => Object.entries({ ...palette, 'main-color': palette.ultramarine })
.map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const label = { fontFamily: MONO, fontSize: pt(7.5), letterSpacing: pt(1.2),
textTransform: 'uppercase' };
const display = { fontFamily: DISPLAY, fontWeight: 900, italic: true };
// #region type: the text face at 11 on 15.5 pt, and a waterfall of it on two leads a line
const bodyText = () => ({
fontFamily: TEXT, fontSize: pt(11), lineHeight: pt(LEAD), color: col('ink'),
boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
textAlign: 'left', firstLineIndent: pt(0), paragraphSpacing: true }); // ragged and spaced
// Every waterfall size and pangram is two leads (31 pt) deep, on the text's 15.5 pt rhythm.
const line = (size) => ({ fontSize: pt(size), lineHeight: pt(2 * LEAD) });
const paragraphStyles = () => [
...[7, 8, 9, 10, 11, 12, 14].map((size) => ({ id: `s${size}`, ...line(size) })),
{ id: 'pangram', ...line(13) },
{ id: 'colophon', fontSize: pt(7), lineHeight: pt(10), fontFamily: MONO, color: col('muted') }];
// Size labels: boxless mono chips. A Plex Mono letter is 0.6 em wide, so a one-digit label gets
// half a letter each side and the samples start on one edge.
const tag = { fontFamily: MONO, fontSize: pt(7), color: col('ultramarine'),
backgroundEnabled: false, borderWidth: pt(0), paddingX: pt(0), gap: mm(2.5) };
const chipStyles = () => [{ id: 'size', ...tag }, { id: 'size-1', ...tag, paddingX: em(0.3) }];
// #endregion
// #region opener: the H1 as a bleed field, the display face at 240 pt, labels naming the faces
const Y = { kicker: 14, glyphs: 17, label: FIELD - 12, title: FIELD + 10, // mm from the top edge
The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)
Variations
#Hand over the files with resolve
kitFonts(FONTS), in from a Markdown string to a designed page, declares nothing: Postext asks its resolve for the files of each face and adds them to document.fonts itself.
#Forget a face
Leave out the bold of IBM Plex Mono, which sets the kicker, the table header and the caption labels: the browser thickens the regular, the table marks the face faked, and the note counts one fontFallback warning, which names IBM Plex Mono 700 as synthesized.
- 'IBM Plex Mono': ['400', '400i', '700', '700i'], // labels, chips, the table, captions
+ 'IBM Plex Mono': ['400', '400i', '700i'], // labels, chips, the table, captions#Embed the same faces in a PDF
renderToPdf embeds the bytes its fontProvider returns for each face, and the provider in a real PDF with the same fonts embedded serves Fontsource's latin files, which stop at Latin-1: for this booklet's ż, ł, ř and ů, have it return each face's whole font file from your own folder.
Pitfalls
Pitfall
Fontsource files cover letters, not symbols
The kit embeds a face's Fontsource latin file, plus its latin-ext file for č, ł, † and its greek file for α, χ (in a family that ships one: Lora and Gelasio do not), when the text sets them, on screen and in the PDF. Symbols such as →, ≈, ✓ and ★ are in none of those files and go missing in the PDF: draw them, set them as maths, or choose a face whose files hold them. Fonts embedded in the PDF →
Layout warning · fontFallback
Font fallback in the layout
Why. A face the text was set in was not in the font set when the document was laid out (`reason: 'missing'`), or the family has no file for that weight or slant and the browser draws it from another face (`'synthesized'`), so the line breaks were measured with a face that is not the one the PDF embeds.
Fix. Load the faces before the first build: `prepareFonts(content, config, { resolve })`, or build with `buildDocumentWithFonts`, which also loads any face the pages used and builds again. For `synthesized`, load that weight or slant, or set a weight the family ships. Docs →
Sandbox check · missingFont
Missing font
Why. A family named in the config never loaded in the browser, so text was measured and drawn with a system fallback.
Fix. Fix the family name (one family, no CSS stack) and load every face before the first build; in a pen, list it in FONTS. Docs →
Sandbox check · missingFontVariant
Missing font variant
Why. A custom family has no file for a weight and style the document uses, such as its italic or bold.
Fix. Upload or declare the missing variant, or stop using that weight or style. Docs →
- If you load a face yourself,
document.fonts.load(font)with no sample text loads only the file that covers a space, the latin one, and ż and ř fall back to a system face.prepareFontspasses the document's own characters. renderPageToCanvasandpostext-pdfclip each column 2 pt past its edge, so a line measured with a narrower fallback loses its last letters. The build that measured it names the face indoc.contentWarningsasfontFallback: read that list before you show or export a page.
Credits
- Recipe
- Ignacio Ferro
- Text
- Original prose, CC BY 4.0
- Fonts
- Ysabeau Office (SIL OFL 1.1) · Noto Serif Display (SIL OFL 1.1) · IBM Plex Mono (SIL OFL 1.1)
Edit this write-up ↗ (opens in a new tab)Recipe folder on GitHub ↗ (opens in a new tab)


