简单来说
一本展示三款字体的四页样本册。示例说明为什么要等所有字体加载完再排版,否则行会在错误的位置断开。
成品一览
House Specimen Nº 3出自虚构的Pellow Lane Press,是一份展示三款字体的四页样张。封面上,群青色底里是240 pt的白色Noto Serif Display斜体Ag,以及两行写着三款字体名字的等宽字;标题在色底下方。第2页把Ysabeau Office从7 pt到14 pt排成字号阶梯,然后排西班牙语、波兰语和捷克语的全字母句,其中的ż、ř和ů需要第二个字体文件。第3页是检查表:一张由pen填写的IBM Plex Mono表格,列出小册子声明的十款字体、页面实际用到的六款,以及浏览器为每款字体下载的文件。第4页把第1页的第一段排两次,分别来自一次提早的构建和最后一次构建。提早的那次在浏览器还没有任何字体文件时运行,所以行尾落在别处,有几行越过了行长。
这道食谱解答
- 为什么断行会变,或者PDF中的字互相重叠?怎样正确加载字体?
- 怎样在排版中使用自己的品牌字体或授权字体,并嵌入PDF?
- 怎样找出文档哪里出了问题(警告、溢出、版面不收敛)?
简短回答
// 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' });
用料
做法
#1 · 声明每个文件,但不下载
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);
}
}
}
一个FontFace对应一个文件,和一条@font-face规则一样,所以一款有latin和latin-ext两个文件的字体要用两个FontFace对象声明,它们的字体族、字重和样式相同,只有unicodeRange不同,照抄字体族CSS里的值即可。把它们加进document.fonts不会下载任何东西:浏览器只在load()调用或某行文字需要其中的字符时才获取文件。页面声明过的字体,Postext通过document.fonts加载;没有人声明的字体,它向resolve选项要文件,其他食谱就是这样从工具包拿到Fontsource文件的。配置里的customFonts只描述.postext文件包里的文件,所以用Markdown构建的页面要么自己声明字体,要么提供一个resolve。
#2 · 先加载字体,再构建
代码见上文的简短回答。buildDocumentWithFonts先调用prepareFonts:它从配置和文字里读出要用的每一款字体,包括每种字重和样式,并以文档自己的字符为样本加载,所以latin-ext文件会随波兰语和捷克语的全字母句一起到达(排版前加载字体)。然后它构建,读出页面实际用到的字体,加载配置没有写明的那些,再构建一次。onFonts收到最后这次检查的报告:已加载的字体(loaded)、缺失的字体(missing),以及浏览器会用别的字重或样式伪造的字体(synthesized)。pen一共构建三次,因为小册子要印出自己的证据:一次故意提早,一次字体到齐,最后一次把表格和图片填好。
#3 · 用报告生成检查表
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'}` };
}
表格从FONTS声明的字体出发,再加上报告对每款字体的说法:页面用它排了文字、浏览器伪造了它,或者它落到了后备字体上。最后一列列出FontFace状态变为loaded的文件。二十个文件里下载了十六个:Postext会加载正文字体族的全部四款,因为任何段落都可能用**和*要到它们;等宽字体的两款斜体没有任何设置提到,所以始终没有下载。附注还从排好的文档里读三样东西:contentWarnings,用后备字体测量的字体在这里列为fontFallback;converged,版面的各轮计算稳定下来时为true;以及warnings。显示或导出页面之前,三样都要检查。
#4 · 留一次提早的构建作证据
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);
}
pen在声明任何字体之前先调用一次buildDocument,所以这次构建用浏览器的后备字体测量每个词。真正的字体到位后,pen把它再画一遍,逐行与最后一次构建比较;题注里的行数来自这次比较,字体数则来自提早构建自己的fontFallback警告。一行用较窄的后备字体测量的普通文字会越过行长,直到栏的裁剪边界(边缘外2 pt)截掉最后几个字母,所以pen用加宽的栏绘制第1页,显示完整的越界部分。Canvas和postext-pdf把两端对齐或混合样式的行中每一段文字画在版面测量它的位置,所以比后备字体宽的真实字体会压到下一个词上,字体到达之前构建的PDF里,词会叠在一起。提早构建的结果不会带到下一次:prepareFonts在document.fonts里发现新字体,就丢弃在这些字体族里测得的宽度,所以不必调用clearMeasurementCache()。
#5 · 按正文节奏排的字号阶梯
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以11/15.5 pt排正文,段落之间空一行而不缩进。正文齐左,所以每个词间距都保持自然宽度。粗体、斜体和引用都用墨色;不设的话,它们会用主色。字号阶梯的每个字号和每句全字母句都是一个两倍行距(31 pt)高的段落样式,所以页面保持正文15.5 pt的节奏。字号标签是等宽字体的行内标签,一位数的字号左右各加半个字母宽的内边距,让每个样本都从同一条边开始。
#6 · 一张封面上的三款字体
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) } }),
] } } });
封面是一级标题的设计:标题glyphs属性里的字母用240 pt的展示字体排出,下面两行等宽字写着这款字体以及正文和标签字体的名字,就像铸字厂的样张那样。span: 'page'让标题通栏,色底挂在出血框的左上角,所以延伸出上边缘。minHeight从上页边距起算,一直预留到Y.end,即色底下方42 mm;不设的话,正文会高一行开始,紧贴在导语下面。
完整食谱
// ═══ 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
组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)
变化
#用resolve提供文件
从一段Markdown字符串到一页设计好的版面里的kitFonts(FONTS)什么都不声明:Postext向它的resolve要每款字体的文件,并自己把它们加进document.fonts。
#漏掉一款字体
去掉IBM Plex Mono的粗体(眉题、表头和题注标签用它排):浏览器把常规体加粗,表格把这款字体标为faked,附注统计到一条fontFallback警告,警告指出IBM Plex Mono 700是synthesized。
- 'IBM Plex Mono': ['400', '400i', '700', '700i'], // labels, chips, the table, captions
+ 'IBM Plex Mono': ['400', '400i', '700i'], // labels, chips, the table, captions#把同样的字体嵌进PDF
renderToPdf为每款字体嵌入其fontProvider返回的字节,而嵌入同样字体的真正PDF里的提供者用的是Fontsource的latin文件,只覆盖到Latin-1:为了这本小册子里的ż、ł、ř和ů,要让它从你自己的文件夹返回每款字体的完整字体文件。
常见问题
易错点
Fontsource的文件只覆盖字母,不含符号
工具包嵌入每种字体在Fontsource的latin文件;正文用到č、ł、†时再嵌入latin-ext文件,用到α、χ时再嵌入greek文件(字体族须有该文件:Lora和Gelasio没有),屏幕和PDF都一样。→、≈、✓、★等符号不在这些文件里,会在PDF中缺失:把它们画出来、写成数学公式,或换用文件中包含它们的字体。 嵌入PDF的字体 →
版面警告 · fontFallback
排版时使用了后备字体
原因. 排版时,文字所用的某个字体不在字体集合中(`reason: 'missing'`),或该字体族没有对应字重或倾斜的文件,浏览器用同族的其他字体模拟(`'synthesized'`);因此断行是用一种与PDF所嵌入字体不同的字体测量的。
解决. 在首次构建前加载字体:`prepareFonts(content, config, { resolve })`,或用`buildDocumentWithFonts`构建,它还会加载页面实际用到的字体并重新构建。对`synthesized`,请加载该字重或倾斜,或改用该字体族提供的字重。 文档 →
沙盒检查 · missingFont
缺少字体
原因. 配置中指定的某个字体族没有在浏览器中加载,因此文字是用系统后备字体测量和绘制的。
解决. 改正字体族名称(只写一个字体族,不要写CSS字体栈),并在第一次构建前加载所有字面;在pen中,把它列入FONTS。 文档 →
沙盒检查 · missingFontVariant
缺少字体变体
原因. 某个自定义字体族缺少文档用到的字重和样式对应的文件,比如斜体或粗体。
解决. 上传或声明缺少的变体,或者不再使用那个字重或样式。 文档 →
- 如果自己加载字体,不带样本文字的
document.fonts.load(font)只加载覆盖空格的那个文件,即latin文件,ż和ř会回退到系统字体。prepareFonts传入的是文档自己的字符。 renderPageToCanvas和postext-pdf在每栏边缘外2 pt处裁剪,所以用较窄的后备字体测量的行会丢掉最后几个字母。测量它的那次构建会在doc.contentWarnings里把这款字体列为fontFallback:显示或导出页面之前先读这份清单。
致谢
- 文本
- 原创文字, CC BY 4.0
- 字体
- Ysabeau Office (SIL OFL 1.1) · Noto Serif Display (SIL OFL 1.1) · IBM Plex Mono (SIL OFL 1.1)


