跳到主要内容
食谱编号25

排版食谱 · 第10章 · 输出与集成

嵌入同一套字体的真正PDF

把一份独奏会节目单导出为PDF。每款字体只下载一次,同时供FontFace和PDF使用,每个标题都成为一个书签。

本页内容
输出
Canvas · PDF
难度
中级
Postext
已用Postext 1.65.0测试
需要≥ 1.25.0 · postext-pdf ≥ 1.25.0
许可证
更新于2026年10月10日
代码MIT · 文本CC BY 4.0
  • 英文样例:尚无中文版本
  • 成品尺寸148 × 210 mm
  • 1栏
  • Crimson Text 10/13.3
  • Fraunces
  • Tenor Sans
  • 4页
  • 难度
  • Postext 1.57.1
  • 排版用时54 ms
  • 180行代码

简单来说

一份四页的黄昏音乐会节目单。示例演示怎样导出与屏幕显示完全一致的PDF,字体随文件保存,每个标题都能在书签里点击跳转。

成品一览

一场黄昏独奏会的节目单,题为Home from Sea:四页A5,演出者是由女高音、大提琴和竖琴组成的小乐团。封面为夜色蓝绿,标题用金色Fraunces斜体,一排排金色波纹鳞片从页脚升起。内页的演出曲目是一个表格,表头用Tenor Sans大写字母、蓝绿底色,合计行着浅色。乐曲解说用两端对齐的Crimson Text。三首歌的歌词分别是朗费罗、史蒂文森和丁尼生的诗,按印刷版本的缩进排出。点Build the PDF按钮,得到的就是你要发给听众或放在场馆网站上的文件。它的四页与屏幕上逐行一致,只嵌入浏览器已加载的五个字体文件,每个标题都是一个书签。如果要交付商业印刷,参见可直接付印的PDF。

这道食谱解答

  • 怎样在浏览器中导出嵌入字体的真正PDF?
  • 为什么断行会变,或者PDF中的字互相重叠?怎样正确加载字体?

简短回答

script.js · 第15–51行在完整代码中
// 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)));
}

用料

类型
Crimson Text, Fraunces, Tenor Sans(SIL OFL 1.1)
素材
  • The seigaiha waves on the cover, drawn in code in the page’s palette (Ignacio Ferro, CC BY 4.0)

做法

#1 · 每款字体只下载一次,页面和PDF共用

代码见上文的简短回答。Postext用构建时浏览器已加载的字体测量每个词,PDF则把每一行画在版面给它的位置上。如果PDF嵌入的是另一个文件,比如可变字体的默认实例或系统后备字体,每个词仍从测量出的位置开始,但字母宽度不同,于是词与词重叠或留出空隙。所以本食谱每款字体只下载一次:它的字节在第一次构建之前变成一个FontFace,字体提供器再把同样的字节交给decompressWoff2供PDF使用,导出时不会另行下载任何字体。

#2 · 先字体,后版面

script.js · 第363–367行在完整代码中
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()要等FONTS中的每款字体都加载完才会完成,所以第一次构建所用的字体就是PDF将要嵌入的字体。这也是唯一一次构建:FONTS列出了页面上用到的每款字体,buildDocumentWithFonts要找的每款字体都已经声明好了(排版前加载字体)。这项检查只对屏幕有用。如果FONTS漏了某款字体,引擎会向工具包要这款字体,加载Fontsource的文件并重新排版,控制台不给警告。但PDF拿到的仍是提供器手里最接近的那款字体。

#3 · 导出,并列出嵌入了什么

script.js · 第371–386行在完整代码中
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分三个阶段调用onProgress:字体和封面嵌入后为prepare,每排完一页为pages,写文件之前为save。它只向提供器要页面上实际印出的字体,这里是五款。状态行列出提供器给出的五个文件,正好是FONTS里的那些,没有替代。出现替代,就说明FONTS里缺了某款字体。如果删掉Crimson Text 600,状态行会报告Crimson Text 600 → 400,第4页粗体的The Harbour Consort会以常规字重印出。CodePen的预览无法显示PDF,所以工具包的offerPdf把按钮换成两个链接,一个在新标签页打开PDF,一个下载它(生成PDF)。

#4 · 标题树就是书签树

script.js · 第108–116行在完整代码中
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) };

在PDF里,书签面板显示封面标题、Programme及其下的About the music、The texts及其三首歌,以及The performers。大纲沿用标题的级别,所以选级别时要考虑书签:这里每个部分用一个H1,每首歌用一个H2。The performers有自己的标题样式,是一个不分页、不做章首页的H1,因此它与丁尼生的诗同在第4页,仍然得到一个顶层书签。把封面标题断成两行的\\在书签里变成一个空格。

#5 · 标题和作者取自frontmatter

script.js · 第80–93行在完整代码中
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')),
  ] } },
};

封面通过{author}和{subtitle}印出前置元数据里的两个值,PDF的文档属性也从同一块里取标题Home from Sea和作者The Harbour Consort。日期和场地是封面标题的属性。它们背后的图案是一张与页面等宽的SVG,PDF将其保留为矢量路径。

完整食谱

沙盒
// ═══ 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}`);

组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)

变化

#不要书签

单页传单或海报没有什么可做书签的。设outlines: false后,PDF不带大纲,打开时侧栏是关闭的。

-    outlines: true, // 默认值,这里明确写出:每个标题都成为一个书签
+    outlines: false,

#自己托管字体

让fetch指向你自己保存的同一套静态WOFF2文件,每个字重和样式一个文件,沿用Fontsource的文件名。页面和PDF仍共用每一次下载。

-    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`);

常见问题

易错点

字体家族缺少的粗体或斜体在屏幕上是模拟的,在PDF中则没有

当文字要求其字体家族没有提供的字重或样式时(只有一种字型的标签字体中的粗体表头,没有斜体的无衬线字体中的斜体),浏览器会在Canvas和HTML中合成它:在相同宽度上把正体字型加粗或倾斜。PDF只嵌入真实的字型,所以在PDF中,字体提供者给出的最接近的字型印出来是普通样式。字体列表里只放家族实际提供的字型,并让每种样式与之匹配,例如tableStyle.headerBold: false。 嵌入PDF的字体 →

易错点

Fontsource的文件只覆盖字母,不含符号

工具包嵌入每种字体在Fontsource的latin文件;正文用到č、ł、†时再嵌入latin-ext文件,用到α、χ时再嵌入greek文件(字体族须有该文件:Lora和Gelasio没有),屏幕和PDF都一样。→、≈、✓、★等符号不在这些文件里,会在PDF中缺失:把它们画出来、写成数学公式,或换用文件中包含它们的字体。 嵌入PDF的字体 →

易错点

标题样式会继承其级别的分页设置

headingStyles中的条目没有写出的字段都取自它所属的标题级别,breakBefore也不例外。在:::pagebreak之后以H1设置样式的目录页或版权页会继承parity 'odd',结果落在一张空白页之后。给这类样式设置breakBefore: { enabled: false }。 标题样式 →

在FONTS中列出页面上用到的每款字体,正文的粗体和斜体也在内。漏了一种时,屏幕看上去仍然正确,因为工具包会不加警告地加载这款字体;但PDF印出的是提供器最接近的字体,只有状态行上的替代项会暴露这次调换。

使用静态文件,每个字重和样式一个。对于可变WOFF2,PDF只嵌入它的默认实例,一段粗体会以常规字重印出(为什么需要字体提供器?)。

致谢

文本
  • “The Tide Rises, the Tide Falls”, with its indents, as printed in The Complete Poetical Works of Henry Wadsworth Longfellow · Henry Wadsworth Longfellow · 公有领域
  • “Requiem”, with the indents and italics of the first edition of Underwoods (1887) · Robert Louis Stevenson · 公有领域
  • “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 · 公有领域
  • The programme, the notes on the music, the performers and the colophon · Ignacio Ferro · CC BY 4.0
图片
  • The seigaiha waves on the cover, drawn in code in the page’s palette · Ignacio Ferro · CC BY 4.0
字体
Crimson Text (SIL OFL 1.1) · Fraunces (SIL OFL 1.1) · Tenor Sans (SIL OFL 1.1)
沙盒PDF