Vai al contenuto principale
Ricetta numero 148

Ricettario · Capitolo 11 · Fumetti e manga

Un fumetto in EPUB letto vignetta per vignetta

Un breve fumetto esportato in PDF, in EPUB a layout fisso con navigazione per regioni (lettura vignetta per vignetta), in Kindle Panel View e in EPUB fluido.

In questa pagina
Genere
Fumetti
Output
Canvas · PDF · EPUB
Livello
Intermedio
Postext
Provata con Postext 1.65.0
Richiede ≥ 1.65.0 · postext-pdf ≥ 1.65.0
Licenza
Aggiornata il 31 ott 2026
Codice MIT · Testo CC BY 4.0

pp. 2–3 di 3

  • Formato 168 × 259 mm
  • 1 colonna
  • Comic Neue 10,5/15
  • Bangers
  • 3 pagine
  • Livello
  • Postext 1.65.0
  • Impaginato in 284 ms
  • 184 righe di codice

In breve

Un fumetto di due pagine salvato come PDF per la stampa e come e-book: uno che mantiene le pagine e permette di ingrandire una vignetta dopo l’altra, uno per Kindle e uno in cui i dialoghi sono testo semplice.

Che cosa comporrai

Il primo capitolo del Faro di Porthcove: un frontespizio e due tavole, impaginati una volta ed esportati in quattro modi. Il PDF è per la stampa. L’EPUB a layout fisso mantiene le pagine stampate e include una navigazione per regioni, così un sistema di lettura può mostrare il libro una vignetta alla volta, passando con lo zoom dalla vignetta dell’arrivo alla radio, poi a Maya. Un secondo EPUB fisso aggiunge Kindle Panel View; quello fluido compone ogni vignetta come la sua immagine ritagliata seguita dalle sue battute. La pagina elenca ogni file come lo aprirà un lettore, con un link per scaricarlo, in dieci lingue.

Questa ricetta risponde a

  • Come rendo un EPUB a fumetti leggibile vignetta per vignetta?

La risposta breve

script.js · righe 264–279nel codice completo
// The fixed layout keeps every printed page and writes regions.xhtml (EPUB Region-Based
// Navigation): one panel region per panel in reading order, its balloons nested in it.
// kindlePanelView adds Kindle's tap-to-magnify targets; the reflowable book sets each panel
// as its cropped picture followed by its lines as text.
const book = {
  metadata: { title: doc.metadata.title, creators: [doc.metadata.author], language: config().locale,
    modified: new Date('2026-10-07T00:00:00Z') }, // a fixed date: the same bytes on every run
  fonts: await epubFonts([LETTERING, SFX], markdown), // every face the pages set, as bytes
  resourceBytes: (fileId) => ({ bytes: imageBytes(fileId), mediaType: 'image/jpeg' }),
  onWarning: (w) => console.warn(`[epub] ${w.kind}`, w.family ?? w.fileId ?? w.detail),
};
const epubs = {
  fixed: await renderToEpub(doc, { ...book, layout: 'fixed' }),
  kindle: await renderToEpub(doc, { ...book, layout: 'fixed', kindlePanelView: true }),
  reflowable: await renderToEpub(doc, { ...book, layout: 'reflowable' }),
};

Ingredienti

Tipo
Comic Neue, Bangers, Zen Antique, Dela Gothic One, ZCOOL KuaiLe, ZCOOL QingKe HuangYou, Playpen Sans Arabic, Lalezar (SIL OFL 1.1)
Risorse
  • lh-arrive.jpg
  • lh-beam.jpg
  • lh-biscuit.jpg
  • lh-maya.jpg
  • lh-radio.jpg
  • Panel picture: Maya arrives at the lighthouse (Generated With Diffusion Models, originale)
  • Panel picture: Tomás at the radio (Generated With Diffusion Models, originale)
  • Panel picture: Maya finds the problem (Generated With Diffusion Models, originale)
  • Panel picture: Biscuit asleep on the cable (Generated With Diffusion Models, originale)
  • Panel picture: the lamp lit at night (Generated With Diffusion Models, originale)

Preparazione

#1 · Esporta lo stesso documento in EPUB

Il codice è nella risposta breve qui sopra. renderToEpub riceve i documenti che stampa renderToPdf, quindi le pagine dell’EPUB sono quelle del PDF (output dei fumetti). Con layout: 'fixed' e tavole a fumetti nel libro scrive anche regions.xhtml: una regione panel per ogni vignetta nell’ordine di lettura, ciascuna un rettangolo in percentuale della sua pagina, con le nuvolette, le didascalie e le onomatopee come regioni al suo interno. La progressione delle pagine segue la direzione di lettura del fumetto, quindi le edizioni giapponese e araba si sfogliano da destra a sinistra. kindlePanelView: true aggiunge un’area da toccare per ogni vignetta e una sua copia ingrandita, con i metadati che Kindle si aspetta. L’edizione fluida non ha pagine da mantenere: ogni vignetta è la sua immagine, ritagliata come sulla pagina, poi le sue battute, «Maya: Biscuit! Dov’è il nonno?», con i nomi presi da comics.cast.

Vignetta 1 di pagina 2: nella lettura guidata è la prima regione, con la didascalia e la nuvoletta di Maya annidate al suo interno.

#2 · Incorpora i caratteri che le pagine usano

script.js · righe 210–239nel codice completo
// For each weight and style the lettering asks for, the file loadComicFonts chose (the
// nearest one Fontsource ships), only the slices whose characters the book sets. A file that
// serves several weights is embedded once, with a weight range ('400 700').
const inRange = (range, cp) => range.split(',').some((part) => {
  const [lo, hi = lo] = part.trim().slice(2).split('-');
  return cp >= parseInt(lo, 16) && cp <= parseInt(hi, 16);
});
async function epubFonts(families, text) {
  const cps = [...new Set(text)].map((ch) => ch.codePointAt(0));
  const byFile = new Map(); // url → the face it serves
  for (const family of families) {
    const meta = await fontsourceMeta(family);
    const asks = [[400, 'normal'], [700, 'normal'], [400, 'italic'], [700, 'italic']];
    for (const [weight, style] of asks) {
      const w = meta.weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a),
        400);
      const s = style === 'italic' && meta.styles.includes('italic') ? 'italic' : 'normal';
      for (const { url, range } of await comicFaceFiles(family, w, s, meta, text)) {
        if (range && !cps.some((cp) => inRange(range, cp))) continue;
        const face = byFile.get(url) ?? { family, style: s, weights: new Set(), range };
        face.weights.add(weight);
        byFile.set(url, face);
      }
    }
  }
  return Promise.all([...byFile].map(async ([url, { family, style, weights, range }]) => ({
    family, style, format: 'woff2', unicodeRange: range,
    weight: weights.size > 1 ? `${Math.min(...weights)} ${Math.max(...weights)}` : [...weights][0],
    bytes: new Uint8Array(await (await fetch(url)).arrayBuffer()) })));
}

Un EPUB a layout fisso disegna il testo con i caratteri che contiene, e un carattere lasciato fuori viene sostituito da quello del lettore. Il lettering chiede regolare, grassetto e corsivo; i caratteri da fumetto ne offrono meno, quindi ogni richiesta riceve il file che loadComicFonts ha scelto per lei, e un file che serve entrambi i pesi entra una volta sola con l’intervallo '400 700'. I caratteri giapponesi e cinesi prendono solo le porzioni che contengono i caratteri dell’edizione, e così il libro giapponese resta a 1,4 MB.

#3 · Rileggi ogni file

script.js · righe 283–304nel 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');
for (const [name, bytes] of Object.entries(epubs)) {
  const epub = readEpub(bytes);
  const regions = new TextDecoder().decode(epub.files.get(`${epub.root}regions.xhtml`)
    ?? new Uint8Array());
  const panels = regions.split('<li epub:type="panel">').slice(1); // one per panel
  const card = el('article', 'width: min(300px, 92vw); padding: 16px; border: 1px solid #2c3038');
  const steps = el('ol', 'margin: 8px 0; padding-left: 22px');
  steps.append(...panels.map((p, i) => el('li', '', `panel ${i + 1}: ${(p.match(
    /epub:type="(balloon|caption|sound-area|text-area)"/g) ?? []).length} text regions`)));
  const link = Object.assign(el('a', 'color: #d8a21a', `Download ${RECIPE}-${name}.epub`), {
    href: URL.createObjectURL(new Blob([bytes])), download: `${RECIPE}-${name}.epub` });
  card.append(el('h2', 'margin: 0; font-size: 15px; color: #f4f1ea', `EPUB 3 · ${name}`),
    el('p', 'margin: 4px 0 0', `${epub.layout} · ${epub.pageProgression} · `
      + `${epub.spine.length} documents · ${Math.round(bytes.length / 1024)} KB`),
    panels.length ? steps : el('p', '', 'No region navigation: the panels are text.'), link);
  shelf.append(card);
}
document.getElementById('pages').before(shelf);

readEpub apre i byte come farebbe un sistema di lettura: layout, progressione delle pagine, spine. L’elenco sotto ogni scheda è la lettura guidata stessa, letta da regions.xhtml: cinque vignette e le loro regioni di testo, nell’ordine in cui un lettore le percorre. I tre file superano EPUBCheck 5.4 senza errori né avvisi in inglese, giapponese e arabo.

#4 · Un’impaginazione, dieci edizioni

script.js · righe 36–41nel codice completo
const [LETTERING, SFX] = t({
  en: ['Comic Neue', 'Bangers'], es: ['Comic Neue', 'Bangers'], ca: ['Comic Neue', 'Bangers'],
  ja: ['Zen Antique', 'Dela Gothic One'], zh: ['ZCOOL KuaiLe', 'ZCOOL QingKe HuangYou'],
  ar: ['Playpen Sans Arabic', 'Lalezar'], pt: ['Comic Neue', 'Bangers'],
  fr: ['Comic Neue', 'Bangers'], de: ['Comic Neue', 'Bangers'], it: ['Comic Neue', 'Bangers'],
});

Ogni content.<lang>.md contiene le parole di un’edizione sotto gli stessi id dei personaggi. Le regioni delle vignette sono le stesse in ogni lingua; quelle delle nuvolette si spostano con le nuvolette, che vengono riletterate attorno al testo di ciascuna lingua.

La ricetta completa

Sandbox
// ═══ Postext Cookbook · Nº 148 · A comic EPUB read panel by panel ═══════════════════
// https://postext.dev/en/cookbook/comic-epub-guided-view
// Code: MIT · Text: original (CC BY 4.0) · Pictures: generated with diffusion models
// Fonts: Comic Neue, Bangers and the faces of five editions (OFL) · Needs postext ≥ 1.65.0
//
// A short comic laid out once and exported four ways: a PDF for print, a fixed-layout EPUB
// whose region-based navigation lets a reading system step through it panel by panel, the
// same EPUB with Kindle Panel View, and a reflowable EPUB with each panel's lines as text.
// Each file is read back to list what a reader will find in it.
import {
  buildDocument, withLoadedFonts, renderPageToCanvas, registerResourceImage, loadVerticalAlternates,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
import { renderToEpub, readEpub } from 'https://esm.sh/postext-epub';

const LANG = 'it'; // @lang: 'en' | 'es' | 'ca' | 'zh' | 'ar' | 'ja' | 'pt' | 'fr' | 'de' | 'it'
const RECIPE = 'comic-epub-guided-view';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: the night sea, the lighthouse red and the yellow of the captions
const palette = {
  ink: '#1b2430', // panel borders, lettering and the title page
  accent: '#b8322a', // the lighthouse red: title and sound effects
  caption: '#f4e7bf', // caption boxes
  muted: '#5f6873', // folios and the imprint
  paper: '#fdfbf6',
};
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

// #region editions: six editions, each lettered in faces for its script
const [LETTERING, SFX] = t({
  en: ['Comic Neue', 'Bangers'], es: ['Comic Neue', 'Bangers'], ca: ['Comic Neue', 'Bangers'],
  ja: ['Zen Antique', 'Dela Gothic One'], zh: ['ZCOOL KuaiLe', 'ZCOOL QingKe HuangYou'],
  ar: ['Playpen Sans Arabic', 'Lalezar'], pt: ['Comic Neue', 'Bangers'],
  fr: ['Comic Neue', 'Bangers'], de: ['Comic Neue', 'Bangers'], it: ['Comic Neue', 'Bangers'],
});
// #endregion

const comics = {
  gutter: { horizontal: mm(4), vertical: mm(3) },
  panel: { borderWidth: pt(1), borderColor: col('ink'), background: col('paper') },
  lettering: { fontFamily: LETTERING, fontSize: pt(8), color: col('ink'), inset: mm(1.5) },
  balloonStyles: [{ id: 'speech', stroke: col('ink') }, { id: 'caption', fill: col('caption'),

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

#Lascia fuori l’edizione Kindle

La navigazione per regioni si scrive in ogni EPUB fisso; Kindle Panel View si limita ad aggiungersi.

-  kindle: await renderToEpub(doc, { ...book, layout: 'fixed', kindlePanelView: true }),

#Dai una copertina al libro fluido

-  reflowable: await renderToEpub(doc, { ...book, layout: 'reflowable' }),
+  reflowable: await renderToEpub(doc, { ...book, layout: 'reflowable',
+    cover: { bytes: imageBytes('lh-beam.jpg'), mediaType: 'image/jpeg' } }),

Errori frequenti

  • Un carattere incorporato una volta per ogni peso che serve verrebbe copiato quattro volte; l’edizione cinese pesava 5,3 MB prima degli intervalli di peso.

Crediti

Testo
Testo originale, CC BY 4.0
Immagini
  • Panel picture: Maya arrives at the lighthouse · Generated With Diffusion Models · originale
  • Panel picture: Tomás at the radio · Generated With Diffusion Models · originale
  • Panel picture: Maya finds the problem · Generated With Diffusion Models · originale
  • Panel picture: Biscuit asleep on the cable · Generated With Diffusion Models · originale
  • Panel picture: the lamp lit at night · Generated With Diffusion Models · originale
Font
Comic Neue (SIL OFL 1.1) · Bangers (SIL OFL 1.1) · Zen Antique (SIL OFL 1.1) · Dela Gothic One (SIL OFL 1.1) · ZCOOL KuaiLe (SIL OFL 1.1) · ZCOOL QingKe HuangYou (SIL OFL 1.1) · Playpen Sans Arabic (SIL OFL 1.1) · Lalezar (SIL OFL 1.1)
SandboxPDF