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

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

من نص Markdown إلى صفحة مصمّمة

نص Markdown ببيانات تمهيدية يُنضَّد صفحات مجلة بعمودين ويُرسم على Canvas، بستة ألوان مسمّاة بدل الأزرق الافتراضي.

في هذه الصفحة
المُخرَج
Canvas
المستوى
متوسط
Postext
اختُبرت مع Postext 1.65.0
تتطلب ≥ 1.34.0
الترخيص
حُدّثت في 16 أكتوبر 2026
الشيفرة MIT · النص CC BY 4.0
  • نموذج باللغة الإنجليزية: لا توجد طبعة عربية بعد
  • مقاس القص 180 × 240 مم
  • عمودان, فاصل 6 مم بين الأعمدة
  • Newsreader 9.5/13.5
  • Inter Tight
  • Young Serif
  • صفحتان
  • المستوى
  • Postext 1.57.1
  • أُخرجت في 86 ms
  • أسطر الشيفرة: 176

باختصار

أول صفحتين من مقالة رحلات في مجلة صغيرة، بشريط ملوّن وصورة. تبيّن كيف يصير نص عادي فيه بضعة عناوين صفحة مصمّمة بألوانك أنت.

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

الصفحات الأولى من تحقيق عن السفر في Field Notes، وهي مجلة صغيرة. الصفحة 1 صفحة افتتاح فردية: صورة لملّاحات وكثيب عند الغسق تغطي 58% من الصفحة من أعلاها، والعنوان بخط Young Serif بحجم 54 نقطة، وتحته عمودان مضبوطان يبدأ بهما النص بمدخل عريض. وتستمر الصفحة 2، على ظهر الورقة، تحت ترويسة بحروف كبيرة متباعدة، وتنتهي بعلامة نهاية وبيانات طبع. يحدد التصميمَ مصنعُ إعدادات واحد ولوحة من ستة ألوان. ويأتي العنوان من عنوان المستوى الأول، وتأتي المقدمة والكاتب والتاريخ من البيانات التمهيدية لنص Markdown، فينضّد المثال نفسه أي مقالة يتسع عنوانها لسطرين؛ ولا يخص هذه المقالة إلا الصورة.

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

  • كيف أمنع العناوين والكلمات العريضة والنقاط من الظهور باللون الأزرق؟
  • كيف أضبط صفحة كتاب: مقاس القطع، وهوامش داخلية وخارجية متناظرة، وعمودين وفاصلًا بينهما؟
  • كيف أحوّل نص Markdown إلى صفحات منضَّدة وأرسم إحداها على لوحة Canvas؟

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

script.js · الأسطر 125–164في الشيفرة الكاملة
const config = () => ({
  locale: t({ en: 'en-us', es: 'es', pt: 'pt', fr: 'fr', de: 'de', it: 'it' }), // the hyphenation
  colorPalette: colorPalette(),
  page: { // mirror: left is the inner margin and right the outer one; versos swap them
    width: mm(PAGE.width), height: mm(PAGE.height),
    margins: { top: mm(MARGIN.top), bottom: mm(MARGIN.bottom), left: mm(MARGIN.inner),
      right: mm(MARGIN.outer), mirror: true },
  },
  // 'double' is the default, stated so that the whole page setup reads in one place
  layout: { layoutType: 'double', gutterWidth: mm(6) },
  bodyText: { // justified, hyphenated and broken by paragraph: all on by default
    fontFamily: 'Newsreader', // one family name: there is no fallback chain
    fontSize: pt(9.5), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    firstLineIndent: mm(4), indentAfterHeading: false,
    // Optional, for 70 mm columns: word spaces from 0.8 to 1.8 × the normal one, and runts
    // tightened by at most 4 thousandths of an em, so the grey of the text stays even.
    minWordSpacing: 0.8, maxWordSpacing: 1.8, maxRuntTracking: 4,
  },
  headings: {
    fontFamily: 'Young Serif', fontWeight: 400, color: col('band'), // it has one weight
    levels: [
      // span: 'page' opens the H1 on a new page, across both columns. Parity 'odd' puts the
      // next article pasted in on a recto, with a blank verso only when one is needed.
      { level: 1, span: 'page', breakBefore: { enabled: true, parity: 'odd' },
        advancedDesign: opener() },
      // A line of margin and a line and a half of head: 2.5 lines, which snapToGrid (on by
      // default) rounds up to 3, so the text below lands back on the grid.
      { level: 2, fontSize: pt(13), lineHeight: pt(1.5 * LEAD), marginTop: pt(LEAD),
        marginBottom: pt(0) },
    ],
  },
  unorderedLists: { color: col('ink'), fontWeight: 400, bulletChar: '–',
    marginTop: pt(0), marginBottom: pt(0) },
  calloutStyles: [colophon()],
  header: header(),
  footer: footer(),
  // The magazine's name is its masthead, the same on every story (#849).
  checks: { contentInConfig: { allow: [MAGAZINE] } },
});

المكونات

الخطوط
Newsreader, Young Serif, Inter Tight (SIL OFL 1.1)
الأصول
  • salt-road-1440.jpg
  • The salt pans and the dune at dusk on the opener, a photograph (Generated With Diffusion Models, أصلي)

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

#1 · كل الوجوه، قبل أول بناء

script.js · الأسطر 224–228في الشيفرة الكاملة
const FONTS = {
  Newsreader: ['400', '400i', '700'], // text
  'Young Serif': ['400'], // display: it ships one weight, so the headings ask for 400
  'Inter Tight': ['400', '600'], // labels: kicker, byline, running heads, colophon
};

يقيس Postext النص بالخطوط الموجودة في المتصفح لحظة الإخراج، فالبناء الذي يسبق وصول الخطوط يحتفظ بفواصل أسطر الخط الاحتياطي. يحمّل buildDocumentWithFonts قبل أول بناء كل شكل خط تذكره الإعدادات وكل شكل في FONTS؛ وتزوّده kitFonts(FONTS) بالملفات من Fontsource، وهي الملفات نفسها التي سيضمّنها ملف PDF. ثم يستعرض أشكال الخط التي تستعملها الصفحات، فيحمّل ما ينقص منها ويعيد البناء. وشكل الخط الذي لا يوفّره Fontsource يبقى بالخط الاحتياطي ويَرِد في doc.contentWarnings باسم fontFallback. أما العريض والمائل من خط النص فلا يُحمَّلان إلا إن كانت العائلة تملكهما.

#2 · سمِّ الألوان ثم أشِر إلى الأسماء

script.js · الأسطر 23–41في الشيفرة الكاملة
const palette = {
  ink: '#1b1e23', // text: a cool near-black, never #000
  band: '#2b3a67', // the one accent (an indigo): the folios, the subheads, the end mark
  sand: '#e9dcc0', // the kicker, the title and the byline
  salt: '#f7f4ee', // the standfirst
  rule: '#d6d3cc', // the hairline over the colophon
  muted: '#66686e', // running heads and the colophon
};
// Each colour carries its palette id and its hex. The design objects below are functions
// that config() calls, so col() copies the hex out of `palette` on every build: one edit
// to `palette` reaches the text, the folios and the drop folio alike.
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' } })),
  // The engine's defaults (headings, bold, italic, bullets, the default running head) link
  // to 'main-color': point it at the accent, so nothing left unset prints blue.
  { id: 'main-color', name: 'defaults', value: { hex: palette.band, model: 'hex' } },
];

كل لون في الإعدادات هو col('id')، أي معرّف من لوحة الألوان وبجانبه قيمته السداسية عشرية. تشير bodyText.boldColor وitalicColor وreferenceColor وunorderedLists.color إلى اللون ink، وتشير headings.color إلى لون التمييز. وقيم المحرّك الافتراضية للعناوين والعريض والمائل والنقاط مرتبطة بـmain-color، وهذه اللوحة توجّه ذلك المدخل إلى لون التمييز، فأي منها تتركه يخرج نيليًّا بدل الأزرق. وكائنات التصميم دوالّ يستدعيها config() في كل بناء، وينسخ col() القيمة الحالية من palette في كل مرة، فيصل تعديل واحد في palette إلى النص وأرقام الصفحات وصفحة الافتتاح معًا. وعلامة النهاية عيّنة لون داخل السطر تشير إلى band، فيصلها تغيير اللون هي أيضًا. والترويسة الافتراضية مرتبطة بـmain-color هي أيضًا، فتخرج بلون التمييز حتى تستبدلها (الخطوة 5).

#3 · صورة مقصوصة على إطارها

script.js · الأسطر 45–51في الشيفرة الكاملة
// A JPEG in assets/, cut to PAGE.width × BAND (180 × 140 mm) and declared at its pixels, so at
// full width it fills the band exactly. A deeper band needs a picture cut to the new frame.
const landscape = { id: 'landscape', typeId: 'figure', kind: 'bitmap', createdAt: 0,
  updatedAt: 0, bitmap: { fileId: 'salt-road-1440.jpg', format: 'jpeg', width: 1440,
    height: 1120 },
  altText: 'Salt pans at dusk, a dune with a cairn of white stones on its crest, and a line of '
    + 'footprints crossing the pans towards it.' };

الملّاحات والكثيب وركام الحجارة صورة مولّدة بنماذج الانتشار (diffusion models)، ملتقطة عند الغسق ليُقرأ العنوان الفاتح على سماء داكنة. وملف JPEG مقصوص على إطار الشريط، PAGE.width × BAND مليمترًا، ويعلن المورد أبعاده بالبكسل، 1440 × 1120، فتملأ الصورة بعرضها الكامل الشريطَ تمامًا. والشريط الأعمق يحتاج إلى صورة مقصوصة على الإطار الجديد. وتعرضها صفحة الافتتاح عبر عنصر صورة يحدّد المورد بمعرّفه.

#4 · البيانات التمهيدية تكتب صفحة الافتتاح

script.js · الأسطر 55–91في الشيفرة الكاملة
const BAND = 140; // mm from the top edge: the band holds the top 58% of the page
const TITLE_W = 130; // mm: room for two lines of the title; a third would push the byline
// down onto the pale salt pans: keep titles short
const DECK_W = 104; // mm: the standfirst stops short of the dune and its cairn
const MAGAZINE = t({ en: 'Field notes', es: 'Cuaderno de campo', pt: 'Caderno de campo',
  fr: 'Carnet de terrain', de: 'Unterwegs', it: 'Quaderno di campo' });
const label = { fontFamily: 'Inter Tight', fontSize: pt(7.5), fontWeight: 600,
  letterSpacing: pt(1.4), textTransform: 'uppercase' };
const below = (id, y, width) => ({ anchor: { to: `#${id}`, edge: 'below' },
  offset: { y: mm(y) }, ...(width && { size: { width: mm(width) } }) });
const opener = () => ({
  enabled: true,
  minHeight: mm(BAND - MARGIN.top + 5), // from the top margin to the band's foot, plus 5 mm
  slot: {
    elements: [
      // The photograph is PAGE.width × BAND (see art): at full width it fills the band.
      { kind: 'image', id: 'art', resourceId: 'landscape',
        placement: { anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill' } } },
      { kind: 'text', id: 'kicker', content: MAGAZINE, ...label, color: col('sand'),
        placement: { anchor: { to: 'page', edge: 'top-left' }, // recto: inner on the left
          offset: { x: mm(MARGIN.inner), y: mm(20) } } },
      // {titleText} is the H1; {subtitle}, {author} and {publishDate} are frontmatter. A bare
      // lineHeight multiplies the text's size: 1 sets the title solid. Both texts wrap.
      { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Young Serif',
        fontSize: pt(54), lineHeight: 1, color: col('sand'), align: 'left',
        placement: below('kicker', 3, TITLE_W) },
      { kind: 'text', id: 'deck', content: '{subtitle}', fontFamily: 'Newsreader',
        fontSize: pt(12), lineHeight: 1.3, italic: true, color: col('salt'), align: 'left',
        placement: below('title', 5, DECK_W) },
      { kind: 'text', id: 'byline', ...label, color: col('sand'),
        content: t({ en: 'By {author} · {publishDate}',
          es: 'Por {author} · {publishDate}', pt: 'Por {author} · {publishDate}',
          fr: 'Par {author} · {publishDate}', de: 'Von {author} · {publishDate}', it: 'Di {author} · {publishDate}' }),
        placement: below('deck', 4.5) },
    ],
  },
});

يمتد عنوان المستوى الأول على العمودين، وصفحة افتتاحه خانة من العناصر: الصورة حتى منطقة النزف، وأربعة نصوص متسلسلة واحدًا تحت الآخر. فالعنوان الأطول يدفع المقدمة واسم الكاتب إلى الأسفل بدل أن يتراكب عليهما، لكن إذا تجاوز سطرين وقع اسم الكاتب على الملّاحات الفاتحة. {titleText} هو نص العنوان؛ و{subtitle} و{author} و{publishDate} حقول من البيانات التمهيدية. وتكسر \\ في العنوان السطر حيث تضعها (فواصل الأسطر في العناوين). ويُحسب minHeight من الهامش العلوي، فينتهي الارتفاع المحجوز على بعد 5 مم تحت الشريط.

#5 · ترويسات بدل الأزرق الافتراضي

script.js · الأسطر 95–114في الشيفرة الكاملة
const HEAD = 12; // mm: the running heads from the top edge, the drop folio from the foot
const GAP = 3; // mm between a folio and its label, however many digits the folio has
const head = (id, content, parity, placement, color = col('muted')) => ({
  kind: 'text', id, content, parity, pages: 'body', ...label, color, placement,
});
const outer = (edge, x) => ({ anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(HEAD) } });
const beside = (id, edge, x) => ({ anchor: { to: `#${id}`, edge }, offset: { x: mm(x) } });
const header = () => ({
  elements: [ // folios on the outer margin's edge; each label hangs off its folio
    head('verso-folio', '{pageNumber}', 'even', outer('top-left', MARGIN.outer), col('band')),
    head('verso-title', '{title}', 'even', beside('verso-folio', 'right-of', GAP)),
    head('recto-folio', '{pageNumber}', 'odd', outer('top-right', -MARGIN.outer), col('band')),
    head('recto-title', MAGAZINE, 'odd', beside('recto-folio', 'left-of', -GAP)),
  ],
});
const footer = () => ({
  elements: [{ kind: 'text', id: 'drop-folio', content: '{pageNumber}', pages: 'opener',
    ...label, color: col('band'),
    placement: { anchor: { to: 'page', edge: 'bottom' }, offset: { y: mm(-HEAD) } } }],
});

إذا تركت header عاد الافتراضي الخاص بالمحرّك: Open Sans فوق خط بعرض الصفحة، في كل صفحة. وهنا كل رقم صفحة مربوط بالصفحة الفعلية ومُرشَّح بحسب الزوجية، فيقع دائمًا عند الحافة الخارجية. وتسميته مربوطة برقم الصفحة، على بعد GAP مليمترًا مع right-of أو left-of، فرقم الصفحة ذو الثلاثة أو الأربعة أرقام يدفع التسمية أمامه بدل أن يصطدم بها. ويُبعد pages: 'body' العناصر الأربعة عن صفحة الافتتاح. وفي التذييل رقم صفحة واحد في أسفل صفحة الافتتاح، ولأن footer محدَّد، تفقد صفحات المتن رقم الصفحة الموسَّط الافتراضي.

#6 · ابنِ بإعدادات جديدة ثم ارسم

script.js · الأسطر 233–243في الشيفرة الكاملة
await loadImage(landscape.bitmap.fileId, asset(landscape.bitmap.fileId));
const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
// showPages paints each page with renderPageToCanvas(page, doc, canvas, { scale }).
showPages(doc, {
  title: t({ en: 'From a Markdown string to a designed page',
    es: 'De una cadena Markdown a una página diseñada',
    pt: 'De uma string Markdown a uma página diagramada',
    fr: 'D’une chaîne Markdown à une page mise en forme',
    de: 'Von einem Markdown-String zur gestalteten Seite',
    it: 'Da una stringa Markdown a una pagina progettata' }),
});

config() دالة كي يقرأ كل بناء لوحة الألوان كما هي في حينه: فهي تستدعي من جديد دوالّ التصميم في الخطوة 2. ويصلح أيضًا كائن إعدادات واحد يُعدَّل في مكانه: فمنذ postext 1.25 يرى المحرّك التغيير في البناء التالي. ويأخذ buildDocumentWithFonts المحتوى وهذه الإعدادات وخيارات الخطوط من العُدّة، ويعيد المستند. ويرتّب showPages الصفحات كما تقع في كتاب مجلّد، الصفحة 1 وحدها على اليمين، ويرسم كلًّا منها بـrenderPageToCanvas.

الوصفة كاملة

Sandbox
// ═══ Postext Cookbook · Nº 012 · From a Markdown string to a designed page ══════════
// https://postext.dev/en/cookbook/first-page-from-markdown
// Code: MIT · Text: original (CC BY 4.0) · Photo: diffusion models
// Fonts: Newsreader, Young Serif, Inter Tight (SIL OFL 1.1) · Needs postext ≥ 1.34.0
//
// This pen sets a Markdown string with a frontmatter block on two magazine pages and paints
// them on canvases. The whole design is in config(); swap config() for {} in the build
// below to see the engine's defaults.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the sample document's language ('en' | 'es' | 'pt' | 'fr' | 'de' | 'it')
const RECIPE = 'first-page-from-markdown';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// Every setting that shapes the pages is in this part, from PAGE down to config().
const PAGE = { width: 180, height: 240 }; // mm: a 3:4 magazine page
const MARGIN = { top: 22, bottom: 22, inner: 20, outer: 14 }; // mm; inner is the spine side
const LEAD = 13.5; // pt: the body leading, the grid every vertical space steps on

// #region palette: six named colours; every colour in the config links to one of them
const palette = {
  ink: '#1b1e23', // text: a cool near-black, never #000
  band: '#2b3a67', // the one accent (an indigo): the folios, the subheads, the end mark
  sand: '#e9dcc0', // the kicker, the title and the byline
  salt: '#f7f4ee', // the standfirst
  rule: '#d6d3cc', // the hairline over the colophon
  muted: '#66686e', // running heads and the colophon
};
// Each colour carries its palette id and its hex. The design objects below are functions
// that config() calls, so col() copies the hex out of `palette` on every build: one edit
// to `palette` reaches the text, the folios and the drop folio alike.
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' } })),
  // The engine's defaults (headings, bold, italic, bullets, the default running head) link
  // to 'main-color': point it at the accent, so nothing left unset prints blue.
  { id: 'main-color', name: 'defaults', value: { hex: palette.band, model: 'hex' } },
];
// #endregion

// #region art: a photograph of the salt pans and the dunes at Sorra, cut for a page × band frame
// A JPEG in assets/, cut to PAGE.width × BAND (180 × 140 mm) and declared at its pixels, so at
// full width it fills the band exactly. A deeper band needs a picture cut to the new frame.
const landscape = { id: 'landscape', typeId: 'figure', kind: 'bitmap', createdAt: 0,
  updatedAt: 0, bitmap: { fileId: 'salt-road-1440.jpg', format: 'jpeg', width: 1440,

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

تنويعات

#انظر ما الذي تستبدله الإعدادات

ابنِ بإعدادات فارغة فيخرج نص Markdown نفسه على صفحة بمقاس 17 × 24 سم بخط EB Garamond بحجم 8 نقاط، بعناوين Open Sans زرقاء وترويسة زرقاء فوق خط؛ ويحمّل المحرّك هاتين العائلتين أيضًا لأن الإعدادات الافتراضية تذكرهما.

-const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
+const doc = await buildDocumentWithFonts({ markdown, resources }, {}, kitFonts(FONTS));

#أعِد تلوين الصفحة كلها

غيّر لون التمييز فيرسم التشغيل التالي أرقام الصفحات والعناوين الفرعية وعلامة النهاية باللون الجديد، لأن col() ينسخ القيمة الجديدة بجانب المعرّف في كل مرة يجري فيها config(). وتحتفظ الصورة بألوانها.

-  band: '#2b3a67', // the one accent (an indigo): the folios, the subheads, the end mark
+  band: '#3f5b3a', // the one accent (a pine green): the folios, the subheads, the end mark

#ارسم صفحة واحدة على Canvas خاص بك

يضبط renderPageToCanvas حجم عنصر Canvas على حجم الصفحة بالبكسل بدقة المستند (300 نقطة في البوصة افتراضيًا) مضروبة في scale، فيرسم scale: 0.5 بدقة 150 نقطة في البوصة تقريبًا، وتحدد CSS حجمه الظاهر على الشاشة.

-showPages(doc, {
-  title: t({ en: 'From a Markdown string to a designed page',
-    es: 'De una cadena Markdown a una página diseñada',
-    pt: 'De uma string Markdown a uma página diagramada',
-    fr: 'D’une chaîne Markdown à une page mise en forme',
-    de: 'Von einem Markdown-String zur gestalteten Seite',
-    it: 'Da una stringa Markdown a una pagina progettata' }),
-});
+const canvas = document.body.appendChild(document.createElement('canvas'));
+renderPageToCanvas(doc.pages[0], doc, canvas, { scale: 0.5 });

أخطاء شائعة

  • لا يأتي Young Serif إلا بوزن واحد. والعناوين عريضة افتراضيًا، فلا بد هنا من headings.fontWeight: 400: بدونه تطلب العناوين Young Serif عريضًا لا يملكه Fontsource، فيثخّن المتصفح الوزن العادي، ويسجّل doc.contentWarnings الخط بوصفه fontFallback.

الحقوق

الوصفة
Ignacio Ferro
النص
نص أصلي, CC BY 4.0
الصور
  • The salt pans and the dune at dusk on the opener, a photograph · Generated With Diffusion Models · أصلي
الخطوط
Newsreader (SIL OFL 1.1) · Young Serif (SIL OFL 1.1) · Inter Tight (SIL OFL 1.1)
الشيفرة
MIT، مثل Postext
Sandbox