Vai al contenuto principale
Ricetta numero 115

Ricettario · Capitolo 10 · Output e integrazione

Un libro, due file EPUB 3: layout fisso e fluido

renderToEpub di postext-epub scrive i capitoli impaginati da buildBundle come EPUB a layout fisso e come EPUB fluido; readEpub elenca il contenuto di ogni file.

In questa pagina

pp. 2–3 di 14

  • Esempio in inglese: non c’è ancora un’edizione italiana
  • Formato 120 × 190 mm
  • 1 colonna
  • Libre Caslon Text 9,6/13,5
  • Jost
  • Libre Caslon Display
  • 14 pagine
  • Livello
  • Postext 1.65.0
  • Impaginato in 137 ms
  • 178 righe di codice

In breve

Un piccolo libro di favole, impaginato una volta per la stampa e salvato come due e-book: uno conserva ogni pagina stampata, l’altro ha un testo che il telefono o l’e-reader ricompone alla propria misura.

Che cosa comporrai

Fables of Aesop, diciotto favole in tre libri su una pagina di 120 × 190 mm, con un frontespizio, il colophon sul suo verso e un’apertura ribassata per ogni libro. L’edizione spagnola compone ¡Adiós, Cordera! di Clarín in tre capitoli sulla stessa pagina. Il libro viene impaginato una volta, capitolo per capitolo, e quell’impaginazione diventa due file EPUB 3. Il layout fisso conserva ogni pagina stampata: le aperture, le testatine e gli a capo, nel Caslon incorporato. Il file fluido conserva il testo e la sua struttura, e il sistema di lettura lo ricompone su un telefono o su uno schermo e-ink. Entrambi si scaricano dalla pagina, ed entrambi superano EPUBCheck del W3C.

Questa ricetta risponde a

  • Come esporto il mio libro come EPUB, con pagine fisse o con testo fluido?

La risposta breve

script.js · righe 256–270nel codice completo
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' });

Ingredienti

Tipo
Libre Caslon Text, Libre Caslon Display, Jost (SIL OFL 1.1)
Risorse
Nessuna: ogni immagine è disegnata nel codice

Preparazione

#1 · Impagina il libro per capitoli

script.js · righe 42–61nel codice completo
// 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 impagina ogni capitolo come documento a sé, portando i numeri di pagina e la parità dall’uno all’altro, quindi docs è l’array che stamperebbe renderToPdf. Il writer EPUB legge lo stesso array: ogni capitolo diventa una voce di navigazione, e il file fluido scrive un documento XHTML per capitolo. Il frontespizio e il suo colophon sono il primo capitolo, e il suo front matter contiene titolo, sottotitolo e autore del libro.

#2 · Passa al writer i file dei font

script.js · righe 235–246nel codice completo
// 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 };
  })));

I caratteri caricati dal browser non sono file che il writer possa leggere, quindi il pen scarica di nuovo gli stessi file woff2 da Fontsource; il browser li ha in cache. Ognuno diventa un file di font nell’EPUB e una regola @font-face. Senza di essi il layout fisso collocherebbe il testo composto in Caslon nel carattere del lettore, e le righe non entrerebbero più nella loro giustezza.

#3 · Scrivi le due versioni

Il codice è la risposta breve qui sopra. layout: 'fixed' scrive un documento XHTML per pagina stampata, al formato rifilato, con testo vero e selezionabile; layout: 'reflowable' ricostruisce i paragrafi dalle righe impaginate, toglie i trattini aggiunti dagli a capo e ricava un foglio di stile dalla configurazione. Una data modified fissa fa sì che ogni esecuzione produca gli stessi byte. I metadati vengono dal front matter del primo capitolo, quindi il titolo e l’autore del file sono quelli stampati sul frontespizio.

#4 · Rileggi ogni file

script.js · righe 274–296nel codice completo
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 apre il file come fa un sistema di lettura: lo spine in ordine di lettura, l’indice, l’elenco delle pagine e il layout. Il file fisso ha una voce dello spine per pagina; quello fluido ne ha quattro, una per capitolo. Entrambi contengono un elenco delle pagine con i numeri di pagina stampati, così un lettore può seguire una citazione fino a pagina 9 in tutti e due. Il link <a download> dà un nome di file ai byte; nulla passa da un server.

La ricetta completa

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

Lo script.js composto funziona così com’è: incollalo nello script modulo di qualsiasi pagina, oppure apri la ricetta su CodePen. Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)

Varianti

#Dai al layout fisso un’immagine di copertina

Dipingi il frontespizio su un canvas e passalo come copertina; showsFirstPage indica al writer di non aggiungerlo come pagina a sé.

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

#Stampa gli stessi capitoli in PDF

renderToPdf(docs, …) di postext-pdf accetta lo stesso array, quindi il PDF, l’EPUB e lo schermo vengono da un’unica impaginazione. Il romanzo breve tascabile in catalano mostra il lato PDF.

Errori frequenti

Errore frequente

renderToEpub incorpora solo i font che gli passi

Le varianti caricate dal browser non sono file che postext-epub possa leggere: passa in options.fonts i byte di ogni variante usata dalle pagine (gli stessi file woff2 di Fontsource caricati dalla pagina). Una variante omessa viene segnalata come missingFont, e il sistema di lettura compone quel testo con un carattere suo, che in un layout fisso non entra più nelle righe con cui la pagina è stata composta. Incorpora solo varianti la cui licenza lo permette. Esportazione in EPUB →

Il file fluido conserva il testo di un titolo ma non la sua grafica: l’occhiello di ogni apertura (Book I) è un elemento grafico, quindi non fa parte del testo. Metti le parole che il lettore deve vedere nel titolo stesso o nel testo.

Crediti

Testo
  • 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 · pubblico dominio
  • ¡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 · pubblico dominio
Font
Libre Caslon Text (SIL OFL 1.1) · Libre Caslon Display (SIL OFL 1.1) · Jost (SIL OFL 1.1)
Sandbox