In short
A short beekeeping handbook written as separate files, one per chapter. Postext joins them into one book, and the page, chapter and picture numbers carry on from file to file.
What you'll build
A Beekeeper’s Year is a small handbook in four chapters, one per season. It opens with Autumn, since the beekeeper’s year begins when the last honey comes off. Each chapter is a separate Markdown file with no page, chapter or figure number in it. buildBundle carries those counts from each file to the next and sets the chapters, with a fifth file for the cover and contents, as one book of eleven pages. Every chapter opens on a right-hand page under a corner of honeycomb that holds its number. The contents page, on the verso facing Autumn, mirrors that opener with its title flush against the spine, and lists each chapter’s folio. One brood frame, drawn in code, appears once in each chapter as Figures 1.1 to 4.1. Page 6 stays blank because Winter fills a single page and Spring has to open on a recto.
This recipe answers
- How do I lay out a multi-chapter book so page, figure and chapter numbers continue across chapters?
- How do I add a table of contents that updates itself (leaders, page numbers, authors, part rows)?
- How do I force a page or column break, and start every chapter on a right-hand page?
- How do I hide running heads on openers and blank pages, or paint a blank verso in the part colour?
The short answer
// 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
});
Five Markdown documents, one book: buildBundle and the rules they share
Ingredients
- Features
- Books built chapter by chapterTable of contentsChapters that open on a rectoNumbered captionsCitations that place figuresNumbered headingsHeading stylesUnnumbered chaptersRunning heads per sectionRunning heads and foliosHeads by page roleDesigned openersHeading attributesPictures in page designsMirrored marginsFloated boxesPDF exportPDF bookmarksFigure and Table in your languageCovers, title pages and colophons
- Also uses
- Callout boxesFull-width chapter bandPaper colourFonts embedded in the PDFFigures and tables as resourcesLine breaks in titles
- Type
- Andada Pro, Rozha One, Figtree (SIL OFL 1.1)
- Assets
- None: every picture is drawn in code
Method
#1 · One file per chapter
// 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 }));
Each season is its own document, so you can rewrite one chapter without opening the others. The first document holds the frontmatter, the cover and the contents. Its metadata is the book’s: {title} and {author} print it in every chapter, and the PDF takes its title and author from it.
#2 · Rules that carry across documents
This step’s code is the short answer above. buildBundle lays the documents out in order with one shared config and passes each one a continuation from those before it: the number of physical pages already set, so parity, mirrored margins and odd and even running heads carry on; the next folio; and the chapter and figure counters. With parity: 'odd', a chapter that follows one ending on a recto starts with a blank verso, and that blank belongs to its own document (break before). The cover and the contents are heading styles with numbered: false, so Autumn is still chapter 1. Both inherit span: 'page' from the chapter level, which puts each on a page of its own without a :::pagebreak. The contents style turns off the inherited parity, which would otherwise leave page 2 blank.
#3 · Contents for the whole book
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 sits in the first document but lists the chapters and sections of the whole book. buildBundle lays the book out, collects every heading with the page label it got, and lays the book out again with that outline until the labels stop moving, three passes at most (table of contents). The months under each title come from a heading attribute, {months="…"}, which the opener prints too.
#4 · One opener, mirrored for the contents
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} counts on from the documents laid out before, so Spring’s opener prints 3 although its file holds no number. The number’s box is computed from the centre of its comb cell, and number and comb both hang from the top right corner of the bleed, so changing the trim or adding a bleed for print moves them together. On the contents page the kicker, read from {subtitle}, and the title are set flush right against the spine, and the comb moves to the verso’s outer corner. Its title then sits at the same height as Autumn’s on the facing page.
#5 · Running heads in every document
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 })] };
Only the first document has frontmatter, and buildBundle hands it to every chapter, so the verso head prints the book’s {title} in all five documents. {chapterTitle} and {pageNumber} are resolved page by page and print in every document; page 11, the one right-hand body page, carries SUMMER beside its folio. pages: 'body' keeps every head off the openers and the blank page.
#6 · Spreads on screen, one PDF for the book
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 returns an array of documents, one per Markdown file. showPages pairs the pages by pageIndexOffset + page.index, so page 1 stands alone as a recto and pages 2 and 3, 4 and 5 and so on face each other. renderToPdf takes the same array and writes one file with the book’s page labels and a bookmark for every chapter and section.
The whole recipe
// ═══ 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
The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)
Variations
#Print one chapter with its book folios
Pass a single document to renderToPdf to proof Spring on its own, still numbered 6 to 8 as in the book. The blank page 6 comes with it, because a blank verso in front of an opener belongs to the chapter that opens after it.
-offerPdf(() => renderToPdf(docs, { fontProvider: fontsourceProvider, resourceBytes: imageBytes }),
+offerPdf(() => renderToPdf(docs[3], { fontProvider: fontsourceProvider, resourceBytes: imageBytes }),#Number the figures straight through the book
A figure counter that never resets numbers the four frames 1 to 4 across the documents instead of 1.1 to 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' })),Pitfalls
Pitfall
A heading style inherits its level's page break
A headingStyles entry takes every field it leaves out from its heading level, breakBefore included. A contents page or a colophon styled on an H1 after a :::pagebreak inherits parity 'odd' and lands behind a blank page. Give such a style breakBefore: { enabled: false }. Heading styles →
Pitfall
Page 1 is a recto: plan pages with physical numbers
Page 1 is a right-hand page and page 2 the first verso, so plan spreads with physical page numbers: an opener on an even page faces the odd page after it. Page and column breaks →
Sandbox check · chapterFrontmatterIgnored
Chapter frontmatter ignored
Why. Only the first chapter's frontmatter counts; a later chapter starts with a frontmatter block that is dropped.
Fix. Keep the book's metadata in chapter one, and use heading attributes for per-chapter values. Docs →
- At the head of a page, and under a figure that heads one, a subhead loses its
marginTop. A subhead that takes its space from the margin stands one line above its text in those two places and a line and a half above it everywhere else. Here the space is in the subhead's own line:lineHeightis a line and a half and the margin one line, so every subhead in the book stands the same distance above its text. - By default a justified line may stretch its spaces to twice their width, and the line breaker prefers that to a hyphen. At that default the English edition had no hyphens at all, and lines whose spaces were nearly twice the normal width sat next to lines squeezed to 0.7.
maxWordSpacing: 1.7makes the breaker hyphenate instead. After changing it, check the last line of every paragraph: a tighter limit can leave a single word there, and rewording a few words of the paragraph fixes it.
Credits
- Recipe
- Ignacio Ferro
- Text
- Original prose, CC BY 4.0
- Fonts
- Andada Pro (SIL OFL 1.1) · Rozha One (SIL OFL 1.1) · Figtree (SIL OFL 1.1)
Edit this write-up ↗ (opens in a new tab)Recipe folder on GitHub ↗ (opens in a new tab)


