跳到主要内容
食谱编号40

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

品牌字体用于版面、PDF和文件包

一本虚构地铁的视觉识别手册,用品牌自己的字体文件排版;文件只下载一次,版面、PDF的字体提供器和.postext文件包都复用它。

本页内容

第2–3页,共4页

  • 英文样例:尚无中文版本
  • 成品尺寸210 × 280 mm
  • 2栏, 栏间距8 mm
  • Public Sans 9.8/14
  • Big Shoulders Display
  • Spline Sans Mono
  • 4页
  • 难度
  • Postext 1.57.1
  • 排版用时76 ms
  • 246行代码

简单来说

一个虚构地铁系统的品牌手册。示例演示怎样把品牌专用字体下载一次,然后在预览、PDF和保存的文件里都用上它们。

成品一览

Metro de Alba视觉识别手册的四页。这是一个虚构的地铁系统,共有五条线路。封面上,五条线从左下角共用一条轨道出发,穿过一条灰色河流后向右分岔,上方是用Big Shoulders Display排的名称。每一节都在一条墨色色带下开始,配一个两位数的大号编号,颜色取其中一条线路的颜色。01 Colour里,表格第一列就是颜色本身;02 Type有样字行和一块站台指示牌;03 Usage最后是两幅带框的线路图,一幅按规则绘制(Do),一幅违反规则(Don't)。所有文字都用六个字体文件排版,脚本在第一次排版之前下载它们。PDF用同样的六个文件绘制,.postext文件包里带五个,因为标题字体被标为不可再分发。

这道食谱解答

  • 怎样在排版中使用自己的品牌字体或授权字体,并嵌入PDF?
  • 怎样在浏览器中导出嵌入字体的真正PDF?
  • 怎样让标题、粗体字和项目符号不再显示成蓝色?
  • 怎样在正文、题注或表注里加入色块图例?
  • 怎样用代码创建.postext文件包,把文档交给沙盒或其他程序?

简短回答

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

用料

类型
Public Sans, Big Shoulders Display, Spline Sans Mono(SIL OFL 1.1)
素材
  • The network drawing on the cover and the two map examples, drawn in code (Ignacio Ferro, CC BY 4.0)

做法

#1 · 注册品牌字体、构建文档,再把同样的字节交给PDF

script.js · 第448–453行在完整代码中
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

排版时用document.fonts里的字体测量每个词,所以简短回答里的loadBrandFonts()把每个文件下载一次,保留它的字节,并在buildDocument运行之前注册一个用这些字节创建的FontFace。套件里的kitFonts只从Fontsource下载,而品牌的字体文件放在自己的服务器上。renderToPdf只请求页面实际用到的字体,brandFontProvider用已经下载的字节回应每个请求;品牌没有的字重或斜体,则返回同一字体族里最接近的文件(为什么需要字体提供器?)。PDF嵌入Canvas测量过的六个文件,每个只嵌入一次。

#2 · 颜色系统就是一个列表

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

调色板和表1.1由同样的九行数据生成,所以表里不可能出现页面没用的值。setCellBackground把每行空着的第一格填上该行的颜色,并与调色板关联。正文里的:swatch{color="line-2"}接收一个调色板id,画一个用正文颜色描边的方块。main-color是Ink的十六进制值,所以默认关联它的标题、粗体和斜体都印成Ink,而不是引擎的蓝色。bodyText.referenceColor: col('ink')把交叉引用也写明为Ink(调色板)。

#3 · 一个章首页设计,三种线路颜色

script.js · 第93–110行在完整代码中
// 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}'把计数器写成两位数,{number}在章首页印出01、02和03;封面标题设为numbered: false,不带编号。三个章节样式只有调色板条目section不同,各自设成本线路的颜色。色带里的编号和方块都关联到section,所以一个章首页设计就能用于三节。minHeight为章首页预留14 pt网格的十行,每一节的正文都从本页同一条网格线开始。

#4 · Do和Don't是两种图类型

script.js · 第159–164行在完整代码中
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

资源类型可以带一个局部的captionStyle,这两种只设置标签颜色:Do用Signal green,Don't用Signal red(资源类型)。两种信号色在白底上的对比度是5.1:1和5.5:1,而1、2、3、5号线的颜色都低于小字所需的4.5:1。两幅图都用position: 'bottom'浮动,并在同一段里引用,也就是Drawing the map下的第一段,所以它们共享第4页的页脚:Do在左栏,Don't在右栏。

#5 · 文件包只装可以分发的字体

script.js · 第457–471行在完整代码中
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读取config.customFonts,按每个变体的fileId在files里找到对应字节,写到fonts/下,并在清单里加一个fonts条目。标题字体族带有redistributable: false,用来模拟禁止转交文件的授权许可(Big Shoulders Display本身采用OFL)。它的文件不会打包进去,warnings会列出这个字体族。81 KB的文件里有章节、配置、三幅图和五个字体文件。排版从不读取customFonts,没有它,页面也完全一样(创建文件包)。

完整食谱

沙盒
// ═══ 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).

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

变化

#把标题字体也打包

如果授权允许转交文件,去掉这个标志,文件包就会带上全部三个字体族,大小为96 KB。

-  name, redistributable: name !== DISPLAY, // 标题字体通过别的途径交给供应商
+  name,

#用真正的Bold

因为品牌没有Bold,boldFontWeight: 600让粗体、表头和题注标签都用SemiBold排。如果你的字体族有Bold,把它的文件加进FONTS,删掉这项设置,再改写示例里的样字行和其中那句“There is no Bold”,因为它已不再成立。

-    boldFontWeight: 600, // 品牌没有Bold:**强调**用它的SemiBold排
-  'Public Sans': ['400', '400i', '600', '600i'],
+  'Public Sans': ['400', '400i', '600', '600i', '700', '700i'],

常见问题

易错点

customFonts不会加载任何字体

config.customFonts只是按fileId列出字体文件:buildDocument以及Canvas、HTML和PDF渲染器从不读取它,所以列在这里却没有注册的字体家族会用后备字体测量和绘制。在第一次构建前自己注册每个字型(用其字节创建FontFace),并把同样的字节交给PDF字体提供者。createBundle读取这个列表,把文件打包进.postext;沙盒读取它来注册字型。 使用自己的字体 →

易错点

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

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

易错点

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

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

交给createBundle的每个字体的字节,都要放在customFonts为它指定的fileId下。没有字节的变体会被省略,并给出“missing file, skipped”警告;一个字体族的变体全部缺失时,它会从清单里消失。

致谢

文本
  • The Metro de Alba identity manual, a fictional network · Ignacio Ferro · CC BY 4.0
图片
  • The network drawing on the cover and the two map examples, drawn in code · Ignacio Ferro · CC BY 4.0
字体
Public Sans (SIL OFL 1.1) · Big Shoulders Display (SIL OFL 1.1) · Spline Sans Mono (SIL OFL 1.1)
沙盒PDF