简单来说
一本养蜂小手册,每章是一个单独的文件。Postext把它们合成一本书,页码、章号和图号从一个文件接着排到下一个。
成品一览
A Beekeeper’s Year是一本分四章的小手册,每章一个季节。它从Autumn开始,因为养蜂人的一年始于最后一批蜂蜜取下之时。每章是一个单独的Markdown文件,里面不含页码、章号或图号。buildBundle把这些计数从一个文件带到下一个文件,把各章连同放封面和目录的第五个文件排成一本十一页的书。每章都从右页开始,页角有一块蜂巢,里面印着章号。目录页位于与Autumn相对的左页,与章首页左右对称,标题紧贴书脊一侧,并列出每章的页码。一幅用代码画出的育虫巢框在每章出现一次,即图1.1到图4.1。第6页留空,因为Winter只占一页,而Spring必须从右页开始。
这道食谱解答
- 怎样排多章的书,让页码、图号和章号跨章连续?
- 怎样添加自动更新的目录(前导符、页码、作者、篇名行)?
- 怎样强制分页或分栏,并让每章都从右页开始?
- 怎样在章首页和空白页上隐藏书眉,或者把空白左页涂成篇的颜色?
简短回答
// buildBundle lays the documents out in order with one config and carries state from each to
// the next: the pages already set (so parity goes on), the folio, the chapter and figure counts.
const book = () => buildBundle({ chapters, config: config(), resources });
const config = () => ({
headings: { ...display, levels: [
// Every chapter opens on a recto: after a chapter that ends on one, the next document
// starts with a blank verso of its own.
{ level: 1, breakBefore: { enabled: true, parity: 'odd' },
// '{1}' puts the number in the PDF bookmarks ('1 Autumn'); the contents and
// {chapterNumber} count the chapters in order either way.
numberingTemplate: '{1}', advancedDesign: opener,
span: 'page' }, // in the column a design stops at the column's foot: the cover would too
subhead,
] },
// The cover and the contents are headings that take no number, no contents entry and no
// running heads, so Autumn is still chapter 1. Both inherit span 'page', which starts
// each on a page of its own, and parity 'odd', which the contents turn off: it would
// leave page 2 blank (gotcha: style-inherits-break).
headingStyles: [
{ id: 'cover', numbered: false, toc: false, advancedDesign: cover, ...bare },
{ id: 'contents', numbered: false, toc: false, breakBefore: { enabled: false },
advancedDesign: contentsOpener, ...bare },
],
// :::toc in the first document lists the whole book with the folio each chapter lands on:
// buildBundle lays the book out again (three passes at most) until those folios settle.
toc: contents,
// The locale picks the hyphenation patterns and names the figures Figure or Figura. They
// number {h1}.{n}, and the counters carry on from document to document (Winter's is 2.1).
locale: t({ en: 'en-us', es: 'es' }),
colorPalette, page, layout: { layoutType: 'single' }, bodyText, captionStyle, calloutStyles,
header, footer, // the look: above, and in the regions below
});
用料
做法
#1 · 每章一个文件
// Nothing in a chapter says where it lands: buildBundle works that out from the order.
const chapters = [front, autumn, winter, spring, summer].map((markdown) => ({ markdown }));
每个季节都是独立的文档,所以你可以改写一章而不必打开其他章。第一个文档包含前置元数据、封面和目录。它的元数据就是全书的元数据:{title}和{author}在每一章都印出这些内容,PDF也从它读取书名和作者。
#2 · 跨文档接续的规则
这一步的代码见上文的简短回答。buildBundle用同一份共享配置依次排各个文档,并把前面文档的结果作为continuation传给每一个文档:已经排出的物理页数,使奇偶、对称页边距和奇偶页书眉得以接续;下一个页码;以及章和图的计数器。设了parity: 'odd'后,如果前一章结束在右页,下一章会以一个空白左页开始,这个空白页属于下一章自己的文档(前置分页)。封面和目录是设了numbered: false的标题样式,所以Autumn仍是第1章。两者都从章一级继承了span: 'page',不需要:::pagebreak就各占一页。目录样式关闭了继承来的奇偶设置,否则第2页会留空。
#3 · 全书目录
const contents = {
levels: [
{ level: 1, fontFamily: 'Rozha One', fontSize: pt(16), lineHeight: pt(18),
numberFontFamily: 'Figtree', numberFontSize: pt(11), numberFontWeight: 700,
numberColor: col('accent'), numberWidth: mm(7), numberGap: mm(4), marginTop: pt(8) },
// Sections: 9.3 pt in the muted colour, indented 11 mm (number 7 + gap 4) to the titles.
{ level: 2, fontSize: pt(9.3), lineHeight: pt(13.5), indent: mm(11), color: col('muted') },
],
pageNumber: { fontFamily: 'Figtree', fontSize: pt(8.5), fontWeight: 600, width: mm(7) },
leader: { char: '. ', gap: mm(2) },
// A second line under each chapter, from its {months="…"} heading attribute.
subtitle: { enabled: true, attr: 'months', fontFamily: 'Andada Pro', fontSize: pt(9),
color: col('muted') }, // italic by default
};
:::toc放在第一个文档里,但列出的是全书的章和节。buildBundle先排一遍全书,收集每个标题及其得到的页码标签,再用这份大纲重新排版,直到标签不再变动,最多三遍(目录)。每个标题下的月份来自标题属性{months="…"},章首页也会印出它。
#4 · 一种章首页,目录页取其镜像
const corner = (id, edge) => ({ kind: 'image', id, resourceId: id,
placement: { anchor: { to: 'bleed', edge }, size: { width: mm(CORNER.width) } } });
const months = { kind: 'text', id: 'months', content: '{attr.months}', ...label,
color: col('accent'), placement: at('top-left', 0, 14, 'container') };
const title = { kind: 'text', id: 'title', content: '{titleText}', ...display, fontSize: pt(42),
lineHeight: 1.05, align: 'left', overflow: 'wrap', placement: below('months', 1.5, 100) };
const opener = { enabled: true, minHeight: mm(52), slot: { elements: [
corner('cells', 'top-right'),
// The number's box is centred on its cell. Comb and number both hang from the bleed's top
// right, so a bleed (page.cutLines) moves them together.
{ kind: 'text', id: 'number', content: '{chapterNumber}', ...display, fontSize: pt(40),
lineHeight: 1, align: 'center', placement: { size: { width: mm(NUMBER.box) },
...at('top-right', NUMBER_CELL.x + NUMBER.box / 2 - CORNER.width,
NUMBER_CELL.y - NUMBER.rise, 'bleed') } },
months, title,
{ kind: 'text', id: 'lead', content: '{attr.lead}', fontFamily: 'Andada Pro', italic: true,
fontSize: pt(11.5), lineHeight: 1.35, color: col('ink'), align: 'left', overflow: 'wrap',
placement: below('title', 3, 88) },
] } };
// The contents mirror it on the verso: the comb in the outer corner, the book's subtitle and
// the title set flush right against the spine, on the same lines as Autumn's across the spread.
const flushRight = (element, placement) => ({ ...element, align: 'right',
placement: { ...placement, size: { width: 'fill' } } });
const contentsOpener = { ...opener, minHeight: mm(40), slot: { elements: [
corner('comb', 'top-left'),
flushRight({ ...months, content: '{subtitle}' }, months.placement),
flushRight(title, below('months', 1.5)),
] } };
{chapterNumber}接着前面已排文档的计数往下数,所以尽管Spring的文件里没有编号,它的章首页仍印出3。编号的框根据所在蜂巢格的中心计算,编号和蜂巢都挂在出血区域的右上角,所以改变成品尺寸或为印刷加出血时,两者会一起移动。在目录页上,从{subtitle}读取的眉题和标题右对齐、紧贴书脊,蜂巢移到左页的外角。这样目录标题与对页Autumn的标题高度相同。
#5 · 每个文档都有书眉
const head = (id, content, parity, placement, extra = {}) => ({
kind: 'text', id, content, parity, pages: 'body', // never on openers or blank pages
...label, color: col('muted'), placement, ...extra,
});
const folio = { fontSize: pt(8.5), fontWeight: 700, color: col('accent') };
// Only the first document has frontmatter, and its {title} is the book's in every chapter.
const header = { elements: [
head('verso-folio', '{pageNumber}', 'even', at('top-left', MARGIN.outer, HEAD.y), folio),
head('verso-title', '{title}', 'even', at('top-left', MARGIN.outer + HEAD.gap, HEAD.y)),
// {chapterTitle} and {pageNumber} are worked out page by page, in every document.
head('recto-title', '{chapterTitle}', 'odd',
at('top-right', -(MARGIN.outer + HEAD.gap), HEAD.y)),
head('recto-folio', '{pageNumber}', 'odd', at('top-right', -MARGIN.outer, HEAD.y), folio),
] };
// Openers carry a drop folio instead, 8 mm under the text block.
const footer = { elements: [head('drop-folio', '{pageNumber}', 'all',
at('top', 0, 8, 'container'), { pages: 'opener', fontWeight: 700 })] };
只有第一个文档有前置元数据,而buildBundle把它交给每一章,所以左页书眉在五个文档里都印出全书的{title}。{chapterTitle}和{pageNumber}逐页解析,在每个文档里都能印出;第11页是唯一的正文右页,在页码旁印着SUMMER。pages: 'body'让章首页和空白页都不印书眉。
#6 · 屏幕上看跨页,整本书输出一个PDF
const text = chapters.map((chapter) => chapter.markdown).join('\n');
await prepareFonts(text, config(), kitFonts(FONTS));
const art = { cover: coverArt(), cells: cornerArt(true), comb: cornerArt(false) };
for (const [season, plan] of Object.entries(SEASONS)) art[`${season}-frame`] = frameArt(plan);
for (const [id, markup] of Object.entries(art)) await loadSvg(`${id}.svg`, markup);
// One VDTDocument per Markdown document.
const docs = await withLoadedFonts(book, { ...kitFonts(FONTS), text });
showPages(docs, { title: t({ en: 'A Beekeeper’s Year', es: 'Un año de colmenar' }) });
// renderToPdf takes the array: one file for the book, with a bookmark per chapter.
offerPdf(() => renderToPdf(docs, { fontProvider: fontsourceProvider, resourceBytes: imageBytes }),
`${RECIPE}.pdf`);
buildBundle返回一个文档数组,每个Markdown文件对应一个。showPages按pageIndexOffset + page.index给页面配对,所以第1页作为右页单独出现,第2和第3页、第4和第5页依次左右相对。renderToPdf接受同一个数组,写出一个文件,带有全书的页码标签,每个章节都有书签。
完整食谱
// ═══ Postext Cookbook · Nº 007 · One book from separate chapters ══════════════════════════
// https://postext.dev/en/cookbook/book-from-chapters
// Code: MIT · Text: original (CC BY 4.0) · Drawings: generated in code (CC BY 4.0)
// Fonts: Andada Pro, Rozha One, Figtree (SIL OFL 1.1) · Needs postext ≥ 1.25.0
// A handbook in four seasons written as five Markdown documents, laid out by buildBundle as
// one book: parity, folios, chapter and figure numbers and the contents run straight through.
import {
buildBundle, prepareFonts, withLoadedFonts, 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 = 'book-from-chapters';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { // every colour in the config links to one of these, so the book can be retinted
ink: '#2a2218', // text and display type
honey: '#d99a1e', // the drawings only: the cover and the comb cells
accent: '#7a4e12', // the text accent (7:1 on paper): numbers, labels, subheads; main-color too
pollen: '#c4692b', comb: '#f7e7c4', rule: '#d8c8a8', // figures: pollen, wax, wood and walls
muted: '#6e634f', paper: '#fffdf7', // running heads, colophon, contents sections; the page
};
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, so nothing prints blue.
{ id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// The geometry, in mm. The drawings, the opener and the running heads are derived from it.
const TRIM = { width: 150, height: 200 }; // a small handbook
const MARGIN = { top: 22, bottom: 22, inner: 19, outer: 15 }; // mirrored
const MEASURE = TRIM.width - MARGIN.inner - MARGIN.outer; // the text width: 116 mm
const SQRT3 = Math.sqrt(3); // comb cells of radius r sit √3·r apart, their rows 1.5·r apart
const CORNER = { width: 84, height: 70, r: 9.5 }; // the openers' comb, and its cell radius
const NUMBER_CELL = { x: 4 * SQRT3 * CORNER.r, y: 2 * 1.5 * CORNER.r }; // row 2, cell 4
// The chapter number's box: 20 mm wide, its top 8 mm above the cell's centre, which is where
// a 40 pt Rozha One figure sits optically centred in the cell.
const NUMBER = { box: 20, rise: 8 };
const FRAME = { width: MEASURE, height: 50 }; // the brood frame figures, at the text width
const HEAD = { y: 12, gap: 8 }; // running heads 12 mm from the top edge, 8 mm folio to text
const LEAD = 14.2; // body leading in pt: the baseline grid
// The look: a small handbook, mirrored, justified Andada Pro on the grid; Rozha One titles.
const page = { // mirror: left is the inner margin, right the outer
sizePreset: 'custom', width: mm(TRIM.width), height: mm(TRIM.height), dpi: 150,
backgroundColor: col('paper'), margins: { top: mm(MARGIN.top), bottom: mm(MARGIN.bottom),
left: mm(MARGIN.inner), right: mm(MARGIN.outer), mirror: true },
};
const bodyText = { // justified, hyphenated, optimal line breaks and widow control: by default
组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)
变化
#单独打印一章,保留全书页码
只把一个文档传给renderToPdf,就能单独校对Spring,页码仍和书中一样是6到8。空白的第6页也一起输出,因为章首页前的空白左页属于其后开始的那一章。
-offerPdf(() => renderToPdf(docs, { fontProvider: fontsourceProvider, resourceBytes: imageBytes }),
+offerPdf(() => renderToPdf(docs[3], { fontProvider: fontsourceProvider, resourceBytes: imageBytes }),#图号全书连续编排
一个从不重置的图计数器会把四幅巢框跨文档编为1到4,而不是1.1到4.1。
buildBundle, prepareFonts, withLoadedFonts, renderPageToCanvas, registerResourceImage,
+ defaultResourceTypes,
@@
locale: t({ en: 'en-us', es: 'es' }),
+ resourceTypes: defaultResourceTypes(LANG)
+ .map((type) => ({ ...type, numberingTemplate: '{n}', resetOn: 'never' })),常见问题
易错点
标题样式会继承其级别的分页设置
headingStyles中的条目没有写出的字段都取自它所属的标题级别,breakBefore也不例外。在:::pagebreak之后以H1设置样式的目录页或版权页会继承parity 'odd',结果落在一张空白页之后。给这类样式设置breakBefore: { enabled: false }。 标题样式 →
沙盒检查 · chapterFrontmatterIgnored
章的前置元数据被忽略
原因. 只有第一章的前置元数据有效;后面某一章以前置元数据块开头,这个块被丢弃。
解决. 把书的元数据放在第一章,每章各自的值用标题属性来设。 文档 →
- 在页首,以及在位于页首的图下方,小标题会失去
marginTop。靠外边距取得上方空间的小标题,在这两种位置离正文一行,在其他地方离正文一行半。这里的空间放在小标题自己的行里:lineHeight是一行半,外边距是一行,所以书中每个小标题与正文的距离都相同。 - 默认情况下,两端对齐的行可以把词间距拉伸到正常宽度的两倍,断行器宁可这样也不断词。在这个默认值下,英文版一个断词都没有,词间距接近两倍的行和压缩到0.7的行挨在一起。
maxWordSpacing: 1.7让断行器改为断词。改动之后要检查每段的最后一行:更紧的限度可能让那里只剩一个词,改写该段的几个词就能解决。
致谢
- 文本
- 原创文字, CC BY 4.0
- 字体
- Andada Pro (SIL OFL 1.1) · Rozha One (SIL OFL 1.1) · Figtree (SIL OFL 1.1)


