跳到主要内容
食谱编号185

排版食谱 · 第2章 · 字体与文字

用符号字体排逻辑与集合符号

一本逻辑小册子,所用字体都没有 ∀、∈、ℵ:symbolFont 指定 Noto Sans Math,由它在画布和 PDF 上画出这些符号和希腊字母。

本页内容
类型
教科书
输出
Canvas · PDF
难度
中级
Postext
已用Postext 1.73.0测试
需要≥ 1.73.0 · postext-pdf ≥ 1.73.0
许可证
更新于2026年11月10日
代码MIT · 文本CC BY 4.0
  • 英文样例:尚无中文版本
  • 成品尺寸155 × 235 mm
  • 1栏
  • Crimson Pro 11/15
  • Cormorant Garamond
  • IBM Plex Sans Condensed
  • 4页
  • 难度
  • Postext 1.73.0
  • 排版用时17 ms
  • 163行代码

简单来说

一个短章,教人读懂逻辑和集合论的符号。书里的字体没有这些符号,于是由第二种字体补上,屏幕上和打印的 PDF 里都一样。

成品一览

一本袖珍逻辑入门的第一章,页面 155 × 235 毫米:一条酒红色色带,上面用大字号排出本章的符号;接着四节逐个读出 ∀、∃、∈、∪、∅ 和 ℵ,公式既嵌在正文里,也在段落之间单独成行。正文用 Crimson Pro,标题用 Cormorant Garamond,标签用 IBM Plex Sans Condensed。Fontsource 提供的这三种字体文件里都没有 ∀、∈,也没有希腊字母。只需一项设置 symbolFont,就把 Noto Sans Math 放到每种字体后面:正文、标题、书眉和表格单元格里的符号都出自同一种字体,PDF 也把它们全部印出来。

这道食谱解答

  • 正文字体缺少逻辑与集合符号(∀、∈、ℵ)和希腊字母时,怎样让 PDF 印出它们而不是空框?

简短回答

script.js · 第34–47行在完整代码中
// None of the three faces has ∀, ∈, ℵ or Greek. config.symbolFont (below) lists Noto Sans
// Math after every family the document names: what a face lacks is drawn from it, at the
// face's size and colour, in the canvas, the PDF, the HTML and the EPUB.
const SYMBOLS = 'Noto Sans Math';
// Fontsource serves Noto Sans Math whole in its "latin" file, and the kit would declare
// that file for the Latin range only. The screen and the PDF take it here with no range,
// so every glyph in it can be used.
const symbolFile = async () =>
  `${await fontsourceAt('noto-sans-math')}files/noto-sans-math-latin-400-normal.woff2`;
const resolve = async (family, ...face) =>
  (family === SYMBOLS ? [{ source: await symbolFile() }] : fontsourceResolver(family, ...face));
const pdfFonts = async (family, ...face) => (family !== SYMBOLS
  ? fontsourceProvider(family, ...face)
  : decompressWoff2(new Uint8Array(await (await fetch(await symbolFile())).arrayBuffer())));

用料

类型
Crimson Pro, Cormorant Garamond, IBM Plex Sans Condensed, Noto Sans Math(SIL OFL 1.1)
素材
无:所有图片都用代码绘制

做法

#1 · 所有字体后面的一种符号字体

这一步的代码就是上面的简短回答。symbolFont: 'Noto Sans Math'(符号字体)把这个字族放到配置里提到的每个字族后面:字体缺的字符改用 Noto Sans Math 画,字号和颜色跟随原字体,这一行其余部分仍用原字体。Fontsource 把完整的 Noto Sans Math 放在 latin 文件里,共 3033 个字符,但工具包只为拉丁范围声明这个文件,浏览器不会向它要 ∀。本配方的 resolve 和 pdfFonts 把同一个文件不带范围地交出去,屏幕上交给画布,打印时交给 renderToPdf。只有缺的字符才换字体:Crimson Pro 有 ¬,所以正文里的否定号仍是 Crimson Pro。

#2 · 先不用它排一遍,看看缺什么

script.js · 第243–250行在完整代码中
// Each paragraph that sets a character its face lacks is a glyphFallbackAt warning with its
// page; with no symbol font it names no family that draws them, and the PDF would print
// empty boxes. The pages shown are the second build's.
const fonts = { ...kitFonts(FONTS), resolve }; // the kit's resolver, with the symbol file
const bare = await buildDocumentWithFonts({ markdown, resources }, { ...config, symbolFont: '' },
  fonts);
console.info((bare.contentWarnings ?? []).filter((w) => w.kind === 'glyphFallbackAt')
  .map(formatWarning).join('\n'));

第一遍排版把 symbolFont 留空,打印出 glyphFallbackAt 警告:每个含有其字体缺字的段落、标题或表格各一条,写明页码和字符。英文版共十八条:十四个 Crimson Pro 段落、三个 Cormorant Garamond 标题,以及表 1.1 中 IBM Plex Sans Condensed 粗体的表头行。没有字族来画,画布会从读者系统里的某种字体借来这些符号,PDF 则每个都印成空框。第二遍用了符号字体,页面上看到的就是它;它的警告写明由 "Noto Sans Math" 来画这些字符。

#3 · 开篇的符号是文字

script.js · 第51–67行在完整代码中
const BAND = 78; // mm from the trim to the foot of the band
const onBand = { color: col('paper'), align: 'left' };
const below = (id, y, width) => ({ anchor: { to: `#${id}`, edge: 'below' }, offset: { y: mm(y) },
  size: { width: mm(width) } });
const opener = { enabled: true, minHeight: mm(BAND - TOP + 2), slot: { elements: [
  { kind: 'box', id: 'band', style: { backgroundColor: col('accent') },
    placement: { anchor: { to: 'bleed', edge: 'top-left' }, size: { height: mm(BAND) } } },
  { kind: 'text', id: 'kicker', content: '{attr.kicker}', ...onBand, fontFamily: LABEL,
    fontWeight: 600, fontSize: pt(8.5), letterSpacing: pt(1.8), textTransform: 'uppercase',
    placement: { anchor: { to: 'container', edge: 'top-left' }, offset: { y: mm(2) } } },
  { kind: 'text', id: 'title', content: '{titleText}', ...onBand, fontFamily: DISPLAY,
    fontWeight: 600, fontSize: pt(38), lineHeight: 1.02, placement: below('kicker', 3, 110) },
  // The signs are text in Cormorant Garamond, which has none of them: Noto Sans Math draws
  // every one, at 30 pt, in the band's white.
  { kind: 'text', id: 'signs', content: '{attr.signs}', ...onBand, fontFamily: DISPLAY,
    fontSize: pt(30), lineHeight: 1, letterSpacing: pt(9), placement: below('title', 7, 114) },
] } };

标题下那行七个符号是一段设计文字,用 30 pt 的 Cormorant Garamond,内容来自标题的 signs 属性。Cormorant Garamond 一个都没有,所以七个都出自符号字体,在色带上以白色印出。9 pt 的字距把它们铺满版心宽度。

#4 · 单元格和书眉用同一种字体

script.js · 第212–230行在完整代码中
const [T, F] = t({ en: ['T', 'F'], es: ['V', 'F'] });
const connectives = [['¬*p*', (p) => !p], ['*p* ∧ *q*', (p, q) => p && q],
  ['*p* ∨ *q*', (p, q) => p || q], ['*p* → *q*', (p, q) => !p || q],
  ['*p* ↔ *q*', (p, q) => p === q]];
const cell = (content, isHeader = false) => ({ content, align: 'center', isHeader });
const truth = [[true, true], [true, false], [false, true], [false, false]].map(([p, q]) =>
  [p, q, ...connectives.map(([, f]) => f(p, q))].map((v) => cell(v ? T : F)));
const table = (id, rows, columnWidths, caption, position) => ({ id, typeId: 'table',
  kind: 'table', caption, createdAt: 0, updatedAt: 0, placement: { position },
  table: { model: { headerRowCount: 1, columnWidths, rows } } });
const resources = [
  table('truth', [['*p*', '*q*', ...connectives.map(([s]) => s)].map((s) => cell(s, true)),
    ...truth],
    [1, 1, 1.3, 1.6, 1.6, 1.6, 1.6], t({ en: 'The five connectives, row by row.',
      es: 'Las cinco conectivas, fila a fila.' }), 'top'), // to the head of a page
  table('signs', parseTSV(signs.trim()).rows.map((row, r) => row.map(({ content }, c) => ({
    content, align: c === 0 ? 'center' : 'left', isHeader: r === 0 }))), [0.8, 2.1, 5.3],
  t({ en: 'Where the signs come from.', es: 'De dónde vienen los signos.' }), 'here'),
];

真值表由联结词本身生成:每列表头是公式,每个单元格是该公式在这一行的结果。表头单元格用 IBM Plex Sans Condensed 粗斜体,表身用 Crimson Pro,符号字体为两者供字。它只有一个正体,为所有字重和倾斜供字,所以粗体表头里的 ∧ 和斜体公式里的 ∈ 是同样的直立符号。奇数页书眉印出当前一节 {firstMark.h2},第 3 页的 SETS: ∈, ∪, ∩ AND ∅ 也从 Noto Sans Math 取符号。

第 3 页:集合公式用 Crimson Pro 斜体,每个符号都来自 Noto Sans Math。

完整食谱

沙盒
// ═══ Postext Cookbook · Nº 185 · Logic signs from a symbol font ═════════════════════
// https://postext.dev/en/cookbook/symbol-font-for-logic
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Crimson Pro, Cormorant Garamond, IBM Plex, Noto Sans Math (OFL) · Needs postext ≥ 1.73.0
// A primer of logical notation set in faces that have no ∀, no ∈, no ℵ and no Greek:
// symbolFont names Noto Sans Math, which draws those characters on the canvas and in the PDF.
import {
  buildDocumentWithFonts, renderPageToCanvas, defaultResourceTypes, parseTSV, formatWarning,
} 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 = 'symbol-font-for-logic';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = {
  ink: '#1f1c22', // text: a cool near-black
  accent: '#7b2a3b', // claret: the opener band, labels, the table heads
  tint: '#f4ece9', // the even rows of the truth table
  rule: '#c3b4b2', // hairlines
  muted: '#6a6064', // running heads, the colophon
  paper: '#ffffff',
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
const TEXT = 'Crimson Pro', DISPLAY = 'Cormorant Garamond', LABEL = 'IBM Plex Sans Condensed';
const TRIM = [155, 235], INNER = 20, OUTER = 21, TOP = 23; // mm: a trade-size primer
const LEAD = 15; // pt: the body leading

// #region answer: one symbol font behind every face, on the canvas and in the PDF
// None of the three faces has ∀, ∈, ℵ or Greek. config.symbolFont (below) lists Noto Sans
// Math after every family the document names: what a face lacks is drawn from it, at the
// face's size and colour, in the canvas, the PDF, the HTML and the EPUB.
const SYMBOLS = 'Noto Sans Math';
// Fontsource serves Noto Sans Math whole in its "latin" file, and the kit would declare
// that file for the Latin range only. The screen and the PDF take it here with no range,
// so every glyph in it can be used.
const symbolFile = async () =>
  `${await fontsourceAt('noto-sans-math')}files/noto-sans-math-latin-400-normal.woff2`;
const resolve = async (family, ...face) =>
  (family === SYMBOLS ? [{ source: await symbolFile() }] : fontsourceResolver(family, ...face));
const pdfFonts = async (family, ...face) => (family !== SYMBOLS
  ? fontsourceProvider(family, ...face)
  : decompressWoff2(new Uint8Array(await (await fetch(await symbolFile())).arrayBuffer())));
// #endregion

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

变化

#去掉第一遍排版

读过警告之后,排一遍就够了。

-const bare = await buildDocumentWithFonts({ markdown, resources }, { ...config, symbolFont: '' },
-  fonts);
-console.info((bare.contentWarnings ?? []).filter((w) => w.kind === 'glyphFallbackAt')
-  .map(formatWarning).join('\n'));

常见问题

版面警告 · glyphFallbackAt

此处字体缺少的字符

原因. 段落含有其正文字体缺字形的字符:数学字母和运算符(∪、ℵ)、拉丁字体中的希腊字母、箭头(glyphFallback 指明字体,此警告指明段落)。supplier 为绘制它们的字体族,通常是 symbolFont;没有时 PDF 将其印成空框。

解决. 指定包含它们的 symbolFont(Noto Sans Math 覆盖大部分数学符号),或选择包含它们的正文字体族。如果字符本身有误(作者想写补集却成了希伯来字母 alef),请改正文本。 文档 →

  • 有些字体的 Fontsource 文件含希腊字母(Source Serif 4、Alegreya),会自己排 φ 和 Γ,正文有希腊字母时工具包会加载那个文件,这时只有符号交给符号字体。Crimson Pro 没有希腊文件,所以它的希腊字母来自 Noto Sans Math。
  • 符号字体只有一个正体常规字重。粗体标题或斜体公式里的符号都用这个字重排,数学书一向就是这样印的。

致谢

文本
  • The primer of logical notation, in English and Spanish · Ignacio Ferro · CC BY 4.0
字体
Crimson Pro (SIL OFL 1.1) · Cormorant Garamond (SIL OFL 1.1) · IBM Plex Sans Condensed (SIL OFL 1.1) · Noto Sans Math (SIL OFL 1.1)
沙盒PDF