In short
A four-page programme for an evening concert. It shows how to save it as a PDF that matches the screen exactly, with its fonts inside and each heading listed for quick jumps.
What you'll build
The programme for a twilight recital, Home from Sea: four A5 pages for a consort of soprano, cello and harp. The cover is night teal, with the title in gilt Fraunces italic and rows of gilt wave scales rising from the foot. Inside, the order of performance is a table with a teal head in Tenor Sans capitals and a tinted total row. The notes are justified Crimson Text. The words of the three songs are poems by Longfellow, Stevenson and Tennyson, set with the indents of their printed editions. The Build the PDF button makes the file you would email to the audience or put on the venue's website. Its four pages match the screen line for line. It embeds only the five font files the browser loaded, and each heading is a bookmark. For commercial printing, see the print-ready PDF.
This recipe answers
- How do I export a real PDF in the browser with the fonts embedded?
- Why do my line breaks change, or PDF words overlap, and how do I load fonts correctly?
The short answer
// Hook-up: `await registerFaces()` before the first build; `renderToPdf(doc, { fontProvider })`.
const files = new Map(); // 'crimson-text-latin-600-normal' → its WOFF2 (gotcha: latin-subset)
function fontFile(family, weight, style) {
const id = family.toLowerCase().replaceAll(' ', '-'), file = `${id}-latin-${weight}-${style}`;
if (!files.has(file)) {
files.set(file, fetch(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${file}.woff2`)
.then((res) => {
if (!res.ok) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
return res.arrayBuffer();
}));
}
return files.get(file);
}
const facesOf = (family) => (FONTS[family] ?? []).map((spec) =>
({ spec, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' }));
// The screen: a FontFace per face, from those bytes, before the first build.
const registerFaces = () => Promise.all(Object.keys(FONTS).flatMap((family) =>
facesOf(family).map(async ({ weight, style }) => {
const face = new FontFace(family, await fontFile(family, weight, style),
{ weight: `${weight}`, style });
document.fonts.add(await face.load());
})));
// The PDF: the same bytes as TrueType. renderToPdf asks for each face the pages paint and no
// other. A face FONTS lacks gets the closest one it has, and is logged as a stand-in: the
// status line should list none.
const embedded = new Set(), standIns = new Set(); // shown once the PDF is ready
async function fontProvider(family, weight, style) {
if (!FONTS[family]) throw new Error(`${family} is not in FONTS: no page was set in it`);
const cost = (f) => (f.style === style ? 0 : 1000) + Math.abs(f.weight - weight);
const best = facesOf(family).reduce((a, b) => (cost(b) < cost(a) ? b : a));
const asked = `${weight}${style === 'italic' ? 'i' : ''}`;
embedded.add(`${family} ${best.spec}`);
if (asked !== best.spec) standIns.add(`${family} ${asked} → ${best.spec}`);
return decompressWoff2(new Uint8Array(await fontFile(family, best.weight, best.style)));
}
One download per face: the layout measures it, the PDF embeds it
Ingredients
- Features
- Fonts embedded in the PDFPDF exportPDF bookmarksFonts before layoutBody typeDocument metadataCovers, title pages and colophonsDesigned openersHeading stylesHeading attributesRunning heads per sectionLine breaks in titlesRunning heads and foliosPictures in page designsPaper colourCustom resource typesFigures exactly hereTable styleParagraph stylesPages on a canvas
- Type
- Crimson Text, Fraunces, Tenor Sans (SIL OFL 1.1)
- Assets
- The seigaiha waves on the cover, drawn in code in the page’s palette (Ignacio Ferro, CC BY 4.0)
Method
#1 · One download per face, for the page and for the PDF
The code is the short answer above. Postext measures every word with the faces the browser has loaded when the build runs, and the PDF draws each line where that layout put it. If the PDF embeds a different file, such as a variable font's default instance or a system fallback, each word still starts at its measured position, but its letters have other widths, so words overlap or leave gaps. The recipe therefore fetches each face once. Its bytes become a FontFace before the first build, and the font provider passes the same bytes through decompressWoff2 for the PDF, so the export downloads no fonts of its own.
#2 · Fonts first, then the layout
await registerFaces(); // the answer: every face in FONTS, from its own bytes
await loadSvg('cover.svg', coverArt(PAGE.width, PAGE.height, WAVES));
// Every face is declared by now; one FONTS forgot would come from Fontsource, for the screen only.
const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
showPages(doc, { title: 'Home from Sea · a recital programme' });
registerFaces() resolves only when every face in FONTS has loaded, so the first build measures with the faces the PDF will embed. It is also the only build, because FONTS lists every face the pages set, and buildDocumentWithFonts finds every face it looks for already declared (Loading fonts before layout). That check only helps the screen. If FONTS misses a face, the engine asks the kit for it, loads the Fontsource file and runs the layout again with no console warning, but the PDF still gets the closest face the provider has.
#3 · The export, and a list of what it embedded
const bar = Object.assign(document.createElement('progress'), { max: 1, value: 0 });
const list = (faces) => [...faces].join(', ') || 'none';
offerPdf(() => {
document.getElementById('pt-actions').prepend(bar);
return renderToPdf(doc, {
fontProvider, // the answer: the page's own font files
resourceBytes: imageBytes, // the cover drawing, as vector paths
outlines: true, // the default, spelled out: each heading becomes a bookmark
onProgress: ({ phase, pages, totalPages }) => {
bar.value = pages / totalPages;
const says = { prepare: 'fonts and cover embedded', pages: `page ${pages} of ${totalPages}`,
save: `embedded: ${list(embedded)} · stand-ins: ${list(standIns)}` };
kitStatus(`PDF · ${says[phase]}`);
},
});
}, `${RECIPE}.pdf`);
renderToPdf calls onProgress in three phases: prepare once the fonts and the cover are embedded, pages after each page, and save before it writes the file. It asks the provider only for the faces the pages paint, here five. The status line lists the five files the provider served, exactly the ones in FONTS, and no stand-in. A stand-in points to a face missing from FONTS. If you remove Crimson Text 600, the line reports Crimson Text 600 → 400 and the bold The Harbour Consort on page 4 prints at regular weight. CodePen's preview cannot show a PDF, so the kit's offerPdf replaces the button with two links, one that opens the PDF in a new tab and one that downloads it (Generating PDFs).
#4 · The heading tree is the bookmark tree
const headings = { fontFamily: 'Fraunces', fontWeight: 300, color: col('band'),
marginTop: pt(0), marginBottom: pt(0), // a two-line H2 carries its own space above
levels: [ // a section opens on the next page, left or right: a programme has no blank pages
{ level: 1, breakBefore: { enabled: true, parity: 'any' }, advancedDesign: opener },
{ level: 2, ...H2 },
] };
// The performers: a top-level bookmark, no break, no opener (gotcha: style-inherits-break).
const aside = { id: 'aside', breakBefore: { enabled: false }, advancedDesign: { enabled: false },
...H2, marginTop: pt(LEAD) };
In the PDF, the bookmarks panel shows the cover's title, Programme with About the music under it, The texts with its three songs, and The performers. The outline follows the heading levels, so choose them with the bookmarks in mind: here, an H1 per section and an H2 per song. The performers has a heading style of its own, an H1 with no page break and no opener, so it shares page 4 with Tennyson's poem and still gets a top-level bookmark. The \\ that breaks the cover title in two becomes a space in the bookmark.
#5 · Title and author from the frontmatter
const cover = {
id: 'cover', span: 'page', header: { elements: [] }, footer: { elements: [] },
advancedDesign: { enabled: true, slot: { elements: [
{ kind: 'image', id: 'night', resourceId: 'cover',
placement: { anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill' } } },
text('consort', '{author}', at('page', 'top', 18), label(8.5, 'gilt')),
text('title', '{titleText}', at('page', 'top', 26, 120), // the \\ in the heading breaks it
{ ...title(68), lineHeight: 0.95, color: col('gilt') }),
text('subtitle', '{subtitle}', at('page', 'top', 75, 66), { fontFamily: 'Crimson Text',
italic: true, fontSize: pt(12.5), lineHeight: 1.25, color: col('foam') }),
text('when', '{attr.when}', at('page', 'top', 91), label(LABEL, 'foam')),
text('where', '{attr.where}', at('page', 'top', 96), label(LABEL, 'foam')),
] } },
};
The cover prints two frontmatter values through {author} and {subtitle}, and the PDF's document properties take the title Home from Sea and the author The Harbour Consort from the same block. The date and the venue are attributes of the cover heading. The drawing behind them is one SVG the width of the page, and the PDF keeps it as vector paths.
The whole recipe
// ═══ Postext Cookbook · Nº 025 · A real PDF with the same fonts embedded ═══════════
// https://postext.dev/en/cookbook/pdf-with-embedded-fonts
// Code: MIT · Text: notes original (CC BY 4.0), poems in the public domain · Cover: drawn in code
// Fonts: Crimson Text, Fraunces, Tenor Sans (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} 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 = 'pdf-with-embedded-fonts';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region answer: one download per face: the layout measures it, the PDF embeds it
// Hook-up: `await registerFaces()` before the first build; `renderToPdf(doc, { fontProvider })`.
const files = new Map(); // 'crimson-text-latin-600-normal' → its WOFF2 (gotcha: latin-subset)
function fontFile(family, weight, style) {
const id = family.toLowerCase().replaceAll(' ', '-'), file = `${id}-latin-${weight}-${style}`;
if (!files.has(file)) {
files.set(file, fetch(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${file}.woff2`)
.then((res) => {
if (!res.ok) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
return res.arrayBuffer();
}));
}
return files.get(file);
}
const facesOf = (family) => (FONTS[family] ?? []).map((spec) =>
({ spec, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' }));
// The screen: a FontFace per face, from those bytes, before the first build.
const registerFaces = () => Promise.all(Object.keys(FONTS).flatMap((family) =>
facesOf(family).map(async ({ weight, style }) => {
const face = new FontFace(family, await fontFile(family, weight, style),
{ weight: `${weight}`, style });
document.fonts.add(await face.load());
})));
// The PDF: the same bytes as TrueType. renderToPdf asks for each face the pages paint and no
// other. A face FONTS lacks gets the closest one it has, and is logged as a stand-in: the
// status line should list none.
const embedded = new Set(), standIns = new Set(); // shown once the PDF is ready
async function fontProvider(family, weight, style) {
if (!FONTS[family]) throw new Error(`${family} is not in FONTS: no page was set in it`);
const cost = (f) => (f.style === style ? 0 : 1000) + Math.abs(f.weight - weight);
const best = facesOf(family).reduce((a, b) => (cost(b) < cost(a) ? b : a));
const asked = `${weight}${style === 'italic' ? 'i' : ''}`;
embedded.add(`${family} ${best.spec}`);
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
#Leave the bookmarks out
A one-page flyer or a poster has nothing to bookmark. With outlines: false the PDF has no outline, and it opens with the sidebar closed.
- outlines: true, // the default, spelled out: each heading becomes a bookmark
+ outlines: false,#Serve the fonts yourself
Point the fetch at your own copies of the same static WOFF2 files, one per weight and style, under Fontsource's file names. The page and the PDF still share each download.
- files.set(file, fetch(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${file}.woff2`)
+ files.set(file, fetch(`/fonts/${file}.woff2`)
.then((res) => {
- if (!res.ok) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
+ if (!res.ok) throw new Error(`No font file ${file}.woff2`);Pitfalls
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 →
Pitfall
A heading style inherits its level's page break
A headingStyles entry takes every field it leaves out from its heading level, breakBefore included. A contents page or a colophon styled on an H1 after a :::pagebreak inherits parity 'odd' and lands behind a blank page. Give such a style breakBefore: { enabled: false }. Heading styles →
List in FONTS every face your pages set, the bold and the italic of the text among them. If one is missing, the screen still looks right, because the kit loads the face without a warning, but the PDF prints the provider's nearest face, and only the stand-ins on the status line reveal the swap.
Use static files, one per weight and style. From a variable WOFF2 the PDF embeds only the default instance, so a bold run would print at regular weight (Why a font provider?).
Credits
- Recipe
- Ignacio Ferro
- Text
- “The Tide Rises, the Tide Falls”, with its indents, as printed in The Complete Poetical Works of Henry Wadsworth Longfellow · Henry Wadsworth Longfellow · public domain
- “Requiem”, with the indents and italics of the first edition of Underwoods (1887) · Robert Louis Stevenson · public domain
- “Crossing the Bar”, with its indented short lines, from the first edition of Demeter and Other Poems (1889), in the proofread Wikisource transcription · Alfred Tennyson · public domain
- The programme, the notes on the music, the performers and the colophon · Ignacio Ferro · CC BY 4.0
- Images
- The seigaiha waves on the cover, drawn in code in the page’s palette · Ignacio Ferro · CC BY 4.0
- Fonts
- Crimson Text (SIL OFL 1.1) · Fraunces (SIL OFL 1.1) · Tenor Sans (SIL OFL 1.1)
Edit this write-up ↗ (opens in a new tab)Recipe folder on GitHub ↗ (opens in a new tab)


