Коротко
Комикс в две страницы, сохранённый как PDF для печати и как электронные книги: одна хранит страницы и позволяет переходить от кадра к кадру, другая для Kindle, а в третьей диалоги — обычный текст.
Что получится
Первая глава The Porthcove Light («Маяк Портков»): титул и две страницы комикса, свёрстанные один раз и экспортированные четырьмя способами. PDF нужен для печати. EPUB с постоянной вёрсткой хранит печатные страницы и несёт навигацию по областям, поэтому программа чтения может показывать книгу по одному кадру: приближать приход к маяку, затем радио, затем Майю. Второй постоянный EPUB добавляет Kindle Panel View; перетекаемый ставит каждый кадр его обрезанной картинкой, а за ней реплики. Страница перечисляет каждый файл так, как его откроет читатель, со ссылкой для скачивания, на десяти языках.
Рецепт отвечает на вопросы
- Как сделать комикс в EPUB читаемым кадр за кадром?
Короткий ответ
// 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' }),
};
Ингредиенты
- Возможности
- Комиксы в PDF и EPUBЭкспорт в EPUBРазбиение на кадрыРисунок кадра и кадрированиеСтраницы комиксовЛеттеринг комиксовЛеттеринг на других языкахПерсонажи и якоряСтили облачковБезопасная зона иллюстрацииСемантическая палитраСтраницы на холстеЭкспорт в PDF
- Также применяет
- Рамки кадров и промежуткиЦвет бумагиКолонтитулы по роли страницыСтили абзацевШрифты, встроенные в PDFРисунки и таблицы как ресурсыЗвукоподражания
- Шрифты
- Comic Neue, Bangers, Zen Antique, Dela Gothic One, ZCOOL KuaiLe, ZCOOL QingKe HuangYou, Playpen Sans Arabic, Lalezar (SIL OFL 1.1)
- Материалы
lh-arrive.jpglh-beam.jpglh-biscuit.jpglh-maya.jpglh-radio.jpg- Panel picture: Maya arrives at the lighthouse (Generated With Diffusion Models, оригинал)
- Panel picture: Tomás at the radio (Generated With Diffusion Models, оригинал)
- Panel picture: Maya finds the problem (Generated With Diffusion Models, оригинал)
- Panel picture: Biscuit asleep on the cable (Generated With Diffusion Models, оригинал)
- Panel picture: the lamp lit at night (Generated With Diffusion Models, оригинал)
Порядок работы
#1 · Экспортируйте тот же документ в EPUB
Код приведён выше, в коротком ответе. renderToEpub берёт документы, которые печатает renderToPdf, поэтому страницы EPUB те же, что в PDF (вывод комиксов). Если в книге с layout: 'fixed' есть комиксные страницы, записывается и regions.xhtml: по области panel на кадр в порядке чтения, каждая — прямоугольник в процентах страницы, внутри которого облачка, подписи и звукоподражания тоже записаны областями. Порядок листания следует направлению чтения комикса, поэтому японская и арабская версии листаются справа налево. kindlePanelView: true добавляет на каждый кадр область касания и увеличенную копию вместе с метаданными, которых ждёт Kindle. В перетекаемом варианте страниц нет: каждый кадр — это его картинка, обрезанная как на странице, а за ней реплики, «Maya: Biscuit! Where's Grandpa?», с именами из comics.cast.

#2 · Встройте шрифты, которыми набраны страницы
// 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()) })));
}
EPUB с постоянной вёрсткой рисует текст шрифтами, которые несёт, а недостающий набирается шрифтом читающей программы. Леттерингу нужны прямой, полужирный и курсив; в комиксных шрифтах начертаний меньше, поэтому каждый запрос получает файл, выбранный для него loadComicFonts, а файл, который служит двум насыщенностям, кладётся один раз с диапазоном '400 700'. Японские и китайские шрифты берут только срезы со знаками своей версии, и японская книга весит 1,4 МБ.
#3 · Прочитайте каждый файл обратно
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 открывает байты как программа чтения: вид вёрстки, порядок листания, порядок документов. Список под каждой карточкой и есть просмотр по кадрам, прочитанный из regions.xhtml: пять кадров и их текстовые области в том порядке, в каком по ним идёт читатель. Три файла проходят EPUBCheck 5.4 без ошибок и предупреждений на английском, японском и арабском.
#4 · Одна вёрстка, десять версий
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'],
});
Каждый content.<lang>.md держит слова одной версии под теми же идентификаторами персонажей. Области кадров одинаковы на всех языках; области облачков сдвигаются вместе с облачками, которые заново строятся вокруг текста каждого языка.
Рецепт целиком
// ═══ 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 = 'en'; // @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'),
Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)
Варианты
#Обойдитесь без версии для Kindle
Навигация по областям записана в каждом постоянном EPUB; Kindle Panel View лишь дополняет её.
- kindle: await renderToEpub(doc, { ...book, layout: 'fixed', kindlePanelView: true }),#Дайте перетекаемой книге обложку
- reflowable: await renderToEpub(doc, { ...book, layout: 'reflowable' }),
+ reflowable: await renderToEpub(doc, { ...book, layout: 'reflowable',
+ cover: { bytes: imageBytes('lh-beam.jpg'), mediaType: 'image/jpeg' } }),Частые ошибки
- Шрифт, встроенный по разу на каждую насыщенность, копировался бы четыре раза; китайская версия весила 5,3 МБ, пока не появились диапазоны насыщенности.
Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- Оригинальный текст, CC BY 4.0
- Изображения
- Panel picture: Maya arrives at the lighthouse · Generated With Diffusion Models · оригинал
- Panel picture: Tomás at the radio · Generated With Diffusion Models · оригинал
- Panel picture: Maya finds the problem · Generated With Diffusion Models · оригинал
- Panel picture: Biscuit asleep on the cable · Generated With Diffusion Models · оригинал
- Panel picture: the lamp lit at night · Generated With Diffusion Models · оригинал
- Шрифты
- 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)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)


