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

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

ملف PDF حقيقي تُضمَّن فيه الخطوط نفسها

برنامج حفل موسيقي مُصدَّر إلى PDF. يُجلب كل خط مرة واحدة، لـ FontFace وللـ PDF، ويصير كل عنوان علامة مرجعية.

في هذه الصفحة
المُخرَج
Canvas · PDF
المستوى
متوسط
Postext
اختُبرت مع Postext 1.65.0
تتطلب ≥ 1.25.0 · postext-pdf ≥ 1.25.0
الترخيص
حُدّثت في 10 أكتوبر 2026
الشيفرة MIT · النص CC BY 4.0
  • نموذج باللغة الإنجليزية: لا توجد طبعة عربية بعد
  • مقاس القص 148 × 210 مم
  • عمود واحد
  • Crimson Text 10/13.3
  • Fraunces
  • Tenor Sans
  • 4 صفحات
  • المستوى
  • Postext 1.57.1
  • أُخرجت في 54 ms
  • أسطر الشيفرة: 180

باختصار

برنامج من أربع صفحات لحفل موسيقي مسائي. يبيّن كيف تحفظه ملف PDF يطابق الشاشة تمامًا، فيه خطوطه، وكل عنوان فيه مدرج للانتقال إليه بسرعة.

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

برنامج أمسية موسيقية عند الغسق، Home from Sea: أربع صفحات A5 لفرقة من سوبرانو وتشيلو وهارب. الغلاف أزرق مخضر ليلي، والعنوان بخط Fraunces المائل المذهّب، وصفوف من حراشف أمواج مذهّبة تصعد من أسفل الصفحة. في الداخل، ترتيب الفقرات الموسيقية جدول رأسه أزرق مخضر بحروف Tenor Sans الكبيرة، وصف مجموع ملوّن بلون خفيف. الملاحظات بخط Crimson Text مضبوطة. كلمات الأغاني الثلاث قصائد لـ Longfellow وStevenson وTennyson، منضّدة بإزاحات طبعاتها المطبوعة. يصنع الزر Build the PDF الملف الذي سترسله بالبريد إلى الجمهور أو تضعه على موقع القاعة. صفحاته الأربع تطابق الشاشة سطرًا بسطر. لا يضمّن إلا ملفات الخطوط الخمسة التي حمّلها المتصفح، وكل عنوان فيه علامة مرجعية. للطباعة التجارية، انظر وصفة ملف PDF الجاهز للطباعة.

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

  • كيف أصدّر ملف PDF حقيقيًّا في المتصفح مع تضمين الخطوط؟
  • لماذا تتغير مواضع كسر الأسطر عندي، أو تتداخل الكلمات في ملف PDF، وكيف أحمّل الخطوط تحميلًا صحيحًا؟

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

script.js · الأسطر 15–51في الشيفرة الكاملة
// Hook-up: `await registerFaces()` before the first build; `renderToPdf(doc, { fontProvider })`.
const files = new Map(); // 'crimson-text-latin-600-normal' → its WOFF2 (gotcha: latin-subset)
function fontFile(family, weight, style) {
  const id = family.toLowerCase().replaceAll(' ', '-'), file = `${id}-latin-${weight}-${style}`;
  if (!files.has(file)) {
    files.set(file, fetch(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${file}.woff2`)
      .then((res) => {
        if (!res.ok) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        return res.arrayBuffer();
      }));
  }
  return files.get(file);
}
const facesOf = (family) => (FONTS[family] ?? []).map((spec) =>
  ({ spec, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' }));

// The screen: a FontFace per face, from those bytes, before the first build.
const registerFaces = () => Promise.all(Object.keys(FONTS).flatMap((family) =>
  facesOf(family).map(async ({ weight, style }) => {
    const face = new FontFace(family, await fontFile(family, weight, style),
      { weight: `${weight}`, style });
    document.fonts.add(await face.load());
  })));

// The PDF: the same bytes as TrueType. renderToPdf asks for each face the pages paint and no
// other. A face FONTS lacks gets the closest one it has, and is logged as a stand-in: the
// status line should list none.
const embedded = new Set(), standIns = new Set(); // shown once the PDF is ready
async function fontProvider(family, weight, style) {
  if (!FONTS[family]) throw new Error(`${family} is not in FONTS: no page was set in it`);
  const cost = (f) => (f.style === style ? 0 : 1000) + Math.abs(f.weight - weight);
  const best = facesOf(family).reduce((a, b) => (cost(b) < cost(a) ? b : a));
  const asked = `${weight}${style === 'italic' ? 'i' : ''}`;
  embedded.add(`${family} ${best.spec}`);
  if (asked !== best.spec) standIns.add(`${family} ${asked} → ${best.spec}`);
  return decompressWoff2(new Uint8Array(await fontFile(family, best.weight, best.style)));
}

المكونات

الخطوط
Crimson Text, Fraunces, Tenor Sans (SIL OFL 1.1)
الأصول
  • The seigaiha waves on the cover, drawn in code in the page’s palette (Ignacio Ferro, CC BY 4.0)

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

#1 · تنزيل واحد لكل خط، للصفحة وللـ PDF

الشيفرة هي الجواب المختصر أعلاه. يقيس Postext كل كلمة بالخطوط التي حمّلها المتصفح لحظة البناء، ويرسم ملف PDF كل سطر حيث وضعه ذلك الإخراج. إذا ضمّن ملف PDF ملفًا مختلفًا، كالنسخة الافتراضية من خط متغيّر أو خط بديل من النظام، تبدأ كل كلمة مع ذلك في موضعها المقيس، لكن حروفها بعروض أخرى، فتتداخل الكلمات أو تترك فجوات. لذلك تجلب الوصفة كل خط مرة واحدة. تصير بايتاته FontFace قبل البناء الأول، ويمرّر مزوّد الخطوط البايتات نفسها عبر decompressWoff2 لملف PDF، فلا ينزّل التصدير أي خطوط خاصة به.

#2 · الخطوط أولًا، ثم الإخراج

script.js · الأسطر 363–367في الشيفرة الكاملة
await registerFaces(); // the answer: every face in FONTS, from its own bytes
await loadSvg('cover.svg', coverArt(PAGE.width, PAGE.height, WAVES));
// Every face is declared by now; one FONTS forgot would come from Fontsource, for the screen only.
const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
showPages(doc, { title: 'Home from Sea · a recital programme' });

لا تكتمل registerFaces() إلا حين يكتمل تحميل كل خط في FONTS، فيقيس البناء الأول بالخطوط التي سيضمّنها ملف PDF. وهو أيضًا البناء الوحيد، لأن FONTS يسرد كل خط تُنضَّد به الصفحات، فتجد buildDocumentWithFonts كل خط تبحث عنه معلَنًا من قبل (تحميل الخطوط قبل الإخراج). هذا الفحص لا ينفع إلا الشاشة. إذا فات FONTS خطٌّ، طلبه المحرّك من الأدوات المساعدة وحمّل ملف Fontsource وأعاد الإخراج من غير تحذير في وحدة التحكم، لكن ملف PDF يأخذ مع ذلك أقرب خط لدى المزوّد.

#3 · التصدير، وقائمة بما ضمّنه

script.js · الأسطر 371–386في الشيفرة الكاملة
const bar = Object.assign(document.createElement('progress'), { max: 1, value: 0 });
const list = (faces) => [...faces].join(', ') || 'none';
offerPdf(() => {
  document.getElementById('pt-actions').prepend(bar);
  return renderToPdf(doc, {
    fontProvider, // the answer: the page's own font files
    resourceBytes: imageBytes, // the cover drawing, as vector paths
    outlines: true, // the default, spelled out: each heading becomes a bookmark
    onProgress: ({ phase, pages, totalPages }) => {
      bar.value = pages / totalPages;
      const says = { prepare: 'fonts and cover embedded', pages: `page ${pages} of ${totalPages}`,
        save: `embedded: ${list(embedded)} · stand-ins: ${list(standIns)}` };
      kitStatus(`PDF · ${says[phase]}`);
    },
  });
}, `${RECIPE}.pdf`);

تستدعي renderToPdf الدالة onProgress على ثلاث مراحل: prepare بعد تضمين الخطوط والغلاف، وpages بعد كل صفحة، وsave قبل أن تكتب الملف. لا تطلب من المزوّد إلا الخطوط التي ترسمها الصفحات، وهي هنا خمسة. يسرد سطر الحالة الملفات الخمسة التي قدّمها المزوّد، وهي بالضبط ما في FONTS، بلا أي بديل. وظهور بديل يدل على خط ناقص من FONTS. إذا حذفت Crimson Text 600، يذكر السطر Crimson Text 600 → 400، وتُطبع The Harbour Consort العريضة في الصفحة 4 بالوزن العادي. معاينة CodePen لا تعرض ملفات PDF، لذلك تستبدل offerPdf من الأدوات المساعدة بالزر رابطين، أحدهما يفتح ملف PDF في تبويب جديد والآخر ينزّله (إنتاج ملفات PDF).

#4 · شجرة العناوين هي شجرة العلامات المرجعية

script.js · الأسطر 108–116في الشيفرة الكاملة
const headings = { fontFamily: 'Fraunces', fontWeight: 300, color: col('band'),
  marginTop: pt(0), marginBottom: pt(0), // a two-line H2 carries its own space above
  levels: [ // a section opens on the next page, left or right: a programme has no blank pages
    { level: 1, breakBefore: { enabled: true, parity: 'any' }, advancedDesign: opener },
    { level: 2, ...H2 },
  ] };
// The performers: a top-level bookmark, no break, no opener (gotcha: style-inherits-break).
const aside = { id: 'aside', breakBefore: { enabled: false }, advancedDesign: { enabled: false },
  ...H2, marginTop: pt(LEAD) };

في ملف PDF تعرض لوحة العلامات المرجعية عنوان الغلاف، وProgramme وتحته About the music، وThe texts مع أغانيه الثلاث، وThe performers. يتبع المخطط مستويات العناوين، فاخترها والعلامات المرجعية في ذهنك: هنا H1 لكل قسم وH2 لكل أغنية. لـ The performers نمط عنوان خاص به، H1 من غير فاصل صفحة ولا صفحة افتتاح، فيتقاسم الصفحة 4 مع قصيدة Tennyson ويحصل مع ذلك على علامة مرجعية في المستوى الأعلى. و\\ التي تكسر عنوان الغلاف إلى سطرين تصير مسافة في العلامة المرجعية.

#5 · العنوان والمؤلف من البيانات التمهيدية

script.js · الأسطر 80–93في الشيفرة الكاملة
const cover = {
  id: 'cover', span: 'page', header: { elements: [] }, footer: { elements: [] },
  advancedDesign: { enabled: true, slot: { elements: [
    { kind: 'image', id: 'night', resourceId: 'cover',
      placement: { anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill' } } },
    text('consort', '{author}', at('page', 'top', 18), label(8.5, 'gilt')),
    text('title', '{titleText}', at('page', 'top', 26, 120), // the \\ in the heading breaks it
      { ...title(68), lineHeight: 0.95, color: col('gilt') }),
    text('subtitle', '{subtitle}', at('page', 'top', 75, 66), { fontFamily: 'Crimson Text',
      italic: true, fontSize: pt(12.5), lineHeight: 1.25, color: col('foam') }),
    text('when', '{attr.when}', at('page', 'top', 91), label(LABEL, 'foam')),
    text('where', '{attr.where}', at('page', 'top', 96), label(LABEL, 'foam')),
  ] } },
};

يطبع الغلاف قيمتين من البيانات التمهيدية (frontmatter) عبر {author} و{subtitle}، وتأخذ خصائص مستند PDF العنوان Home from Sea والمؤلف The Harbour Consort من الكتلة نفسها. التاريخ والمكان سمتان لعنوان الغلاف. والرسم خلفهما ملف SVG واحد بعرض الصفحة، ويحتفظ به ملف PDF مسارات متجهية.

الوصفة كاملة

Sandbox
// ═══ Postext Cookbook · Nº 025 · A real PDF with the same fonts embedded ═══════════
// https://postext.dev/en/cookbook/pdf-with-embedded-fonts
// Code: MIT · Text: notes original (CC BY 4.0), poems in the public domain · Cover: drawn in code
// Fonts: Crimson Text, Fraunces, Tenor Sans (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} 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 = 'pdf-with-embedded-fonts';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region answer: one download per face: the layout measures it, the PDF embeds it
// Hook-up: `await registerFaces()` before the first build; `renderToPdf(doc, { fontProvider })`.
const files = new Map(); // 'crimson-text-latin-600-normal' → its WOFF2 (gotcha: latin-subset)
function fontFile(family, weight, style) {
  const id = family.toLowerCase().replaceAll(' ', '-'), file = `${id}-latin-${weight}-${style}`;
  if (!files.has(file)) {
    files.set(file, fetch(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${file}.woff2`)
      .then((res) => {
        if (!res.ok) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        return res.arrayBuffer();
      }));
  }
  return files.get(file);
}
const facesOf = (family) => (FONTS[family] ?? []).map((spec) =>
  ({ spec, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' }));

// The screen: a FontFace per face, from those bytes, before the first build.
const registerFaces = () => Promise.all(Object.keys(FONTS).flatMap((family) =>
  facesOf(family).map(async ({ weight, style }) => {
    const face = new FontFace(family, await fontFile(family, weight, style),
      { weight: `${weight}`, style });
    document.fonts.add(await face.load());
  })));

// The PDF: the same bytes as TrueType. renderToPdf asks for each face the pages paint and no
// other. A face FONTS lacks gets the closest one it has, and is logged as a stand-in: the
// status line should list none.
const embedded = new Set(), standIns = new Set(); // shown once the PDF is ready
async function fontProvider(family, weight, style) {
  if (!FONTS[family]) throw new Error(`${family} is not in FONTS: no page was set in it`);
  const cost = (f) => (f.style === style ? 0 : 1000) + Math.abs(f.weight - weight);
  const best = facesOf(family).reduce((a, b) => (cost(b) < cost(a) ? b : a));
  const asked = `${weight}${style === 'italic' ? 'i' : ''}`;
  embedded.add(`${family} ${best.spec}`);

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

تنويعات

#استغنِ عن العلامات المرجعية

نشرة من صفحة واحدة أو ملصق ليس فيهما ما يستحق علامة مرجعية. مع outlines: false لا يكون في ملف PDF مخطط، ويُفتح والشريط الجانبي مغلق.

-    outlines: true, // the default, spelled out: each heading becomes a bookmark
+    outlines: false,

#قدّم الخطوط من خادمك

وجّه الجلب إلى نسخك من ملفات WOFF2 الثابتة نفسها، ملف لكل وزن وأسلوب، بأسماء ملفات Fontsource. وتبقى الصفحة وملف PDF يتقاسمان كل تنزيل.

-    files.set(file, fetch(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/${file}.woff2`)
+    files.set(file, fetch(`/fonts/${file}.woff2`)
       .then((res) => {
-        if (!res.ok) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
+        if (!res.ok) throw new Error(`No font file ${file}.woff2`);

أخطاء شائعة

خطأ شائع

العريض أو المائل الذي لا تملكه العائلة يُصطنع على الشاشة، لا في PDF

حين يطلب النص وزنًا أو نمطًا لا توفّره عائلته (ترويسة جدول عريضة بخط تسميات ذي وجه واحد، أو مائل في خط غير مذيَّل بلا وجوه مائلة)، يصطنعه المتصفح في Canvas وفي HTML بتغليظ الوجه القائم أو إمالته على العروض نفسها. أما PDF فلا يضمّن إلا أوجهًا حقيقية، فيُطبع هناك أقرب وجه لدى المزوّد عاديًا. لا تضع في قائمة خطوطك إلا الأوجه التي توفّرها العائلة واضبط كل نمط ليطابقها، مثل tableStyle.headerBold: false. الخطوط المضمَّنة في PDF →

خطأ شائع

ملفات Fontsource تغطي الحروف لا الرموز

تضمّن العُدّة ملف latin من Fontsource لكل خط، ومعه ملف latin-ext للحروف č وł و†، وملف greek للحروف α وχ (في عائلة تضمه: لا يضمه Lora ولا Gelasio)، حين يستعملها النص، على الشاشة وفي PDF. أما رموز مثل → و≈ و✓ و★ فليست في أي من هذه الملفات فتغيب عن PDF: ارسمها، أو اكتبها رياضيات، أو اختر خطًا تضمها ملفاته. الخطوط المضمَّنة في PDF →

خطأ شائع

يرث نمط العنوان فاصل الصفحة من مستواه

يأخذ مُدخل headingStyles كل حقل يتركه من مستوى عنوانه، بما فيه breakBefore. فصفحة المحتويات أو صفحة بيانات النشر المنسّقة على H1 بعد :::pagebreak ترث الزوجية 'odd' وتقع بعد صفحة فارغة. أعطِ هذا النمط breakBefore: { enabled: false }. أنماط العناوين →

اسرد في FONTS كل خط تُنضَّد به صفحاتك، ومنها عريض النص ومائله. إذا نقص أحدها تبدو الشاشة سليمة، لأن الأدوات المساعدة تحمّل الخط من غير تحذير، لكن ملف PDF يطبع أقرب خط لدى المزوّد، ولا يكشف الاستبدال إلا البدائل في سطر الحالة.

استعمل ملفات ثابتة، ملفًا لكل وزن وأسلوب. من ملف WOFF2 متغيّر لا يضمّن ملف PDF إلا النسخة الافتراضية، فيُطبع المقطع العريض بالوزن العادي (لماذا مزوّد الخطوط؟).

الحقوق

الوصفة
Ignacio Ferro
النص
  • “The Tide Rises, the Tide Falls”, with its indents, as printed in The Complete Poetical Works of Henry Wadsworth Longfellow · Henry Wadsworth Longfellow · ملك عام
  • “Requiem”, with the indents and italics of the first edition of Underwoods (1887) · Robert Louis Stevenson · ملك عام
  • “Crossing the Bar”, with its indented short lines, from the first edition of Demeter and Other Poems (1889), in the proofread Wikisource transcription · Alfred Tennyson · ملك عام
  • The programme, the notes on the music, the performers and the colophon · Ignacio Ferro · CC BY 4.0
الصور
  • The seigaiha waves on the cover, drawn in code in the page’s palette · Ignacio Ferro · CC BY 4.0
الخطوط
Crimson Text (SIL OFL 1.1) · Fraunces (SIL OFL 1.1) · Tenor Sans (SIL OFL 1.1)
الشيفرة
MIT، مثل Postext
SandboxPDF