Skip to main content
Recipe number 115

Cookbook · Chapter 10 · Output & integration

One book, two EPUB 3 files: fixed and reflowable

renderToEpub from postext-epub writes the chapters buildBundle laid out as a fixed-layout EPUB and a reflowable one; readEpub lists what each file holds.

pp. 2–3 of 14

  • Trim 120 × 190 mm
  • 1 column
  • Libre Caslon Text 9.6/13.5
  • Jost
  • Libre Caslon Display
  • 14 pages
  • Level
  • Postext 1.65.0
  • Laid out in 137 ms
  • 178 lines of code

In short

A small book of fables, laid out for print once and saved as two e-books: one that keeps every printed page, and one whose text a phone or an e-reader sets again at its own size.

What you'll build

Fables of Aesop, eighteen fables in three books on a 120 × 190 mm page, with a title page, an imprint on its verso and a sunk opener for each book. The Spanish edition sets Clarín’s ¡Adiós, Cordera! in three chapters on the same page. The book is laid out once, chapter by chapter, and that layout becomes two EPUB 3 files. The fixed layout keeps every printed page: the openers, the running heads and the line breaks, in the embedded Caslon. The reflowable file keeps the text and its structure, and the reading system sets it again on a phone or an e-ink screen. Both download from the page, and both pass W3C EPUBCheck.

This recipe answers

  • How do I export my book as an EPUB, with fixed pages or with reflowable text?

The short answer

script.js · lines 256–270in full code
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' });

One layout, two EPUB 3 files: every printed page, or text that reflows

Ingredients

Type
Libre Caslon Text, Libre Caslon Display, Jost (SIL OFL 1.1)
Assets
None: every picture is drawn in code

Method

#1 · Lay the book out as chapters

script.js · lines 42–61in full code
// 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 lays out each chapter as a document of its own, carrying page numbers and parity from one to the next, so docs is the array renderToPdf would print. The EPUB writer reads the same array: each chapter becomes a navigation entry, and the reflowable file writes one XHTML document per chapter. The title page and its imprint are the first chapter, and its front matter is the book’s title, subtitle and author.

#2 · Hand the writer the font files

script.js · lines 235–246in full code
// 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 };
  })));

The faces the browser loaded are not files the writer can read, so the pen fetches the same Fontsource woff2 files again; the browser has them cached. Each one becomes a font file in the EPUB and an @font-face rule. Without them the fixed layout would place text set in Caslon in a reader’s own face, and the lines would no longer fit their measure.

#3 · Write both renditions

The code is the short answer above. layout: 'fixed' writes one XHTML document per printed page at the trimmed page size, with real, selectable text; layout: 'reflowable' rebuilds paragraphs from the laid-out lines, drops the hyphens the line breaks added and derives a stylesheet from the configuration. A fixed modified date makes each run produce the same bytes. The metadata comes from the first chapter’s front matter, so the file’s title and author are the ones printed on the title page.

#4 · Read each file back

script.js · lines 274–296in full code
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 opens the file the way a reading system does: the spine in reading order, the contents, the page list and the layout. The fixed file has one spine entry per page; the reflowable one has four, one per chapter. Both carry a page list of the printed folios, so a reader can follow a citation to page 9 in either. The <a download> link gives the bytes a file name; nothing goes through a server.

The whole recipe

Sandbox
// ═══ 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'),

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

#Give the fixed layout a cover picture

Paint the title page to a canvas and pass it as the cover; showsFirstPage tells the writer not to add it as a page of its own.

+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 });

renderToPdf(docs, …) from postext-pdf takes the same array, so the PDF, the EPUB and the screen come from one layout. The Catalan pocket novella shows the PDF side.

Pitfalls

Pitfall

renderToEpub embeds only the fonts you hand it

The browser's loaded faces are not files postext-epub can read: pass the bytes of every face the pages use in options.fonts (the same Fontsource woff2 files the page loaded). A face left out is reported as missingFont, and the reading system sets that text in a face of its own, which in a fixed layout no longer fits the lines the page was set with. Embed only faces whose licence allows it. EPUB export →

The reflowable file keeps a heading’s text but not its design: the kicker of each opener (Book I) is a design element, so it is not in the text. Put words the reader must see in the heading itself or in the text.

Credits

Text
  • 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 · public domain
  • ¡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 · public domain
Fonts
Libre Caslon Text (SIL OFL 1.1) · Libre Caslon Display (SIL OFL 1.1) · Jost (SIL OFL 1.1)
Sandbox