باختصار
مطوية بوجهين لطاحونة مدّ قديمة، بالإنجليزية والإسبانية. تبيّن كيف تحفظ مستندًا مع خطوطه وصوره في ملف واحد، ثم تستعيد الصفحات نفسها من ذلك الملف.
ما الذي ستنضده
وجها مطوية زيارة بقياس DL، أي 99 × 210 مم، لطاحونة مدّ على مصبّ نهر متخيَّل. الوجه الأمامي رسم واحد: عجلة طاحونة على خط الماء، نصفها الأعلى على الرمل ونصفها الأسفل شاحب تحت الماء الأزرق، والعنوان بخط DM Serif Display المائل بحجم 50 نقطة، ولسان أزرق يذكر الطبعة: EN أو ES. يبدأ الوجه الخلفي بمقطع عرضي للطاحونة، ثم النص بخط DM Sans مضبوطًا، ومواعيد الفتح في جدول برأس أزرق، والتعليقات بخط Instrument Sans، ثم بيانات الطبع وشريط أزرق باسم الناشر. تُكتب كل طبعة في ملف .postext، وكل صفحة هنا مُنضَّدة من بايتات ذلك الملف، بالخطوط والرسوم التي يتضمّنها.
تجيب هذه الوصفة عن
- كيف أفتح ملف .postext وأعرضه بخطوطه وصوره وإعداداته الخاصة؟
- كيف أنشئ حزمة .postext من الشيفرة، لأسلّم مستندًا إلى Sandbox أو إلى برنامج آخر؟
- كيف أنشر الكتاب نفسه بلغتين من مشروع واحد؟
- كيف أحصل على تسميتي «شكل» و«جدول» بلغة مستندي؟
الجواب المختصر
// The writer: text, design, resources and every file they name, zipped. createBundle looks
// up each fileId (a drawing's svg.fileId, a face's variant fileId) in `files`.
const { bytes, warnings } = await createBundle({
name: t({ en: 'The Tide Mill of Arenal', es: 'El molino de mareas de Arenal' }),
locale: LANG, // one language per file; `localized` would add the other edition to it
markdown, config: config(), resources,
files: { ...drawings, ...faceFiles },
thumbnail: { data: drawings['cover.svg'], mime: 'image/svg+xml' }, // the book's picture
});
if (warnings.length) console.warn(warnings); // what was left out, and why
// The reader has nothing but the bytes. Each fileId is now the file's path inside the zip:
// mill.svg is resources/mill.svg, and the faces sit under fonts/.
const bundle = await openBundle(bytes);
await loadBundleFonts(bundle); // one FontFace per face from the file, in place of loadFonts()
await registerBundleImages(bundle); // the drawings, for the canvas
const docs = buildBundle(bundle); // one VDTDocument per chapter: a leaflet has one
المكونات
- الميزات
- حزم .postext«شكل» و«جدول» بلغتكخطوطك الخاصةتقسيم الكلمات ولغة المستندتعليقات مرقّمةاستشهادات تضع الأشكالأشكال في هذا الموضع بالضبطمسافة عمودية صريحةكتب تُبنى فصلًا فصلًاالأغلفة وصفحات العنوان وبيانات النشرأنماط العناوينسمات العنوانصفحات افتتاح مصمَّمةالنصوص والخطوط والمربعات في تصاميم الصفحةالصور في تصاميم الصفحةالبيانات الوصفية للمستندنمط التعليقنمط الجدولالتصدير إلى PDFالخطوط المضمَّنة في PDF
- تستخدم أيضًا
- شريط فصل بعرض الصفحةفواصل الصفحات والأعمدةالترويسات بحسب دور الصفحةأنماط الفقراتأنواع موارد مخصّصة
- الخطوط
- DM Sans, DM Serif Display, Instrument Sans (SIL OFL 1.1)
- الأصول
- لا شيء: كل صورة مرسومة بالشيفرة
طريقة التحضير
#1 · اكتب الطبعة، ثم اقرأ البايتات وحدها
// The writer: text, design, resources and every file they name, zipped. createBundle looks
// up each fileId (a drawing's svg.fileId, a face's variant fileId) in `files`.
const { bytes, warnings } = await createBundle({
name: t({ en: 'The Tide Mill of Arenal', es: 'El molino de mareas de Arenal' }),
locale: LANG, // one language per file; `localized` would add the other edition to it
markdown, config: config(), resources,
files: { ...drawings, ...faceFiles },
thumbnail: { data: drawings['cover.svg'], mime: 'image/svg+xml' }, // the book's picture
});
if (warnings.length) console.warn(warnings); // what was left out, and why
// The reader has nothing but the bytes. Each fileId is now the file's path inside the zip:
// mill.svg is resources/mill.svg, and the faces sit under fonts/.
const bundle = await openBundle(bytes);
await loadBundleFonts(bundle); // one FontFace per face from the file, in place of loadFonts()
await registerBundleImages(bundle); // the drawings, for the canvas
const docs = buildBundle(bundle); // one VDTDocument per chapter: a leaflet has one
تضغط createBundle في ملف zip الفصلَ والإعدادات والموارد وكل ملف تذكره؛ ولا تتلقى openBundle سوى تلك البايتات. الخطوط تأتي من loadBundleFonts، والرسوم من registerBundleImages، والتصميم من bundle.config. الخط الذي لا يرد في files يُطبع بخط المتصفح الاحتياطي، والرسم الذي يغيب يُسقَط مع تحذير وتُطبع الإحالة إليه (?). داخل الملف المضغوط يصير كل fileId مسارًا (mill.svg صار resources/mill.svg)، والموارد وcustomFonts التي تعيدها openBundle تستعمل الأسماء الجديدة من الأصل (فتح حزمة).
#2 · ضع الخطوط في الملف
const customFonts = Object.entries(FONTS).map(([name, specs]) => ({ name,
variants: specs.map((spec) => ({ weight: parseInt(spec, 10), format: 'woff2',
style: spec.endsWith('i') ? 'italic' : 'normal', fileId: `${fontsourceId(name)}-${spec}` })),
}));
// The bytes: Fontsource's static woff2 files, latin subset, which covers the Spanish text too.
const faceFiles = Object.fromEntries(await Promise.all(customFonts.flatMap(({ name, variants }) =>
variants.map(async ({ weight, style, fileId }) => {
const id = fontsourceId(name);
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 ${name} ${weight} ${style}`);
return [fileId, new Uint8Array(await res.arrayBuffer())];
}))));
تتضمّن الحزمة خطًّا حين تذكره customFonts وتحفظ files بايتاته تحت fileId الخاص بذلك الوزن أو النمط؛ فتخزّن createBundle خط DM Sans بوزن 400 باسم fonts/dm-sans-400-normal.woff2. ينزّل المثال ملفات woff2 السبعة من Fontsource ولا يسجّل أيًّا منها: تضيف loadBundleFonts نسخ الحزمة إلى document.fonts قبل أن تقيس buildBundle أي سطر، ويأخذ ملف PDF خطوطه من الملفات السبعة نفسها.
#3 · سمِّ كل ملف بـfileId الخاص به
const svg = (id, w, h, altText, extra) => ({ id, typeId: 'figure', kind: 'svg', createdAt: 0,
updatedAt: 0, altText, svg: { fileId: `${id}.svg`, width: w * 10, height: h * 10 }, ...extra });
const row = (...cells) => cells.map((content) => ({ content }));
const head = (...cells) => cells.map((content) => ({ content, isHeader: true }));
const resources = [
svg('cover', PAGE.w, PAGE.h, t({ en: 'A mill wheel on the waterline, its lower half pale '
+ 'under the estuary', es: 'Una rueda de molino en la línea del agua, con la mitad '
+ 'inferior pálida bajo la ría' })),
svg('mill', SECTION.w, SECTION.h, t({
en: 'The mill in section: the pond at high level on the left, the mill house on the dam '
+ 'with its millstones, the horizontal wheel in the vaulted pit, and the estuary on the '
+ 'right below a dashed high-water line',
es: 'El molino en sección: el estanque a nivel alto a la izquierda, la casa del molino sobre '
+ 'la presa con sus muelas, el rodezno en el cárcavo abovedado y la ría a la derecha, bajo '
+ 'una línea discontinua de pleamar' }), {
placement: { position: 'here' },
caption: t({ en: 'Two hours after high water: the pond turns the wheel, and the estuary '
+ 'has fallen below the dashed line.',
es: 'Dos horas tras la pleamar: el estanque mueve el rodezno y la ría ha quedado por debajo '
+ 'de la línea discontinua.' }) }),
{ id: 'hours', typeId: 'table', kind: 'table', createdAt: 0, updatedAt: 0,
placement: { position: 'here' },
caption: t({ en: 'Opening hours. Last entry 45 minutes before closing.',
es: 'Horario. Última entrada 45 minutos antes del cierre.' }),
table: { model: { headerRowCount: 1, columnWidths: [1.55, 0.9, 1.55], rows: t({
en: [head('Season', 'Days', 'Hours'),
row('April–June', 'Tue–Sun', '10:00–14:00, 16:00–19:00'),
row('July–August', 'Mon–Sun', '10:00–20:00'),
row('September–March', 'Fri–Sun', '10:30–14:30')],
es: [head('Temporada', 'Días', 'Horario'),
row('Abril–junio', 'Mar.–dom.', '10:00–14:00 y 16:00–19:00'),
row('Julio–agosto', 'Lun.–dom.', '10:00–20:00'),
row('Septiembre–marzo', 'Vie.–dom.', '10:30–14:30')] }) } } },
];
الرسمان شيفرة SVG يولّدها المثال، وتُسلَّم إلى files تحت svg.fileId الخاص بمورد كل منهما؛ أما الجدول فبيانات، فينتقل في preset.json مع تعليقه. يُنضَّد المقطع العرضي والجدول بالإعداد position: 'here': المقطع في رأس الوجه الخلفي، والمواعيد تحت الفقرة التي تحيل إليها. تضبط المطوية layout.inlineResourceGap: 'above'، فيبقى فراغ المورد المضمَّن في النص فوقه فقط ويتّسع الوجه الخلفي في صفحة واحدة: العنوان الذي يلي المقطع يأتي بفراغه، وسطر :::space{lines=0.5} بعد الجدول يترك 3.7 مم تحت تعليقه.
#4 · أبقِ التسميات بلغة الملف
// Hyphenation patterns and the PDF's /Lang.
locale: t({ en: 'en-us', es: 'es' }),
// '{n}' numbers the figures 1, 2, 3: a leaflet has no chapters to number them by. Without
// resourceTypes the reader builds Figure 1.1 or Figura 1.1, in the language of the file.
resourceTypes: defaultResourceTypes(LANG).map((type) => ({ ...type, numberingTemplate: '{n}' })),
من يفتح الملف يبني الأنواع المضمَّنة باللغة التي يقدّمها ذلك الملف: فمن دون resourceTypes في الإعدادات تطبع المطوية الإسبانية Figura 1.1 وTabla 1.1 أينما فُتحت، وفي Sandbox على /en/sandbox أيضًا. والمطوية تكتب الأنواع من أجل أرقامها فقط: يُسقط '{n}' رقم الفصل، وهو رقم لا تحتاجه مطوية من صفحتين (أنواع الموارد). والدالة config() نفسها تضبط locale، فتختار أنماط تقسيم الكلمات الإسبانية بالواصلة (compuer-tas في الوجه الخلفي) واللغة التي يعلنها ملف PDF.
#5 · سلّم البايتات نفسها
const file = `tide-mill-${LANG}.postext`;
document.getElementById('pt-actions').append(Object.assign(document.createElement('a'), {
href: URL.createObjectURL(new Blob([bytes], { type: 'application/zip' })), download: file,
textContent: `Download ${file} · ${Math.round(bytes.length / 1024)} KB` }));
// The PDF embeds the faces the bundle carries, and draws the figures from its files.
offerPdf(() => renderToPdf(docs, {
fontProvider: bundleFontProvider(bundle, { decodeWoff2: decompressWoff2 }),
resourceBytes: bundleResourceBytes(bundle),
}), `${RECIPE}-${LANG}.pdf`);
يقدّم الرابط bytes التي نُضّدت منها الصفحات، 132 كيلوبايت مع الخطوط. وإذا استُورد الملف في Sandbox (الكتب › جديد › افتح ملف .postext…) صار كتابًا إسبانيًا أو إنجليزيًا صورته العجلة، مأخوذة من thumbnail. يأخذ ملف PDF خطوطه من bundleFontProvider، الذي يعيد أقرب خط في الحزمة وزنًا، وبالنمط نفسه إن وُجد، ورسومَه من bundleResourceBytes، فلا يُنزَّل أي خط أو صورة مرة ثانية (تنضيد حزمة وإخراجها).
#6 · ارسم الوجه الأمامي بعنوان واحد
const at = (x, y, width, edge = 'top-left') => ({ anchor: { to: 'page', edge },
offset: { x: mm(x), y: mm(y) }, size: { width: mm(width) } });
const text = (id, content, family, size, placement, look) => ({ kind: 'text', id, content,
fontFamily: family, fontSize: pt(size), color: col('estuary'), placement, ...look });
const caps = { fontFamily: LABEL, fontWeight: 700, textTransform: 'uppercase',
letterSpacing: pt(1.15) };
const [MEASURE, EDGE] = [PAGE.w - 2 * PAGE.side, 17]; // mm; EDGE: trim to kicker and facts
const cover = { id: 'cover', advancedDesign: { enabled: true, slot: { elements: [
{ kind: 'image', id: 'art', resourceId: 'cover', placement: { anchor: { to: 'page',
edge: 'top-left' }, size: { width: mm(PAGE.w), height: mm(PAGE.h) } } },
text('kicker', '{attr.kicker}', LABEL, 7.5, at(PAGE.side, EDGE, MEASURE), caps),
// The language tab: the edition's code on a blue flap hanging from the top edge.
text('edition', '{attr.edition}', LABEL, 8, { anchor: { to: 'page', edge: 'top-right' },
offset: { x: mm(-PAGE.side) } }, { ...caps, color: col('foam'), box: {
backgroundColor: col('estuary'), padding: { top: mm(8), right: mm(2.4), bottom: mm(2.2),
left: mm(2.4) } } }),
text('title', '{titleText}', DISPLAY, 50, at(PAGE.side - 0.8, 25, MEASURE + 2),
{ italic: true, lineHeight: 0.96 }), // 48 pt from line to line
text('lead', '{attr.lead}', TEXT, 11, at(PAGE.side + 2, WATER + 50, MEASURE - 4),
{ color: col('foam'), italic: true, lineHeight: 1.4 }),
text('facts', '{attr.facts}', LABEL, 7.5, at(PAGE.side, -EDGE, MEASURE, 'bottom-left'),
{ ...caps, color: col('sand') }),
] } } };
الوجه الأمامي هو تصميم عنوان الغلاف: الرسم مربوط بالصفحة بحجمه الكامل، ونص العنوان عبر {titleText}، والعنوان التمهيدي والمقدمة وسطر المعلومات من سماته، وعنصر نصي داخل إطار للسان اللغة. مستوى H1 مضبوط على span: 'page'، فيمتدّ الرسم إلى الحافة السفلى للورق. أما تصميم العنوان الذي يبقى داخل العمود فيُقصّ عند أسفل كتلة النص: كان الرسم سيتوقف قبل الحافة السفلى بـ13 مم.
الوصفة كاملة
// ═══ Postext Cookbook · Nº 041 · .postext round trip in two languages ════════════
// https://postext.dev/en/cookbook/bundle-round-trip
// Code: MIT · Text: original (CC BY 4.0) · Drawings: generated in code (CC BY 4.0)
// Fonts: DM Sans, DM Serif Display, Instrument Sans (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import { createBundle, openBundle, loadBundleFonts, registerBundleImages, buildBundle,
bundleFontProvider, bundleResourceBytes, defaultResourceTypes, renderPageToCanvas }
from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'bundle-round-trip';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { ink: '#172130', muted: '#56606c', // text; the colophon
estuary: '#25476a', mud: '#8a6f4d', // the one accent; the wheel's wood in the drawings
sand: '#e9dcc4', foam: '#eef2f3', rule: '#c4ced6', paper: '#ffffff' };
// Each colour carries its hex and the palette entry it follows.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// The engine's defaults link to 'main-color': point it at the estuary blue.
const colorPalette = Object.entries({ ...palette, 'main-color': palette.estuary })
.map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [TEXT, DISPLAY, LABEL] = ['DM Sans', 'DM Serif Display', 'Instrument Sans'];
const PAGE = { w: 99, h: 210, top: 12, bottom: 13, side: 10 }; // mm: a DL leaflet, both sides
const [BODY, LEAD] = [9.4, 13.4]; // pt
const WATER = 98; // mm from the top of the cover: where the sand ends and the estuary begins
// #region cover: the front of the leaflet, a heading drawn over one picture
const at = (x, y, width, edge = 'top-left') => ({ anchor: { to: 'page', edge },
offset: { x: mm(x), y: mm(y) }, size: { width: mm(width) } });
const text = (id, content, family, size, placement, look) => ({ kind: 'text', id, content,
fontFamily: family, fontSize: pt(size), color: col('estuary'), placement, ...look });
const caps = { fontFamily: LABEL, fontWeight: 700, textTransform: 'uppercase',
letterSpacing: pt(1.15) };
const [MEASURE, EDGE] = [PAGE.w - 2 * PAGE.side, 17]; // mm; EDGE: trim to kicker and facts
const cover = { id: 'cover', advancedDesign: { enabled: true, slot: { elements: [
{ kind: 'image', id: 'art', resourceId: 'cover', placement: { anchor: { to: 'page',
edge: 'top-left' }, size: { width: mm(PAGE.w), height: mm(PAGE.h) } } },
text('kicker', '{attr.kicker}', LABEL, 7.5, at(PAGE.side, EDGE, MEASURE), caps),
// The language tab: the edition's code on a blue flap hanging from the top edge.
text('edition', '{attr.edition}', LABEL, 8, { anchor: { to: 'page', edge: 'top-right' },
offset: { x: mm(-PAGE.side) } }, { ...caps, color: col('foam'), box: {
backgroundColor: col('estuary'), padding: { top: mm(8), right: mm(2.4), bottom: mm(2.2),
left: mm(2.4) } } }),
text('title', '{titleText}', DISPLAY, 50, at(PAGE.side - 0.8, 25, MEASURE + 2),
{ italic: true, lineHeight: 0.96 }), // 48 pt from line to line
text('lead', '{attr.lead}', TEXT, 11, at(PAGE.side + 2, WATER + 50, MEASURE - 4),
{ color: col('foam'), italic: true, lineHeight: 1.4 }),
text('facts', '{attr.facts}', LABEL, 7.5, at(PAGE.side, -EDGE, MEASURE, 'bottom-left'),
يعمل ملف script.js المجمّع كما هو: الصقه في سكربت الوحدة (module) لأي صفحة، أو افتح الوصفة على CodePen. مجلد الوصفة على GitHub ↗ (يفتح في تبويب جديد)
تنويعات
#اقرأ حزمة ثنائية اللغة
يضمّ دليل Postext فصوله وإعداداته وتعليقاته الإنجليزية والإسبانية في ملف واحد؛ ويختار { locale } الطبعة، فتُفتح في اثني عشر فصلًا على 48 صفحة بأي من اللغتين، بينما يظل الرابط يقدّم ملف المطوية ويبني زر PDF الدليل.
-const bundle = await openBundle(bytes);
+const guide = await fetch('https://postext.dev/bundles/postext-guide.postext');
+const bundle = await openBundle(await guide.arrayBuffer(), { locale: LANG });#رقّم الأشكال بحسب الفصل
من دون الأنواع يبنيها من يفتح الملف بلغة الملف وبالترقيم الافتراضي، وتبدأ الأشكال العدّ من عنوان الغلاف: تطبع الطبعة الإسبانية Figura 1.1 وTabla 1.1، والإنجليزية Figure 1.1 وTable 1.1.
- resourceTypes: defaultResourceTypes(LANG).map((type) => ({ ...type, numberingTemplate: '{n}' })),أخطاء شائعة
- كل طبعة هنا ملف قائم بذاته. ولحمل اللغتين في ملف واحد، مرّر إلى
createBundleخريطةlocalized(الحزم ثنائية اللغة)؛ وعندها تقرأopenBundle(bytes, { locale })أيًّا من الطبعتين.
الحقوق
- الوصفة
- Ignacio Ferro
- النص
- نص أصلي, CC BY 4.0
- الخطوط
- DM Sans (SIL OFL 1.1) · DM Serif Display (SIL OFL 1.1) · Instrument Sans (SIL OFL 1.1)
- الشيفرة
- MIT، مثل Postext
حرّر هذا الشرح ↗ (يفتح في تبويب جديد)مجلد الوصفة على GitHub ↗ (يفتح في تبويب جديد)


