Zum Hauptinhalt springen
Rezept Nummer 115

Rezepte · Kapitel 10 · Ausgabe und Integration

Ein Buch, zwei EPUB-3-Dateien: fest und umfließend

renderToEpub aus postext-epub schreibt die von buildBundle gesetzten Kapitel als EPUB mit festem Layout und als umfließendes; readEpub listet den Inhalt.

Auf dieser Seite
Ausgabe
Canvas · EPUB
Postext
Getestet mit Postext 1.65.0
Erfordert ≥ 1.65.0
Lizenz
Aktualisiert am 31. Okt. 2026
Code MIT · Text MIT

S. 2–3 von 14

  • Englisches Beispiel: noch keine deutsche Ausgabe
  • Endformat 120 × 190 mm
  • 1 Spalte
  • Libre Caslon Text 9,6/13,5
  • Jost
  • Libre Caslon Display
  • 14 Seiten
  • Stufe
  • Postext 1.65.0
  • In 137 ms gesetzt
  • 178 Zeilen Code

Kurz gesagt

Ein kleines Fabelbuch, einmal für den Druck gesetzt und als zwei E-Books gespeichert: eines, das jede gedruckte Seite bewahrt, und eines, dessen Text ein Handy oder E-Reader in eigener Größe neu setzt.

Was Sie setzen

Fables of Aesop, achtzehn Fabeln in drei Büchern auf einem Format von 120 × 190 mm, mit Titelseite, einem Impressum auf deren Rückseite und einem abgesenkten Auftakt für jedes Buch. Die spanische Ausgabe setzt Claríns ¡Adiós, Cordera! in drei Kapiteln auf demselben Format. Das Buch wird einmal gesetzt, Kapitel für Kapitel, und aus diesem Satz entstehen zwei EPUB-3-Dateien. Das feste Layout bewahrt jede gedruckte Seite: die Auftakte, die Kolumnentitel und die Zeilenumbrüche, in der eingebetteten Caslon. Die umfließende Datei bewahrt den Text und seine Struktur, und das Lesesystem setzt ihn auf einem Handy oder einem E-Ink-Bildschirm neu. Beide lassen sich von der Seite herunterladen, und beide bestehen W3C EPUBCheck.

Dieses Rezept beantwortet

  • Wie exportiere ich mein Buch als EPUB, mit festen Seiten oder mit umfließendem Text?

Die kurze Antwort

script.js · Zeilen 256–270im vollständigen 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' });

Zutaten

Schrift
Libre Caslon Text, Libre Caslon Display, Jost (SIL OFL 1.1)
Dateien
Keine: Jedes Bild wird im Code gezeichnet

Zubereitung

#1 · Das Buch als Kapitel setzen

script.js · Zeilen 42–61im vollständigen 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 setzt jedes Kapitel als eigenes Dokument und führt Seitenzahlen und Parität von einem zum nächsten fort; docs ist also das Array, das renderToPdf ausgeben würde. Der EPUB-Schreiber verarbeitet dasselbe Array: Jedes Kapitel wird zu einem Navigationseintrag, und die umfließende Datei schreibt ein XHTML-Dokument pro Kapitel. Titelseite und Impressum sind das erste Kapitel, und dessen Frontmatter enthält Titel, Untertitel und Autor des Buches.

#2 · Dem Schreiber die Schriftdateien übergeben

script.js · Zeilen 235–246im vollständigen 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 };
  })));

Die Schriften, die der Browser geladen hat, sind keine Dateien, die der Schreiber lesen kann; der Pen holt daher dieselben woff2-Dateien von Fontsource erneut, der Browser hat sie im Cache. Jede wird zu einer Schriftdatei im EPUB und zu einer Regel @font-face. Ohne sie würde das feste Layout den in Caslon gesetzten Text in der Schrift des Lesegeräts platzieren, und die Zeilen passten nicht mehr in ihre Satzbreite.

#3 · Beide Fassungen schreiben

Der Code steht oben in der kurzen Antwort. layout: 'fixed' schreibt ein XHTML-Dokument pro gedruckter Seite im beschnittenen Seitenformat, mit echtem, auswählbarem Text; layout: 'reflowable' baut die Absätze aus den gesetzten Zeilen wieder auf, entfernt die Trennstriche, die die Zeilenumbrüche hinzugefügt haben, und leitet ein Stylesheet aus der Konfiguration ab. Ein festes Datum modified sorgt dafür, dass jeder Lauf dieselben Bytes erzeugt. Die Metadaten kommen aus dem Frontmatter des ersten Kapitels, sodass Titel und Autor der Datei die auf der Titelseite gedruckten sind.

#4 · Jede Datei zurücklesen

script.js · Zeilen 274–296im vollständigen 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 öffnet die Datei wie ein Lesesystem: den Spine in Lesereihenfolge, das Inhaltsverzeichnis, die Seitenliste und das Layout. Die feste Datei hat einen Spine-Eintrag pro Seite, die umfließende vier, einen pro Kapitel. Beide enthalten eine Seitenliste der gedruckten Paginas, sodass ein Leser in beiden einem Verweis auf Seite 9 folgen kann. Der Link <a download> gibt den Bytes einen Dateinamen; nichts läuft über einen Server.

Das ganze Rezept

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'),

Das zusammengesetzte script.js läuft unverändert: Fügen Sie es in das Modulskript einer beliebigen Seite ein, oder öffnen Sie das Rezept auf CodePen. Ordner des Rezepts auf GitHub ↗ (öffnet sich in einem neuen Tab)

Varianten

#Dem festen Layout ein Umschlagbild geben

Zeichnen Sie die Titelseite in ein Canvas und übergeben Sie sie als Umschlag; showsFirstPage sagt dem Schreiber, sie nicht als eigene Seite hinzuzufügen.

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

#Dieselben Kapitel als PDF drucken

renderToPdf(docs, …) aus postext-pdf nimmt dasselbe Array, sodass PDF, EPUB und Bildschirm aus einem Satz stammen. Die katalanische Novelle zeigt die PDF-Seite.

Häufige Fehler

Häufiger Fehler

renderToEpub bettet nur die Schriften ein, die Sie ihm übergeben

Die vom Browser geladenen Schnitte sind keine Dateien, die postext-epub lesen kann: Übergeben Sie die Bytes jedes Schnitts, den die Seiten verwenden, in options.fonts (dieselben woff2-Dateien von Fontsource, die die Seite geladen hat). Ein fehlender Schnitt wird als missingFont gemeldet, und das Lesesystem setzt diesen Text in einer eigenen Schrift, die bei festem Layout nicht mehr in die Zeilen passt, mit denen die Seite gesetzt wurde. Betten Sie nur Schnitte ein, deren Lizenz es erlaubt. EPUB-Export →

Die umfließende Datei bewahrt den Text einer Überschrift, aber nicht ihre Gestaltung: Die Dachzeile jedes Auftakts (Book I) ist ein Gestaltungselement und steht daher nicht im Text. Setzen Sie Wörter, die der Leser sehen muss, in die Überschrift selbst oder in den Text.

Nachweise

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