简单来说
一本小小的寓言集,为印刷排一次版,存成两本电子书:一本保留每一页印刷页面,另一本的文字由手机或电子阅读器按自己的字号重新排。
成品一览
《伊索寓言》(Fables of Aesop),十八篇寓言分为三卷,页面120 × 190 mm,有书名页、背面的版权页,每卷有下沉的章首页;西班牙语版用同样的设计排克拉林(Clarín)的短篇小说*¡Adiós, Cordera!*。全书按章排一次版,这份排版生成两个EPUB 3文件。固定版式保留每一页印刷页面:章首页、书眉和换行,用嵌入的Caslon字体。流式版式保留文字及其结构,由阅读系统在手机或电子墨水屏上重新排。两个文件都能从页面下载,也都通过W3C的EPUBCheck校验。
这道食谱解答
- 怎样把书导出为EPUB,用固定页面还是流式文本?
简短回答
const { title, subtitle, author } = docs[0].metadata; // the first chapter's front matter
const book = {
metadata: { title, subtitle, creators: [author], language: LANG,
rights: t({ en: 'Public domain', es: 'Dominio público' }),
// A fixed date gives the same bytes on every run; the identifier (a urn:uuid) comes
// from the title, the author and the language, so a new version keeps its place.
modified: new Date('2026-10-04T00:00:00Z') },
// Every face the pages use, as bytes: a face left out is set in the reader's own
// (gotcha: epub-embeds-given-fonts).
fonts: await epubFonts(FONTS),
onWarning: (w) => console.warn(`[epub] ${w.kind}`, w.family ?? w.fileId ?? w.detail),
};
// The same documents renderToPdf would print: one per chapter, in book order.
const fixed = await renderToEpub(docs, { ...book, layout: 'fixed' });
const reflowable = await renderToEpub(docs, { ...book, layout: 'reflowable' });
用料
- 类型
- Libre Caslon Text, Libre Caslon Display, Jost(SIL OFL 1.1)
- 素材
- 无:所有图片都用代码绘制
做法
#1 · 按章排书
// Each line spans the measure and centres its text; the rule centres under the title.
const text = (id, content, fontFamily, size, placement, extra = {}) => ({ kind: 'text', id,
content, fontFamily, fontSize: pt(size), color: col('ink'), align: 'center',
overflow: 'wrap', lineHeight: 1.15, ...extra,
placement: { ...placement, size: { width: 'fill', height: 'auto' } } });
const rule = (id, below, y) => ({ kind: 'rule', id, direction: 'horizontal', thickness: pt(0.75),
color: col('accent'),
placement: { ...at(below, 'below', (MEASURE - 10) / 2, y), size: { width: mm(10) } } });
const titlePage = { id: 'title-page', header: { elements: [] }, footer: { elements: [] },
marginBottom: pt(0), advancedDesign: { enabled: true, minHeight: mm(120), slot: { elements: [
text('author', '{author}', LABEL, 9, at('container', 'top-left', 0, 30), caps(9)),
text('title', '{titleText}', DISPLAY, 34, at('#author', 'below', 0, 8)),
rule('rule', '#title', 6),
text('subtitle', '{subtitle}', TEXT, 11, at('#title', 'below', 0, 13), { italic: true }),
] } } };
const opener = { enabled: true, minHeight: mm(56), slot: { elements: [
text('kicker', '{attr.kicker}', LABEL, 8, at('container', 'top-left', 0, 14), caps(8)),
text('title', '{titleText}', DISPLAY, 28, at('#kicker', 'below', 0, 4)),
rule('rule', '#title', 5),
] } };
buildBundle把每一章排成一个独立的文档,并把页码和奇偶页从一章带到下一章,所以docs就是renderToPdf要打印的那个数组。EPUB写入器读取同一个数组:每章是导航目录里的一项,流式文件为每章写一个XHTML文档。书名页和版权页是第一章,它的前置元数据提供书名、副题和作者。
#2 · 把字体文件交给写入器
// Only the latin files: they hold every letter of both samples. A text beyond Latin-1 would
// add each family's latin-ext file with its unicodeRange.
const epubFonts = (faces) => Promise.all(Object.entries(faces).flatMap(([family, specs]) =>
specs.map(async (spec) => {
const [weight, style] = [parseInt(spec, 10), spec.endsWith('i') ? 'italic' : 'normal'];
const id = fontsourceId(family);
const res = await fetch(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/`
+ `${id}-latin-${weight}-${style}.woff2`);
if (!res.ok) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
const bytes = new Uint8Array(await res.arrayBuffer());
return { family, weight, style, format: 'woff2', bytes };
})));
浏览器加载的字体不是写入器能读取的文件,所以代码再次获取同一批Fontsource woff2文件,浏览器已经缓存了它们。每个文件都成为EPUB里的一个字体文件和一条@font-face规则。没有它们,固定版式会用阅读器自己的字体放置用Caslon排的文字,行就不再符合原来的行长。
#3 · 写出两种版式
代码就是上面的简短回答。layout: 'fixed'为每一页印刷页面写一个XHTML文档,尺寸是裁切后的页面,文字是真正的文字,可以选中;layout: 'reflowable'根据排好的行重建段落,去掉换行时加上的连字符,并从配置生成样式表。固定的modified日期让每次运行得到相同的字节。元数据来自第一章的前置元数据,所以文件的书名和作者就是书名页上印的那些。
#4 · 把每个文件读回来
const el = (tag, css, text) => Object.assign(document.createElement(tag),
{ textContent: text ?? '' }, { style: css });
const shelf = el('section', 'display: flex; flex-wrap: wrap; gap: 16px; justify-content: center;'
+ 'padding: 24px 16px 0; color: #d9d5cc; font: 13px/1.5 system-ui, sans-serif');
shelf.id = 'epub';
for (const [layout, bytes] of [['fixed', fixed], ['reflowable', reflowable]]) {
const epub = readEpub(bytes); // what a reading system opens: spine, contents, page list
const file = `${RECIPE}-${layout}.epub`;
const card = el('article', 'width: min(420px, 92vw); padding: 16px 18px;'
+ 'border: 1px solid #2c3038; border-radius: 6px; background: #15181d');
const spine = el('ol', 'margin: 8px 0; padding-left: 22px; max-height: 9em; overflow: auto');
spine.append(...epub.spine.map((item) => el('li', '', item.path.slice(epub.root.length))));
const link = el('a', 'color: #d8a21a', `Download ${file}`);
link.href = URL.createObjectURL(new Blob([bytes], { type: 'application/epub+zip' }));
link.download = file;
card.append(el('h2', 'margin: 0; font-size: 15px; color: #f4f1ea', `EPUB 3 · ${epub.layout}`),
el('p', 'margin: 4px 0 0', `${epub.spine.length} documents in the spine · `
+ `${epub.toc.length} contents entries · ${epub.pageList.length} print pages · `
+ `${Math.round(bytes.length / 1024)} KB`), spine, link);
shelf.append(card);
}
document.getElementById('pages').before(shelf);
kitStatus(`${docs.length} documents laid out · two EPUB 3 files`);
readEpub像阅读系统那样打开文件:阅读顺序(spine)、目录、页码列表和版式。固定版式文件每页一项;流式文件有四项,每章一项。两个文件都带有印刷页码列表,所以引文里的第9页在哪个文件里都能找到。<a download>链接给字节起一个文件名,不经过任何服务器。
完整食谱
// ═══ Postext Cookbook · Nº 115 · One book, two EPUB 3 files: fixed and reflowable ════
// https://postext.dev/en/cookbook/epub-fixed-and-reflowable
// Code: MIT · Text: Aesop, tr. G. F. Townsend, 1867; L. Alas, Clarín, 1893 (PD) · Pictures: none
// Fonts: Libre Caslon Text, Libre Caslon Display, Jost (SIL OFL 1.1) · Needs postext ≥ 1.65.0
//
// A small book of three chapters, laid out once with buildBundle and written as two EPUB 3
// files with postext-epub: a fixed layout that keeps every printed page, and reflowable text
// that a phone or an e-reader sets again. Each file is read back with readEpub to list what
// a reading system will open, with a link to download it.
import {
buildBundle, prepareFonts, withLoadedFonts, renderPageToCanvas,
} from 'https://esm.sh/postext';
import { renderToEpub, readEpub } from 'https://esm.sh/postext-epub';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'epub-fixed-and-reflowable';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
ink: '#211e1b', // text: a warm near-black
accent: '#2d5872', // Prussian blue: kickers, rules, folios
rule: '#c8c0b4', // the title page's hairline
muted: '#6b645d', // running heads and the imprint
paper: '#fbf8f1', // an off-white page, kept in the fixed-layout EPUB
};
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' } },
];
// #endregion
const [TEXT, DISPLAY, LABEL] = ['Libre Caslon Text', 'Libre Caslon Display', 'Jost'];
const [TRIM_W, TRIM_H, TOP, BOTTOM, INNER, OUTER] = [120, 190, 20, 22, 16, 15]; // mm
const MEASURE = TRIM_W - INNER - OUTER; // 89 mm: about 62 characters of Libre Caslon Text
const LEAD = 13.5; // pt: the body leading
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const caps = (size, color = 'accent') => ({ fontFamily: LABEL, fontSize: pt(size),
fontWeight: 600, letterSpacing: pt(size * 0.2), textTransform: 'uppercase', color: col(color) });
// #region openers: a title page, then each chapter sunk under its kicker and a short rule
// Each line spans the measure and centres its text; the rule centres under the title.
const text = (id, content, fontFamily, size, placement, extra = {}) => ({ kind: 'text', id,
content, fontFamily, fontSize: pt(size), color: col('ink'), align: 'center',
overflow: 'wrap', lineHeight: 1.15, ...extra,
placement: { ...placement, size: { width: 'fill', height: 'auto' } } });
const rule = (id, below, y) => ({ kind: 'rule', id, direction: 'horizontal', thickness: pt(0.75),
color: col('accent'),
组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)
变化
#给固定版式加封面图片
把书名页画到canvas上,作为封面传入;showsFirstPage告诉写入器不要再把它加成一页。
+const canvas = document.createElement('canvas');
+renderPageToCanvas(docs[0].pages[0], docs[0], canvas, { scale: 2 });
+const png = await new Promise((done) => canvas.toBlob(done, 'image/png'));
+const cover = { bytes: new Uint8Array(await png.arrayBuffer()), mediaType: 'image/png',
+ showsFirstPage: true };
-const fixed = await renderToEpub(docs, { ...book, layout: 'fixed' });
+const fixed = await renderToEpub(docs, { ...book, layout: 'fixed', cover });#把同样的章节印成PDF
postext-pdf的renderToPdf(docs, …)接受同一个数组,所以PDF、EPUB和屏幕都来自同一份排版。加泰罗尼亚语口袋本小说展示了PDF这一边。
常见问题
易错点
renderToEpub只嵌入你交给它的字体
浏览器加载的字体不是postext-epub能读取的文件:把页面用到的每款字体的字节放进options.fonts(页面加载的同一批Fontsource woff2文件)。缺少的字体会报告为missingFont,阅读系统会用自己的字体排这段文字,在固定版式中就不再符合页面排版时的行。只嵌入许可证允许嵌入的字体。 导出EPUB →
流式文件保留标题的文字,但不保留它的设计:每个章首页的眉题(Book I)是设计元素,不属于正文。读者必须看到的字要写在标题本身或正文里。
致谢
- 文本
- Eighteen fables from Three Hundred Æsop’s Fables, translated from the Greek by George Fyler Townsend (London, 1867), the opening capitals of each fable set in lower case · Aesop, tr. George Fyler Townsend · 公有领域
- ¡Adiós, Cordera!, complete, from El Señor y lo demás, son cuentos (Madrid, 1893), its five parts grouped in three chapters, with dialogue dashes and « » quotation marks · Leopoldo Alas, Clarín · 公有领域
- 字体
- Libre Caslon Text (SIL OFL 1.1) · Libre Caslon Display (SIL OFL 1.1) · Jost (SIL OFL 1.1)


