In short
A style guide for a made-up metro system. It shows how to download a brand's own fonts once and use them for the page preview, the PDF and the saved file.
What you'll build
Four pages of the identity manual for Metro de Alba, a fictional metro of five lines. On the cover, the five lines leave the lower left on one shared track and branch to the right after crossing a grey river, under the name in Big Shoulders Display. Each section opens under an ink band, with a large two-digit number in the colour of one line. In 01 Colour the first column of the table is the colour itself; 02 Type has specimen lines and a platform sign, and 03 Usage closes on two framed map drawings, one drawn by the rules (Do) and one against them (Don't). All the text is set in six font files that the script downloads before the first layout. The PDF is drawn with the same six files, and the .postext file carries five, because the display face is marked as not redistributable.
This recipe answers
- How do I use my own brand or licensed fonts in the layout and embed them in the PDF?
- How do I export a real PDF in the browser with the fonts embedded?
- How do I stop headings, bold words and bullets from coming out blue?
- How do I add colour-key swatches to text, captions or table notes?
- How do I create a .postext bundle from code, to hand a document to the Sandbox or another program?
The short answer
// Your licensed files, one per face in FONTS. Fontsource's copies stand in for them here:
// point FONT_URL at your own server (same origin, or one that lets this page in by CORS).
const slug = (family) => family.toLowerCase().replaceAll(' ', '-');
const FONT_URL = ({ family, weight, style }) => `https://cdn.jsdelivr.net/npm/@fontsource/`
+ `${slug(family)}@5/files/${slug(family)}-latin-${weight}-${style}.woff2`;
const brandFaces = () => Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) => {
const weight = parseInt(spec, 10), style = spec.endsWith('i') ? 'italic' : 'normal';
return { family, weight, style, fileId: `${slug(family)}-${weight}-${style}.woff2` };
}));
const fontFiles = new Map(); // fileId → the WOFF2 bytes, fetched once
// 1 · Layout measures with document.fonts: register every face before the first build.
async function loadBrandFonts() {
await Promise.all(brandFaces().map(async ({ family, weight, style, fileId }) => {
const res = await fetch(FONT_URL({ family, weight, style }));
if (!res.ok) throw new Error(`No file for ${family} ${weight} ${style}`);
fontFiles.set(fileId, new Uint8Array(await res.arrayBuffer()));
const face = new FontFace(family, fontFiles.get(fileId), { weight: `${weight}`, style });
document.fonts.add(await face.load());
}));
}
// 2 · The PDF embeds the same bytes as TrueType. renderToPdf asks for the faces the pages
// paint; a weight or slant the brand lacks gets the family's closest file, embedded once.
async function brandFontProvider(family, weight, style) {
const cost = (f) => (f.style === style ? 0 : 1000) + Math.abs(f.weight - weight);
const own = brandFaces().filter((f) => f.family === family);
if (!own.length) throw new Error(`${family} is not one of the brand's fonts`);
return decompressWoff2(fontFiles.get(own.reduce((a, b) => (cost(b) < cost(a) ? b : a)).fileId));
}
// 3 · The bundle: customFonts names each face's file by its fileId; createBundle packs the bytes
// of every family it may hand on. Layout never reads it (gotcha: custom-fonts-declarative).
const customFonts = () => Object.keys(FONTS).map((name) => ({
name, redistributable: name !== DISPLAY, // the display face reaches suppliers another way
variants: brandFaces().filter((f) => f.family === name)
.map(({ weight, style, fileId }) => ({ weight, style, fileId, format: 'woff2' })),
}));
The brand's font files, fetched once for the layout, the PDF and the bundle
Ingredients
- Features
- Your own fontsSemantic colour paletteCell fillsColour swatchesDesigned openersNumbered headingsFull-width chapter bandNamed table stylesParagraph stylesCustom resource typesCaption styleFigure placementText, rules and boxes in page designsBody typeOne or two columnsFonts before layoutPDF export.postext bundlesPages on a canvasFigures and tables as resources
- Also uses
- Callout boxesCitations that place figuresHeading attributesHeading stylesFigure and Table in your languageColours per partFonts embedded in the PDFRunning heads per sectionUnnumbered chapters
- Type
- Public Sans, Big Shoulders Display, Spline Sans Mono (SIL OFL 1.1)
- Assets
- The network drawing on the cover and the two map examples, drawn in code (Ignacio Ferro, CC BY 4.0)
Method
#1 · Register the brand's faces, build, and give the PDF the same bytes
await loadBrandFonts(); // the answer, step 1
for (const [fileId, markup] of Object.entries(ART)) await loadSvg(fileId, markup);
const doc = buildDocument({ markdown, resources }, config());
showPages(doc, { title: 'Metro de Alba · Identity manual' });
offerPdf(() => renderToPdf(doc, { fontProvider: brandFontProvider, resourceBytes: imageBytes }),
`${RECIPE}.pdf`); // step 2: the provider hands renderToPdf the same files
Layout measures every word with the faces in document.fonts, so loadBrandFonts() in the short answer fetches each file once, keeps its bytes and registers a FontFace built from them before buildDocument runs. The kit's kitFonts only fetches from Fontsource, and a brand serves its files from its own server. renderToPdf asks for the faces the pages paint, and brandFontProvider answers each request with the bytes already fetched; a weight or slant the brand lacks would get the closest file of the same family (Why a font provider?). The PDF embeds the six files the canvas measured, each once.
#2 · The colour system is one list
const COLOURS = [ // id, name, screen, print (coated stock)
['line-1', 'Line 1 · Tile red', '#e4572e', '0 75 85 0'],
['line-2', 'Line 2 · Harbour teal', '#17bebb', '75 0 32 0'],
['line-3', 'Line 3 · Broom yellow', '#ffc914', '0 22 95 0'],
['line-4', 'Line 4 · Heather', '#6c4f9e', '65 75 0 0'],
['line-5', 'Line 5 · Pine', '#3f9b4a', '76 12 90 2'],
['signal-red', 'Signal red', '#c0391b', '10 88 100 2'],
['signal-green', 'Signal green', '#2b7d3c', '84 25 95 10'],
['ink', 'Ink', '#1f2124', '72 62 55 78'],
['rule', 'Rule grey', '#d9d9d4', '14 10 14 0'],
];
const palette = { ...Object.fromEntries(COLOURS.map(([id, , hex]) => [id, hex])),
paper: '#ffffff', section: '#e4572e' }; // section: the line colour of the current section
// col(): a colour linked to its palette entry, with the entry's hex beside the link.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [...Object.entries(palette), ['main-color', palette.ink]]
.map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const rgb = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)).join(' ');
const swatchTable = () => COLOURS.reduce( // an empty first cell, filled with the colour itself
(model, [id], i) => setCellBackground(model, { row: i + 1, col: 0 }, col(id)),
{ headerRowCount: 1, columnWidths: [22, 34, 14, 15, 15], rows: [
['COLOUR', 'NAME', 'HEX', 'RGB', 'CMYK'].map((content) => ({ content, isHeader: true })),
...COLOURS.map(([, name, hex, cmyk]) =>
['', name, hex.toUpperCase(), rgb(hex), cmyk].map((content) => ({ content }))),
] });
Because the palette and Table 1.1 are built from the same nine rows, the table cannot list a value the pages do not use. setCellBackground fills the empty first cell of each row with that row's colour, linked to the palette. In the text, :swatch{color="line-2"} takes a palette id and draws a square outlined in the text colour. main-color has the hex of Ink, so headings and bold and italic runs, whose defaults link to it, print in Ink instead of the engine's blue. bodyText.referenceColor: col('ink') names Ink for references as well (Color Palette).
#3 · One opener, three line colours
// The body starts ten grid lines down, in both columns.
const opener = { enabled: true, minHeight: pt(10 * LEAD), slot: { elements: [
{ kind: 'text', id: 'number', content: '{number}', fontFamily: DISPLAY, fontWeight: 800,
fontSize: pt(130), lineHeight: 1, color: col('section'), align: 'left', overflow: 'wrap',
// Nudged by eye on the capture: the cap tops of number and title on one line.
placement: { anchor: { to: 'container', edge: 'top-left' },
offset: { x: mm(-1.5), y: mm(1.3) } } },
{ kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY, fontWeight: 800,
fontSize: pt(34), lineHeight: 1, color: col('ink'), align: 'left', overflow: 'wrap',
placement: { anchor: { to: 'container', edge: 'top-left' },
offset: { x: mm(COL + GUTTER), y: mm(1) }, size: { width: mm(COL) } } },
{ kind: 'text', id: 'lead', content: '{attr.lead}', fontFamily: TEXT, fontSize: pt(12.5),
lineHeight: 1.36, color: col('ink'), align: 'left', overflow: 'wrap',
placement: { anchor: { to: '#title', edge: 'below' }, offset: { y: mm(3) },
size: { width: mm(COL) } } },
] } };
// Each section sets `section` to its line's colour; the number and the head square use it.
const section = (id) => ({ id, palette: { section: palette[id] } });
numberingTemplate: '{1:01}' writes the counter with two digits, and {number} prints 01, 02 and 03 in the opener; the cover heading is numbered: false and gets no number. The three section styles differ only in the palette entry section, which each sets to its line's colour. The number and the square in the band are linked to section, so one opener design serves all three sections. minHeight reserves ten lines of the 14 pt grid for the opener, and the text of every section starts on the same grid line of its page.
#4 · Do and Don't are figure types
const example = (id, name, colour) => ({ id, name, shortLabel: name, captionPrefix: name,
numberingTemplate: '{n}', resetOn: 'never', counterFormat: 'decimal',
captionStyle: { labelColor: col(colour) } });
const resourceTypes = [...defaultResourceTypes(LANG),
example('do', 'Do', 'signal-green'), example('dont', 'Don’t', 'signal-red')];
const FOOT = { position: 'bottom' }; // cited in one paragraph: its page's foot, one per column
A resource type can carry a partial captionStyle, and these two set only the label colour, Signal green for Do and Signal red for Don't (Resource types). The signals reach 5.1:1 and 5.5:1 on white, while lines 1, 2, 3 and 5 stay under the 4.5:1 that small text needs. Both drawings float with position: 'bottom' and are cited in the same paragraph, the first under Drawing the map, so they share the foot of page 4, Do in the left column and Don't in the right.
#5 · The bundle packs the fonts it may share
const pack = Object.assign(document.createElement('button'), { type: 'button',
textContent: 'Build the .postext' });
pack.addEventListener('click', async () => {
const { bytes, manifest, warnings } = await createBundle({
name: 'Metro de Alba identity manual', locale: LANG, markdown, config: config(), resources,
files: new Map([...Object.entries(ART), ...fontFiles]), // fileId → SVG markup or font bytes
});
const size = `${Math.round(bytes.length / 1024)} KB`;
const packed = `fonts inside: ${manifest.fonts.map((font) => font.name).join(', ')}`;
kitStatus(['.postext', size, packed, ...warnings].join(' · ')); // warnings: what stayed out
pack.replaceWith(Object.assign(document.createElement('a'), { download: `${RECIPE}.postext`,
href: URL.createObjectURL(new Blob([bytes], { type: 'application/zip' })),
textContent: `Download ${RECIPE}.postext · ${size}` }));
});
document.getElementById('pt-actions').append(pack);
createBundle reads config.customFonts, looks up each variant's bytes in files by its fileId and writes them under fonts/, with a fonts entry in the manifest. The display family carries redistributable: false, standing in for a licence that forbids handing the files on (Big Shoulders Display itself is under the OFL). Its file stays out, and warnings names the family. The 81 KB file holds the chapter, the configuration, the three drawings and five font files. Layout never reads customFonts; the pages come out the same without it (Creating a bundle).
The whole recipe
// ═══ Postext Cookbook · Nº 040 · Brand fonts in layout, PDF and bundle ════════════
// https://postext.dev/en/cookbook/brand-fonts-identity-manual
// Code: MIT · Text and drawings: original (CC BY 4.0) · Metro de Alba is a fictional network
// Fonts: Public Sans, Big Shoulders Display, Spline Sans Mono (OFL 1.1) · Needs postext ≥ 1.25.0
import {
buildDocument, renderPageToCanvas, registerResourceImage, defaultResourceTypes, setCellBackground,
createBundle,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'brand-fonts-identity-manual';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region answer: the brand's font files, fetched once for the layout, the PDF and the bundle
// Your licensed files, one per face in FONTS. Fontsource's copies stand in for them here:
// point FONT_URL at your own server (same origin, or one that lets this page in by CORS).
const slug = (family) => family.toLowerCase().replaceAll(' ', '-');
const FONT_URL = ({ family, weight, style }) => `https://cdn.jsdelivr.net/npm/@fontsource/`
+ `${slug(family)}@5/files/${slug(family)}-latin-${weight}-${style}.woff2`;
const brandFaces = () => Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) => {
const weight = parseInt(spec, 10), style = spec.endsWith('i') ? 'italic' : 'normal';
return { family, weight, style, fileId: `${slug(family)}-${weight}-${style}.woff2` };
}));
const fontFiles = new Map(); // fileId → the WOFF2 bytes, fetched once
// 1 · Layout measures with document.fonts: register every face before the first build.
async function loadBrandFonts() {
await Promise.all(brandFaces().map(async ({ family, weight, style, fileId }) => {
const res = await fetch(FONT_URL({ family, weight, style }));
if (!res.ok) throw new Error(`No file for ${family} ${weight} ${style}`);
fontFiles.set(fileId, new Uint8Array(await res.arrayBuffer()));
const face = new FontFace(family, fontFiles.get(fileId), { weight: `${weight}`, style });
document.fonts.add(await face.load());
}));
}
// 2 · The PDF embeds the same bytes as TrueType. renderToPdf asks for the faces the pages
// paint; a weight or slant the brand lacks gets the family's closest file, embedded once.
async function brandFontProvider(family, weight, style) {
const cost = (f) => (f.style === style ? 0 : 1000) + Math.abs(f.weight - weight);
const own = brandFaces().filter((f) => f.family === family);
if (!own.length) throw new Error(`${family} is not one of the brand's fonts`);
return decompressWoff2(fontFiles.get(own.reduce((a, b) => (cost(b) < cost(a) ? b : a)).fileId));
}
// 3 · The bundle: customFonts names each face's file by its fileId; createBundle packs the bytes
// of every family it may hand on. Layout never reads it (gotcha: custom-fonts-declarative).
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
#Pack the display face too
If the licence lets you hand the files on, drop the flag, and the bundle carries all three families in 96 KB.
- name, redistributable: name !== DISPLAY, // the display face reaches suppliers another way
+ name,#Use a real Bold
boldFontWeight: 600 sets bold runs, table heads and caption labels in the SemiBold, because the brand has no Bold; if your family has one, add its files to FONTS, delete the setting and rewrite the sample's specimen line and its “There is no Bold”, which would no longer hold.
- boldFontWeight: 600, // the brand has no Bold: its SemiBold sets **emphasis**
- 'Public Sans': ['400', '400i', '600', '600i'],
+ 'Public Sans': ['400', '400i', '600', '600i', '700', '700i'],Pitfalls
Pitfall
customFonts loads no font
config.customFonts only names font files by fileId: buildDocument and the canvas, HTML and PDF renderers never read it, so a family listed there and not registered is measured and painted in a fallback. Register each face yourself (a FontFace from its bytes) before the first build and give the same bytes to the PDF font provider. createBundle reads the list to pack the files into a .postext, and the Sandbox reads it to register the faces. Your own fonts →
Pitfall
A bold or italic the family lacks is faked on screen, not in the PDF
When text asks for a weight or style its family does not ship (a bold table header in a single-face label font, italic in a sans with no italics), the browser synthesises it on the canvas and in HTML, thickening or slanting the upright face on the same widths. A PDF embeds real faces only, so there the provider's closest face prints plain. Put only faces the family ships in your font list and set every style to match, such as tableStyle.headerBold: false. Fonts embedded in the PDF →
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 →
Pass createBundle each font's bytes under the fileId that customFonts gives it. A variant without bytes is left out with a “missing file, skipped” warning, and a family that loses every variant drops out of the manifest.
Credits
- Recipe
- Ignacio Ferro
- Text
- The Metro de Alba identity manual, a fictional network · Ignacio Ferro · CC BY 4.0
- Images
- The network drawing on the cover and the two map examples, drawn in code · Ignacio Ferro · CC BY 4.0
- Fonts
- Public Sans (SIL OFL 1.1) · Big Shoulders Display (SIL OFL 1.1) · Spline Sans Mono (SIL OFL 1.1)
Edit this write-up ↗ (opens in a new tab)Recipe folder on GitHub ↗ (opens in a new tab)


