かんたんな説明
章ごとに別ファイルで書いた小さな養蜂の手引き書です。Postextがそれらを1冊にまとめ、ページ、章、図の番号はファイルをまたいで続きます。
できあがり
『A Beekeeper’s Year』は、季節ごとに1章、全4章の小さな手引き書です。養蜂家の1年は最後の蜜を採り終えたときに始まるので、本は秋の章から始まります。各章は別々のMarkdownファイルで、ページ番号も章番号も図番号も書かれていません。buildBundleがそれらの数をファイルから次のファイルへ引き継ぎ、表紙と目次を収めた5つ目のファイルとあわせて、11ページの1冊の本に組みます。どの章も右ページから始まり、章番号を収めたハニカムが隅に置かれます。秋の章と向かい合う偶数ページの目次は、その章扉を左右反転させた形で、表題をのど側にそろえ、各章のノンブルを並べます。コードで描いた巣枠の図が各章に1点ずつ、図1.1から図4.1として入ります。冬の章が1ページで終わり、春の章を奇数ページから始める必要があるため、6ページは白ページになります。
このレシピが答える質問
- 複数の章からなる本で、ページ番号・図番号・章番号を章をまたいで続けるには?
- 自動で更新される目次(リーダー、ノンブル、著者名、部の行)を追加するには?
- 改ページや改段を強制し、すべての章を右ページから始めるには?
- 章扉や白ページで柱を隠したり、空白の偶数ページを部の色で塗ったりするには?
手短な答え
// 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
});
材料
- 機能
- 章ごとに組む本目次奇数ページから始まる章番号付きキャプション図を配置する参照番号付き見出し見出しスタイル番号のない章節ごとの柱柱とノンブルページの役割ごとの柱デザインした章扉見出しの属性ページデザインの画像見開きの余白フロートする囲みPDFの書き出しPDFのしおり「図」と「表」を文書の言語で表紙、扉、奥付
- 種類
- Andada Pro, Rozha One, Figtree (SIL OFL 1.1)
- 素材
- なし:画像はすべてコードで描画
作り方
#1 · 1章に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 }));
季節ごとに独立した文書なので、ほかの章を開かずに1章だけを書き直せます。最初の文書にはフロントマター、表紙、目次が入ります。そのメタデータが本全体のメタデータになります。{title}と{author}はどの章でもそれを印字し、PDFも表題と著者をそこから取ります。
#2 · 文書をまたいで続く規則
この手順のコードは上の手短な答えにあります。buildBundleは共通の設定ひとつで文書を順に組み、各文書にそれまでの文書から求めたcontinuationを渡します。中身は、すでに組んだ物理ページの数(これで奇偶、左右対称の余白、奇数・偶数ページの柱が続きます)、次のノンブル、章と図のカウンターです。parity: 'odd'を指定すると、奇数ページで終わった章のあとの章は白の偶数ページから始まり、その白ページはあとの章の文書に属します(前で改ページ)。表紙と目次はnumbered: falseの見出しスタイルなので、秋の章は第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は本を組み、各見出しとそれに付いたページラベルを集め、その目次の骨組みを使って、ラベルが動かなくなるまで本を組み直します。最大で3回です(目次)。各章題の下の月は見出しの属性{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}は先に組んだ文書から数を引き継ぐので、春の章扉にはファイルに番号がなくても3と印字されます。番号のボックスはハニカムのセルの中心から計算し、番号とハニカムはどちらも塗り足しの右上の角に固定します。仕上がりサイズを変えても、印刷用に塗り足しを付けても、両者はいっしょに動きます。目次のページでは、{subtitle}から取るキッカー(表題の上の小さな見出し)と表題をのど側に右そろえし、ハニカムは偶数ページの小口側の隅に移します。こうすると目次の表題は、向かいのページの秋の章題と同じ高さに並びます。
#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がそれをすべての章に渡すので、偶数ページの柱は5つの文書のどれでも本の{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ファイル1つにつき1つ、文書の配列を返します。showPagesはpageIndexOffset + page.indexでページを組み合わせるので、1ページは単独の奇数ページとして立ち、2と3、4と5……が見開きで向かい合います。renderToPdfは同じ配列を受け取り、本のページラベルと各章・各節のしおりを付けた1つのファイルを書き出します。
レシピの全体
// ═══ 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上のレシピのフォルダー ↗ (新しいタブで開きます)
アレンジ
#1章だけを本のノンブルで印刷する
春の章だけを校正するなら、文書をひとつだけrenderToPdfに渡します。ノンブルは本と同じ6〜8のままです。章扉の前の白の偶数ページはその後に始まる章に属するので、6ページの白ページもいっしょに付いてきます。
-offerPdf(() => renderToPdf(docs, { fontProvider: fontsourceProvider, resourceBytes: imageBytes }),
+offerPdf(() => renderToPdf(docs[3], { fontProvider: fontsourceProvider, resourceBytes: imageBytes }),#図番号を本全体の通し番号にする
一度もリセットしない図のカウンターを使うと、4点の巣枠の図には1.1〜4.1ではなく、文書をまたいで1〜4の番号が振られます。
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 }を指定してください。 見出しスタイル →
つまずき
1ページは奇数ページ。ページは物理的な番号で計画する
1ページは右ページで、2ページが最初の偶数ページです。見開きは物理的なページ番号で計画してください。偶数ページの章扉は、その次の奇数ページと向かい合います。 改ページと改段 →
Sandboxの検査 · chapterFrontmatterIgnored
フロントマターを無視
原因. 有効なのは最初の章のフロントマターだけです。後の章の冒頭にあるフロントマターのブロックは破棄されます。
対処. 本のメタデータは第1章に置き、章ごとの値には見出しの属性を使ってください。 ドキュメント →
- ページの先頭や、ページの先頭にある図の下では、小見出しの
marginTopが消えます。間隔を余白でとる小見出しは、その2か所では本文の1行上に、それ以外では1行半上に立ちます。ここでは間隔を小見出しの行そのものに持たせています。lineHeightを1行半、余白を1行にしたので、本のどの小見出しも本文から同じ距離に立ちます。 - 初期設定では、両端そろえの行は語間を元の幅の2倍まで広げられ、行分割はハイフンよりもそちらを選びます。この初期設定のままでは英語版にハイフンがひとつもなく、語間が通常の2倍近くまで広がった行と、0.7まで詰められた行が隣り合っていました。
maxWordSpacing: 1.7にすると、行分割は代わりにハイフネーションを選びます。変更したら、各段落の最終行を確かめてください。上限を厳しくすると最終行に1語だけが残ることがあり、段落の数語を書き換えれば直ります。
クレジット
- 本文
- 書き下ろしの文章, CC BY 4.0
- フォント
- Andada Pro (SIL OFL 1.1) · Rozha One (SIL OFL 1.1) · Figtree (SIL OFL 1.1)


