انتقل إلى المحتوى الرئيسي
الوصفة رقم 115

دليل الوصفات · الفصل 10 · الإخراج والدمج

كتاب واحد وملفا EPUB 3: تخطيط ثابت وقابل لإعادة التدفق

تكتب renderToEpub من postext-epub الفصول التي أخرجتها buildBundle ملفَّ EPUB بتخطيط ثابت وآخر قابلًا لإعادة التدفق، وتسرد readEpub ما يحويه كل ملف.

في هذه الصفحة
المُخرَج
Canvas · EPUB
المستوى
متقدم
Postext
اختُبرت مع Postext 1.65.0
تتطلب ≥ 1.65.0
الترخيص
حُدّثت في 31 أكتوبر 2026
الشيفرة MIT · النص MIT
  • نموذج باللغة الإنجليزية: لا توجد طبعة عربية بعد
  • مقاس القص 120 × 190 مم
  • عمود واحد
  • Libre Caslon Text 9.6/13.5
  • Jost
  • Libre Caslon Display
  • 14 صفحة
  • المستوى
  • Postext 1.65.0
  • أُخرجت في 137 ms
  • أسطر الشيفرة: 178

باختصار

كتاب صغير من الحكايات يُخرَج للطباعة مرة واحدة ويُحفظ كتابين إلكترونيين: واحد يحتفظ بكل صفحة مطبوعة، وآخر يعيد الهاتف أو القارئ الإلكتروني تنضيد نصه بالحجم الذي يناسبه.

ما الذي ستنضده

Fables of Aesop (حكايات إيسوب)، ثماني عشرة حكاية في ثلاثة كتب على صفحة بقياس 120 × 190 mm، مع صفحة عنوان وبيانات الطبع على ظهرها وصفحة افتتاح غائرة لكل كتاب. وتنضّد الطبعة الإسبانية قصة ¡Adiós, Cordera! لكلارين (Clarín) في ثلاثة فصول على الصفحة نفسها. يُخرَج الكتاب مرة واحدة، فصلًا فصلًا، ويصير ذلك الإخراج ملفي EPUB 3. يحتفظ التخطيط الثابت بكل صفحة مطبوعة: صفحات الافتتاح والترويسات ومواضع انتهاء الأسطر، بخط Caslon المضمَّن. ويحتفظ الملف القابل لإعادة التدفق بالنص وبنيته، ويعيد نظام القراءة تنضيده على الهاتف أو على شاشة حبر إلكتروني. يُنزَّل الملفان كلاهما من الصفحة، ويجتاز كلاهما فحص EPUBCheck من W3C.

تجيب هذه الوصفة عن

  • كيف أصدّر كتابي بصيغة EPUB، بصفحات ثابتة أو بنص متدفق؟

الجواب المختصر

script.js · الأسطر 256–270في الشيفرة الكاملة
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' });

المكونات

الخطوط
Libre Caslon Text, Libre Caslon Display, Jost (SIL OFL 1.1)
الأصول
لا شيء: كل صورة مرسومة بالشيفرة

طريقة التحضير

#1 · أخرِج الكتاب فصولًا

script.js · الأسطر 42–61في الشيفرة الكاملة
// 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 كل فصل مستندًا قائمًا بذاته، وتنقل أرقام الصفحات وزوجيتها من فصل إلى الذي يليه، فتكون docs هي المصفوفة نفسها التي تطبعها renderToPdf. ويقرأ كاتب EPUB هذه المصفوفة: يصير كل فصل مدخلًا في قائمة التنقل، ويكتب الملف القابل لإعادة التدفق مستند XHTML واحدًا لكل فصل. صفحة العنوان وبيانات الطبع على ظهرها هما الفصل الأول، وبياناته التمهيدية (frontmatter) هي عنوان الكتاب وعنوانه الفرعي ومؤلفه.

#2 · سلّم الكاتب ملفات الخطوط

script.js · الأسطر 235–246في الشيفرة الكاملة
// 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 };
  })));

الخطوط التي حمّلها المتصفح ليست ملفات يستطيع الكاتب قراءتها، لذلك يجلب المثال ملفات woff2 نفسها من Fontsource مرة أخرى، والمتصفح يحتفظ بها في ذاكرته المؤقتة. يصير كل ملف منها ملف خط داخل EPUB وقاعدة @font-face. ومن دونها يضع التخطيط الثابت النص المنضَّد بخط Caslon بالخط الذي يختاره القارئ الإلكتروني، فلا تعود الأسطر مطابقة للعرض الذي حُسبت عليه.

#3 · اكتب النسختين

الشيفرة هي الجواب المختصر أعلاه. يكتب layout: 'fixed' مستند XHTML واحدًا لكل صفحة مطبوعة بقياس الصفحة بعد القص، بنص حقيقي قابل للتحديد؛ ويعيد layout: 'reflowable' بناء الفقرات من الأسطر المُخرَجة، ويحذف الواصلات التي أضافها تقسيم الأسطر، ويستخرج ورقة أنماط من الإعدادات. ويجعل تاريخ modified الثابت كل تشغيل يُنتج البايتات نفسها. تأتي البيانات الوصفية من البيانات التمهيدية للفصل الأول، فيكون عنوان الملف ومؤلفه هما المطبوعين على صفحة العنوان.

#4 · اقرأ كل ملف من جديد

script.js · الأسطر 274–296في الشيفرة الكاملة
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 الملف كما يفتحه نظام القراءة: العمود الفقري (spine) بترتيب القراءة، والمحتويات، وقائمة الصفحات، والتخطيط. للملف الثابت مدخل واحد في العمود الفقري لكل صفحة، وللملف القابل لإعادة التدفق أربعة مداخل، واحد لكل فصل. وفي كليهما قائمة صفحات بأرقام الصفحات المطبوعة، فيستطيع القارئ أن يتبع استشهادًا إلى الصفحة 9 في أي منهما. يحدّد الرابط <a download> اسم ملف للبايتات، ولا يمر شيء عبر خادم.

الوصفة كاملة

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

يعمل ملف script.js المجمّع كما هو: الصقه في سكربت الوحدة (module) لأي صفحة، أو افتح الوصفة على CodePen. مجلد الوصفة على GitHub ↗ (يفتح في تبويب جديد)

تنويعات

#أعطِ التخطيط الثابت صورة غلاف

ارسم صفحة العنوان على لوحة (canvas) ومرّرها غلافًا؛ ويخبر showsFirstPage الكاتبَ ألا يضيفها صفحةً مستقلة.

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

#اطبع الفصول نفسها ملف PDF

تأخذ renderToPdf(docs, …) من postext-pdf المصفوفة نفسها، فيأتي ملف PDF وملف EPUB والشاشة من إخراج واحد. وتُظهر الرواية الكتالونية في قطع الجيب جانب PDF.

أخطاء شائعة

خطأ شائع

لا تضمّن renderToEpub إلا الخطوط التي تمرّرها إليها

الخطوط التي حمّلها المتصفح ليست ملفات تستطيع postext-epub قراءتها: مرّر في options.fonts بايتات كل خط تستخدمه الصفحات (ملفات woff2 نفسها من Fontsource التي حمّلتها الصفحة). يُبلَّغ عن الخط الناقص بتحذير missingFont، ويُنضّد نظام القراءة ذلك النص بخط من عنده، وهو في التخطيط الثابت لا يتسع للأسطر التي نُضّدت بها الصفحة. لا تضمّن إلا الخطوط التي تسمح رخصتها بذلك. التصدير إلى EPUB →

يحتفظ الملف القابل لإعادة التدفق بنص العنوان لا بتصميمه: العنوان التمهيدي في كل صفحة افتتاح (Book I) عنصر من عناصر التصميم، فلا يدخل في النص. ضع الكلمات التي يجب أن يراها القارئ في العنوان نفسه أو في النص.

الحقوق

الوصفة
Ignacio Ferro
النص
  • 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 · ملك عام
  • ¡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 · ملك عام
الخطوط
Libre Caslon Text (SIL OFL 1.1) · Libre Caslon Display (SIL OFL 1.1) · Jost (SIL OFL 1.1)
الشيفرة
MIT، مثل Postext
Sandbox