简单来说
一本《红楼梦》选读本,书末附人名索引。同一套标记排出两个版本:简体版按拼音排序,繁体版按笔画排序。
成品一览
一本薄薄的《紅樓夢》读本,从第一回到第三回中选印了人物初次登场的段落,书末附一份人名索引,收47个人名,另有四条从别名指过来的参见。同一套标记生成两个版本。大陆版用简体字,按拼音首字母F、H、J……归组;台湾版用繁体字,按首字的笔画数三畫、四畫……归组。两版都是大32开平装,140 × 203 mm,每行26字,正文用Noto Serif,回目用楷体,眉题、页码和索引分组标题用Noto Sans。卡片上放大的是简体版索引的前几组,F到L。人名索引与主题索引为一本英文专著做了同类的索引。
这道食谱解答
- 怎样把中文人名索引按拼音或笔画数分组?
- 怎样让汉字在PDF里不显示成空框?
简短回答
// Marks in the Markdown, one per passage; main is the page where the character enters:
// 字:index[士隐]{term="甄士隐" main} :index{term="贾化" see="贾雨村"}
// Printed at the end of each edition: # 人名索引 {style="index"}, then :::index
const index = (e) => ({
// 'auto' reads the same from the locale: pinyin for zh-Hans, strokes for zh-Hant.
groupBy: e.locale === 'zh-Hans' ? 'pinyin' : 'stroke', // A B C… or 三畫 四畫…
fontFamily: e.serif, fontSize: pt(9), lineHeight: pt(14),
separator: '\u3000', locatorSeparator: ',', // 贾宝玉 4,6: an ideographic space, then ,
see: { italic: false }, // 见 / 見 upright: Chinese has no italic (gotcha: cjk-no-italic)
groups: { fontFamily: e.sans, fontSize: pt(9.5), fontWeight: 700, color: col('cinnabar'),
marginTop: pt(6.25) }, // the three names of 九畫 stay whole at the foot of their column
});
const indexHeading = { id: 'index', numbered: false, breakBefore: { enabled: true, parity: 'any' },
layout: { layoutType: 'double', gutterWidth: pt(21) } }; // two columns, 2 characters apart
用料
- 类型
- Noto Serif SC, Noto Sans SC, Ma Shan Zheng, Noto Serif TC, Noto Sans TC, LXGW WenKai TC(SIL OFL 1.1)
- 素材
- 无:所有图片都用代码绘制
做法
#1 · 在读者遇到人名的地方加标记
代码见上文的简短回答,其余都在Markdown里。无论正文印的是什么,标记都以全名归档:字:index[士隐]{term="甄士隐" main}印出士隐,在甄士隐名下记一个页码。main让这个页码排成粗体,索引标题下的说明交代了粗体在这里的含义:人物亲自登场的那一页。贾宝玉在第二回出生时没有提名字(又生了一位公子),所以这里的标记不印任何文字,写作:index{term="贾宝玉"},他的条目读作4, 6。别名和绰号有自己的参见条目,:index[凤辣子]{term="凤辣子" see="王熙凤"},Postext按中文习惯印出,前面是句号,不留空格:凤辣子。见王熙凤(索引标记)。
#2 · 让语言区域决定排序
// The mainland edition in Simplified characters and the Taiwan edition in Traditional ones.
// Each takes the Song (serif), Hei (sans) and Kai faces cut for its script. Fontsource has no
// Kai text face with mainland forms: LXGW WenKai TC draws 冷 the Taiwan way, so the mainland
// titles take Ma Shan Zheng, a brush Kai.
const EDITIONS = {
hans: { locale: 'zh-Hans', serif: 'Noto Serif SC', sans: 'Noto Sans SC', kai: 'Ma Shan Zheng' },
hant: { locale: 'zh-Hant', serif: 'Noto Serif TC', sans: 'Noto Sans TC', kai: 'LXGW WenKai TC' },
};
两个版本共用同一份配置,索引只需要locale这一个开关:groupBy: 'auto'让zh-Hans索引按拼音分组,让zh-Hant索引按笔画分组;简短回答把这两个值明确写了出来,方便你看清。条目按分组标题所依据的顺序排列,所以同样的人名会换位置:在Z组下,甄费排在甄士隐之前(fèi在shì之前),在十四畫下则排在其后(士三画,費十二画);宁国公和荣国公分入N和R两组,而寧國公和榮國公在十四画的人名中仍然挨在一起(索引)。读音和笔画数来自浏览器的中文排序规则;遇到读错的姓(曾、单、解),就用读音正确的汉字给它一个sort键。
#3 · 每种字体只加载它要排的字符
const DIGITS = '0123456789';
const HEADS = '第回一二三四五六七八九十画畫ABCDEFGHIJKLMNOPQRSTUVWXYZ'; // 第一回, the index heads
const all = (md, re) => [...md.matchAll(re)].map((m) => m[1]).join('\n');
for (const [key, md] of [['hans', markdown], ['hant', traditional]]) {
e = EDITIONS[key];
await loadCjkFonts({ [e.serif]: ['400'] }, md); // the text, the index, the running heads
await loadCjkFonts({ [e.serif]: ['700'] }, DIGITS); // the bold page numbers
await loadCjkFonts({ [e.sans]: ['700'] }, all(md, /kicker="([^"]*)"/g) + HEADS + DIGITS);
await loadCjkFonts({ [e.kai]: ['400'] }, all(md, /^# ([^{\n]*)/gm)); // the titles alone
}
Fontsource把每个中文字重拆成约一百个文件,loadCjkFonts只取文本用到的那些。宋体拿到整本书,所以书眉不额外占用它的文件;宋体粗体拿到主要页码的数字;黑体拿到kicker属性的文字、索引分组标题和页码的数字;楷体拿到三副对联和人名索引。PDF走同样的路线:cjkPdfProvider嵌入这些文件,每个文件都裁剪到页面上实际用到的字符,没有哪个字会变成空框。楷体随版本而变。LXGW WenKai TC是Fontsource上唯一的楷体正文字体,它用传承字形,比如冷字里令的下部写成旧式的卩,逗号和句号也居中,所以简体版的标题改用Ma Shan Zheng,一种采用大陆字形的毛笔楷体(中日韩字体)。
#4 · 把说明放进索引首页
const opener = (e, sink, kicker, note = []) => ({
enabled: true,
minHeight: pt(LEAD * sink), // the text starts on the same line after every opener
slot: { elements: [
{ kind: 'text', id: 'kicker', content: kicker, fontFamily: e.sans, fontSize: pt(9),
fontWeight: 700, letterSpacing: pt(2.7), color: col('cinnabar'), align: 'center',
placement: { ...at('container', 'top', 0, 8), size: { width: 'fill', height: 'auto' } } },
{ kind: 'text', id: 'title', content: '{titleText}', fontFamily: e.kai, fontSize: pt(16),
lineHeight: 1.45, color: col('ink'), align: 'center',
overflow: 'wrap', // design text ends in an ellipsis by default
placement: { ...at('#kicker', 'below', 0, 3), size: { width: 'fill', height: 'auto' } } },
{ kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(0.5), color: col('rule'),
placement: { ...at('#title', 'below', (MEASURE - 12) / 2, 4), size: { width: mm(12) } } },
...note,
] },
});
// The note (note="…" on the heading) sits above the columns: no paragraph for balancing to loosen.
const indexNote = (e) => [{ kind: 'text', id: 'note', content: '{attr.note}',
fontFamily: e.serif, fontSize: pt(9), lineHeight: 1.6, color: col('muted'), align: 'center',
overflow: 'wrap', placement: { ...at('#rule', 'below', -(MEASURE - 12) / 2, 4),
size: { width: 'fill', height: 'auto' } } }];
说明是标题的一个属性,# 人名索引 {style="index" kicker="按汉语拼音排列" note="…"},排在两栏上方,占满整个行长。如果把它作为栏内的段落,它就会成为各栏齐底的调节手段:为了让繁体版最后一页齐底,排版把它放松到每行十二字,而栏宽是十四字。说明是一整句话,本索引收录前三回选文中的人物,粗体页码为人物出场之页;别名与原名另立参见条目。,由设计自动折行:中文书的设计文本遵循正文的避头尾规则和标点宽度,所以,;在简体版中排半角,在繁体版中排全角,与正文一致,说明的各行也不会以标点开头。章首页也用这个设计,眉题是第{numberHan}回,按文档的字形印出第一回。
#5 · 把两个索引页并排展示
const indexPage = (doc) => doc.pages[doc.blocks.find((b) => b.headingStyleId === 'index')
?.pageIndex ?? doc.pages.length - 1];
const labels = { hans: t({ en: 'Simplified · by pinyin', es: 'Simplificado · por pinyin' }),
hant: t({ en: 'Traditional · by strokes', es: 'Tradicional · por trazos' }) };
document.getElementById('pages').insertAdjacentHTML('beforebegin', `<section id="indexes" style="
display:flex;flex-wrap:wrap;justify-content:center;gap:24px;padding:28px 16px;background:#e9e4da">
${Object.keys(docs).map((key) => `<figure style="margin:0;width:min(340px,44vw)">
<canvas id="index-${key}" role="img" style="display:block;width:100%;background:#fff;
box-shadow:0 18px 36px -18px rgb(0 0 0 / .45)"></canvas><figcaption style="margin-top:10px;
font:600 11px/1 system-ui,sans-serif;letter-spacing:.14em;text-transform:uppercase;color:#5b534a">
${labels[key]}</figcaption></figure>`).join('')}</section>`);
for (const [key, doc] of Object.entries(docs)) {
const canvas = document.getElementById(`index-${key}`);
const page = indexPage(doc);
canvas.setAttribute('aria-label', `${labels[key]}, ${page.pageLabel}`);
renderPageToCanvas(page, doc, canvas, { scale: (2 * canvas.clientWidth) / page.width });
}
这个pen构建两个版本,桌面上显示简体版。简体版和繁體版两个按钮切换桌面,每次切换都提供当前版本的PDF,即chinese-name-index-hans.pdf或chinese-name-index-hant.pdf。截图记录两次构建(capture.doc: ['first', 'last']):上面前八页是简体版,其后四页来自繁体版,即它的第一页和笔画索引。桌面上方的条带放着两个版本各自的索引首页。随食谱提供的PDF是简体版的。
完整食谱
// ═══ Postext Cookbook · Nº 079 · An index of Chinese names, by pinyin and by strokes ═══
// https://postext.dev/en/cookbook/chinese-name-index
// Code: MIT · Text: 紅樓夢 (1792), zh.wikisource revision 9685985 (CC BY-SA 4.0) · Pictures: none
// Fonts: Noto Serif/Sans SC/TC, Ma Shan Zheng, LXGW WenKai TC (OFL 1.1) · Needs postext ≥ 1.28.0
import { buildDocument, withLoadedFonts, renderPageToCanvas } 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 = 'chinese-name-index';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: ink on a warm paper, one cinnabar for the heads and the index letters
const palette = {
ink: '#1f1b18', // text
cinnabar: '#a3301f', // the one accent: 回 numbers, index heads
muted: '#6b635a', // running heads, folios, colophon
rule: '#d6cdbf', // the short rule under each title
paper: '#fbf8f1',
};
// Each colour carries its hex and the palette entry it follows.
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' } })),
// The engine's defaults link to main-color: point it at the accent, never the default blue.
{ id: 'main-color', name: 'accent (defaults)', value: { hex: palette.cinnabar, model: 'hex' } },
];
// #endregion
// #region editions: one book, two scripts; the locale decides the index order
// The mainland edition in Simplified characters and the Taiwan edition in Traditional ones.
// Each takes the Song (serif), Hei (sans) and Kai faces cut for its script. Fontsource has no
// Kai text face with mainland forms: LXGW WenKai TC draws 冷 the Taiwan way, so the mainland
// titles take Ma Shan Zheng, a brush Kai.
const EDITIONS = {
hans: { locale: 'zh-Hans', serif: 'Noto Serif SC', sans: 'Noto Sans SC', kai: 'Ma Shan Zheng' },
hant: { locale: 'zh-Hant', serif: 'Noto Serif TC', sans: 'Noto Sans TC', kai: 'LXGW WenKai TC' },
};
// #endregion
const LEAD = 18; // body leading in pt: 1.7 × the 10.5 pt text (五号)
const MEASURE = (26 * 10.5 * 25.4) / 72; // the grid's 26 characters of 10.5 pt, in mm
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
// #region answer: the same marks, grouped by pinyin in zh-Hans and by strokes in zh-Hant
// Marks in the Markdown, one per passage; main is the page where the character enters:
// 字:index[士隐]{term="甄士隐" main} :index{term="贾化" see="贾雨村"}
// Printed at the end of each edition: # 人名索引 {style="index"}, then :::index
const index = (e) => ({
// 'auto' reads the same from the locale: pinyin for zh-Hans, strokes for zh-Hant.
组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)
变化
#繁体索引按拼音分组
面向按读音查名字的读者,繁体版也可以按拼音归档。在两个版本中都设groupBy: 'pinyin':分组标题为A–Z,条目保留繁体字形。眉题说明了索引的排列方式,所以繁体版的Markdown里也要把它改成kicker="依漢語拼音排列"。
- groupBy: e.locale === 'zh-Hans' ? 'pinyin' : 'stroke', // A B C… or 三畫 四畫…
+ groupBy: 'pinyin', // A B C… in both scripts#不带分组标题的人名表
简短的人名表可以不加分组标题,只在各组之间空一行。保留分组,关掉标题即可。groupBy: 'none'做不到这一点:它只把符号、数字和词语分开,而这里每个人名都以汉字开头,47个人名会连成一整块。
- groups: { fontFamily: e.sans, fontSize: pt(9.5), fontWeight: 700, color: col('cinnabar'),
- marginTop: pt(6.25) }, // the three names of 九畫 stay whole at the foot of their column
+ groups: { enabled: false, marginTop: pt(14) }, // no heads; a blank line between groups常见问题
易错点
中文字体通过cjk块分片加载
Fontsource把一个中文、日文或韩文字体家族按每个字重约一百个文件提供,每个文件覆盖一段字符范围。loadFonts只获取latin文件,所以屏幕上的汉字来自系统字体,测量不准;fontsourceProvider交给PDF的也是这个latin文件,汉字印出来是空框。列出kit中的cjk块,在loadFonts之后调用loadCjkFonts(FONTS, markdown)(书中用到几种CJK字体时,每种字体调用一次,并传入它所排的文字),并给renderToPdf传fontProvider: cjkPdfProvider:两者都会取用包含文中字符的那些文件。 中日韩字体 →
易错点
中文没有斜体
CJK字体家族不带斜体,中文排版用字旁的着重号标示强调,而不是倾斜。在标记为中文的文档中,*…*给其中的汉字加着重号,拉丁文词仍用斜体(cjk.emphasis: 'dots',中文的默认值);:dots[…]可以在任何地方加着重号。设置cjk.emphasis: 'italic'时,或在标记为en或es的文档中,*…*会让Canvas把正体字形倾斜,这种合成的伪斜体是中文排版从来不用的(PDF会退回正体字型):保留中文标记,或者通过段落样式或标签样式,用粗体或楷体(LXGW WenKai)表示强调。 中日韩字体 →
易错点
用zh-Hans或zh-Hant标记文档,不要用LANG
食谱的版本是en和es,但中文示例在两个版本里都是中文:`locale: LANG`会把它标记为英文或西班牙文,给其中的拉丁文词断词,把图标注为Figure或Figura,并给PDF标上错误的语言。postext 1.30起,这个标记也是文字成形所用的语言(测量、绘制和嵌入都按它进行),所以标记成英文或西班牙文时,中文字体的数字和与拉丁文共用的标点会换成另一套字形,断行的位置也随之改变。自己写出标记:'zh-Hans'(大陆规范:GB断行规则、开明式标点)或'zh-Hant'(台湾:全角居中标点);香港用'zh-HK'。单写'zh'按简体、大陆规范处理。日文示例写'ja'(见gotcha ja-locale-tag)。 中文断行 →
易错点
各地区的标点要用该地区的字体排
标点宽度调整会把每个标点旁的空白移到文档所属地区规定的一侧,而不是字体绘制时的那一侧:在zh-Hans下,开明式的逗号保留字框的左半部分(简体字体把字形画在这里),让出右半部分。繁体字体把,。画在字框中央,所以让出的那一半含有部分字形,逗号就挤到了下一个字上。LXGW WenKai TC是Fontsource上唯一的楷体正文字体,在简体文字中就会这样。大陆的正文、注释和引文用Noto Serif SC或Noto Sans SC排,TC字体留给zh-Hant,简体毛笔字体(Ma Shan Zheng)只用于展示行,因为设计文本不做标点宽度调整。LXGW WenKai TC还会画出大陆和台湾标准都不采用的传承字形:為用爲的爫头,令(在冷、領中)用卩底。要检查页面上用它排的字。 中文标点宽度 →
index配置属于文档,所以一个文档只能印出一种排序。一本书如果既要拼音索引又要笔画检字表,就要构建两次,就像这个pen一样。- 在字格上,各栏齐底默认关闭,每部索引的最后一页会把第一栏排到底:简体版的版权说明会从Z组下面排起,到第二栏顶端才排完。设
headings.balancing: { enabled: true }后,这一页的第一栏提前截断,人名接排到第二栏,版权说明整段排在人名之后(各栏齐底)。截断处总在条目之间,而且不会让一组里的某个人名单独留在栏底或栏首(index.groups.splitMinEntries,默认为2),所以两栏只有在长度凑得上时才齐底。这里每段版权说明都加了一句交代索引排序的话,两个末页的两栏相差不到三分之一行。
致谢
- 文本
- Dream of the Red Chamber (紅樓夢), chapters 1–3, passages where the characters first appear, in the Cheng–Gao edition of 1792 (程乙本); Wikisource transcription, revision 9685985. The Traditional edition reads the source's 原系 as 原係; both set its -- as ——; the Simplified edition converted with OpenCC · Cao Xueqin, Cheng Weiyuan and Gao E; transcription by Wikisource editors · CC BY-SA 4.0
- 字体
- Noto Serif SC (SIL OFL 1.1) · Noto Sans SC (SIL OFL 1.1) · Ma Shan Zheng (SIL OFL 1.1) · Noto Serif TC (SIL OFL 1.1) · Noto Sans TC (SIL OFL 1.1) · LXGW WenKai TC (SIL OFL 1.1)


