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

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

خطوط العلامة في الإخراج وملف PDF والحزمة

دليل هوية لمترو متخيَّل منضَّد بملفات خطوط العلامة نفسها، تُنزَّل مرة واحدة ويعيد استخدامها الإخراج ومزوّد خطوط PDF وحزمة .postext.

في هذه الصفحة
المُخرَج
Canvas · PDF · حزمة .postext
المستوى
متقدم
Postext
اختُبرت مع Postext 1.65.0
تتطلب ≥ 1.25.0 · postext-pdf ≥ 1.25.0
الترخيص
حُدّثت في 10 أكتوبر 2026
الشيفرة MIT · النص CC BY 4.0
  • نموذج باللغة الإنجليزية: لا توجد طبعة عربية بعد
  • مقاس القص 210 × 280 مم
  • عمودان, فاصل 8 مم بين الأعمدة
  • Public Sans 9.8/14
  • Big Shoulders Display
  • Spline Sans Mono
  • 4 صفحات
  • المستوى
  • Postext 1.57.1
  • أُخرجت في 76 ms
  • أسطر الشيفرة: 246

باختصار

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

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

أربع صفحات من دليل هوية Metro de Alba، مترو متخيَّل من خمسة خطوط. على الغلاف تخرج الخطوط الخمسة من أسفل اليسار على مسار مشترك واحد، ثم تتفرّع نحو اليمين بعد عبور نهر رمادي، تحت الاسم المنضَّد بخط Big Shoulders Display. يبدأ كل قسم تحت شريط بلون الحبر، مع رقم كبير من خانتين بلون أحد الخطوط. في 01 Colour يكون العمود الأول من الجدول هو اللون نفسه؛ وفي 02 Type أسطر عيّنة ولافتة رصيف، ويُختم 03 Usage برسمين مؤطَّرين للخريطة، أحدهما مرسوم وفق القواعد (Do) والآخر مخالف لها (Don't). النص كله منضَّد بستة ملفات خطوط ينزّلها السكربت قبل أول إخراج. يُرسم ملف PDF بالملفات الستة نفسها، ويتضمّن ملف .postext خمسة منها، لأن خط العناوين موسوم بأنه غير قابل لإعادة التوزيع.

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

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

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

script.js · الأسطر 16–53في الشيفرة الكاملة
// Your licensed files, one per face in FONTS. Fontsource's copies stand in for them here:
// point FONT_URL at your own server (same origin, or one that lets this page in by CORS).
const slug = (family) => family.toLowerCase().replaceAll(' ', '-');
const FONT_URL = ({ family, weight, style }) => `https://cdn.jsdelivr.net/npm/@fontsource/`
  + `${slug(family)}@5/files/${slug(family)}-latin-${weight}-${style}.woff2`;
const brandFaces = () => Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) => {
  const weight = parseInt(spec, 10), style = spec.endsWith('i') ? 'italic' : 'normal';
  return { family, weight, style, fileId: `${slug(family)}-${weight}-${style}.woff2` };
}));
const fontFiles = new Map(); // fileId → the WOFF2 bytes, fetched once

// 1 · Layout measures with document.fonts: register every face before the first build.
async function loadBrandFonts() {
  await Promise.all(brandFaces().map(async ({ family, weight, style, fileId }) => {
    const res = await fetch(FONT_URL({ family, weight, style }));
    if (!res.ok) throw new Error(`No file for ${family} ${weight} ${style}`);
    fontFiles.set(fileId, new Uint8Array(await res.arrayBuffer()));
    const face = new FontFace(family, fontFiles.get(fileId), { weight: `${weight}`, style });
    document.fonts.add(await face.load());
  }));
}

// 2 · The PDF embeds the same bytes as TrueType. renderToPdf asks for the faces the pages
// paint; a weight or slant the brand lacks gets the family's closest file, embedded once.
async function brandFontProvider(family, weight, style) {
  const cost = (f) => (f.style === style ? 0 : 1000) + Math.abs(f.weight - weight);
  const own = brandFaces().filter((f) => f.family === family);
  if (!own.length) throw new Error(`${family} is not one of the brand's fonts`);
  return decompressWoff2(fontFiles.get(own.reduce((a, b) => (cost(b) < cost(a) ? b : a)).fileId));
}

// 3 · The bundle: customFonts names each face's file by its fileId; createBundle packs the bytes
// of every family it may hand on. Layout never reads it (gotcha: custom-fonts-declarative).
const customFonts = () => Object.keys(FONTS).map((name) => ({
  name, redistributable: name !== DISPLAY, // the display face reaches suppliers another way
  variants: brandFaces().filter((f) => f.family === name)
    .map(({ weight, style, fileId }) => ({ weight, style, fileId, format: 'woff2' })),
}));

المكونات

الخطوط
Public Sans, Big Shoulders Display, Spline Sans Mono (SIL OFL 1.1)
الأصول
  • The network drawing on the cover and the two map examples, drawn in code (Ignacio Ferro, CC BY 4.0)

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

#1 · سجّل محارف العلامة، وابنِ المستند، وأعطِ ملف PDF البايتات نفسها

script.js · الأسطر 448–453في الشيفرة الكاملة
await loadBrandFonts(); // the answer, step 1
for (const [fileId, markup] of Object.entries(ART)) await loadSvg(fileId, markup);
const doc = buildDocument({ markdown, resources }, config());
showPages(doc, { title: 'Metro de Alba · Identity manual' });
offerPdf(() => renderToPdf(doc, { fontProvider: brandFontProvider, resourceBytes: imageBytes }),
  `${RECIPE}.pdf`); // step 2: the provider hands renderToPdf the same files

يقيس الإخراج كل كلمة بالمحارف الموجودة في document.fonts، لذلك تنزّل loadBrandFonts() في الجواب المختصر كل ملف مرة واحدة، وتحتفظ ببايتاته، وتسجّل FontFace مبنيًّا منها قبل تشغيل buildDocument. الدالة kitFonts في عُدّة الوصفات لا تنزّل إلا من Fontsource، أما العلامة فتقدّم ملفاتها من خادمها الخاص. تطلب renderToPdf المحارف التي ترسمها الصفحات، وتجيب brandFontProvider عن كل طلب بالبايتات التي نُزّلت من قبل؛ وإذا طُلب وزن أو مائل لا تملكه العلامة أعادت أقرب ملف من العائلة نفسها (لماذا مزوّد خطوط؟). يضمّن ملف PDF الملفات الستة التي قاس بها Canvas، كلًّا منها مرة واحدة.

#2 · نظام الألوان قائمة واحدة

script.js · الأسطر 59–84في الشيفرة الكاملة
const COLOURS = [ // id, name, screen, print (coated stock)
  ['line-1', 'Line 1 · Tile red', '#e4572e', '0 75 85 0'],
  ['line-2', 'Line 2 · Harbour teal', '#17bebb', '75 0 32 0'],
  ['line-3', 'Line 3 · Broom yellow', '#ffc914', '0 22 95 0'],
  ['line-4', 'Line 4 · Heather', '#6c4f9e', '65 75 0 0'],
  ['line-5', 'Line 5 · Pine', '#3f9b4a', '76 12 90 2'],
  ['signal-red', 'Signal red', '#c0391b', '10 88 100 2'],
  ['signal-green', 'Signal green', '#2b7d3c', '84 25 95 10'],
  ['ink', 'Ink', '#1f2124', '72 62 55 78'],
  ['rule', 'Rule grey', '#d9d9d4', '14 10 14 0'],
];
const palette = { ...Object.fromEntries(COLOURS.map(([id, , hex]) => [id, hex])),
  paper: '#ffffff', section: '#e4572e' }; // section: the line colour of the current section
// col(): a colour linked to its palette entry, with the entry's hex beside the link.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [...Object.entries(palette), ['main-color', palette.ink]]
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));

const rgb = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)).join(' ');
const swatchTable = () => COLOURS.reduce( // an empty first cell, filled with the colour itself
  (model, [id], i) => setCellBackground(model, { row: i + 1, col: 0 }, col(id)),
  { headerRowCount: 1, columnWidths: [22, 34, 14, 15, 15], rows: [
    ['COLOUR', 'NAME', 'HEX', 'RGB', 'CMYK'].map((content) => ({ content, isHeader: true })),
    ...COLOURS.map(([, name, hex, cmyk]) =>
      ['', name, hex.toUpperCase(), rgb(hex), cmyk].map((content) => ({ content }))),
  ] });

لأن لوحة الألوان والجدول 1.1 مبنيّان من الصفوف التسعة نفسها، لا يمكن للجدول أن يذكر قيمة لا تستعملها الصفحات. تملأ setCellBackground الخلية الأولى الفارغة في كل صف بلون ذلك الصف، مربوطًا بلوحة الألوان. وفي النص تأخذ :swatch{color="line-2"} معرّفًا من لوحة الألوان وترسم مربعًا محاطًا بلون النص. قيمة main-color هي قيمة hex للون Ink، فتُطبع العناوين والمقاطع العريضة والمائلة، المربوطة به افتراضيًا، بلون Ink بدل الأزرق الافتراضي للمحرّك. والإعداد bodyText.referenceColor: col('ink') يجعل Ink لون الإحالات أيضًا (لوحة الألوان).

#3 · صفحة افتتاح واحدة بثلاثة ألوان للخطوط

script.js · الأسطر 93–110في الشيفرة الكاملة
// The body starts ten grid lines down, in both columns.
const opener = { enabled: true, minHeight: pt(10 * LEAD), slot: { elements: [
  { kind: 'text', id: 'number', content: '{number}', fontFamily: DISPLAY, fontWeight: 800,
    fontSize: pt(130), lineHeight: 1, color: col('section'), align: 'left', overflow: 'wrap',
    // Nudged by eye on the capture: the cap tops of number and title on one line.
    placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { x: mm(-1.5), y: mm(1.3) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY, fontWeight: 800,
    fontSize: pt(34), lineHeight: 1, color: col('ink'), align: 'left', overflow: 'wrap',
    placement: { anchor: { to: 'container', edge: 'top-left' },
      offset: { x: mm(COL + GUTTER), y: mm(1) }, size: { width: mm(COL) } } },
  { kind: 'text', id: 'lead', content: '{attr.lead}', fontFamily: TEXT, fontSize: pt(12.5),
    lineHeight: 1.36, color: col('ink'), align: 'left', overflow: 'wrap',
    placement: { anchor: { to: '#title', edge: 'below' }, offset: { y: mm(3) },
      size: { width: mm(COL) } } },
] } };
// Each section sets `section` to its line's colour; the number and the head square use it.
const section = (id) => ({ id, palette: { section: palette[id] } });

يكتب numberingTemplate: '{1:01}' العدّاد بخانتين، ويطبع {number} الأرقام 01 و02 و03 في صفحة الافتتاح؛ أما عنوان الغلاف فهو numbered: false ولا يأخذ رقمًا. لا تختلف أنماط الأقسام الثلاثة إلا في مدخل لوحة الألوان section، الذي يضبطه كل نمط على لون خطه. الرقم والمربع في الشريط مربوطان بالمدخل section، فيخدم تصميم واحد لصفحة الافتتاح الأقسام الثلاثة. يحجز minHeight عشرة أسطر من شبكة 14 pt لصفحة الافتتاح، فيبدأ نص كل قسم على خط الشبكة نفسه في صفحته.

#4 · Do وDon't نوعان من الأشكال

script.js · الأسطر 159–164في الشيفرة الكاملة
const example = (id, name, colour) => ({ id, name, shortLabel: name, captionPrefix: name,
  numberingTemplate: '{n}', resetOn: 'never', counterFormat: 'decimal',
  captionStyle: { labelColor: col(colour) } });
const resourceTypes = [...defaultResourceTypes(LANG),
  example('do', 'Do', 'signal-green'), example('dont', 'Don’t', 'signal-red')];
const FOOT = { position: 'bottom' }; // cited in one paragraph: its page's foot, one per column

يمكن أن يتضمّن نوع المورد captionStyle جزئيًا، وهذان النوعان لا يضبطان إلا لون التسمية: أخضر Signal للرسم Do وأحمر Signal للرسم Don't (أنواع الموارد). يبلغ تباين لوني الإشارة 5.1:1 و5.5:1 على الأبيض، بينما تبقى الخطوط 1 و2 و3 و5 دون نسبة 4.5:1 التي يحتاجها النص الصغير. يطفو الرسمان كلاهما بالإعداد position: 'bottom' ويُستشهد بهما في الفقرة نفسها، الأولى تحت Drawing the map، فيتقاسمان أسفل الصفحة 4: Do في العمود الأيسر وDon't في العمود الأيمن.

#5 · تحزم الحزمة الخطوط التي يحق لها توزيعها

script.js · الأسطر 457–471في الشيفرة الكاملة
const pack = Object.assign(document.createElement('button'), { type: 'button',
  textContent: 'Build the .postext' });
pack.addEventListener('click', async () => {
  const { bytes, manifest, warnings } = await createBundle({
    name: 'Metro de Alba identity manual', locale: LANG, markdown, config: config(), resources,
    files: new Map([...Object.entries(ART), ...fontFiles]), // fileId → SVG markup or font bytes
  });
  const size = `${Math.round(bytes.length / 1024)} KB`;
  const packed = `fonts inside: ${manifest.fonts.map((font) => font.name).join(', ')}`;
  kitStatus(['.postext', size, packed, ...warnings].join(' · ')); // warnings: what stayed out
  pack.replaceWith(Object.assign(document.createElement('a'), { download: `${RECIPE}.postext`,
    href: URL.createObjectURL(new Blob([bytes], { type: 'application/zip' })),
    textContent: `Download ${RECIPE}.postext · ${size}` }));
});
document.getElementById('pt-actions').append(pack);

تقرأ createBundle الإعداد config.customFonts، وتبحث عن بايتات كل نسخة من الخط في files بحسب fileId، وتكتبها تحت fonts/ مع مدخل fonts في البيان. في عائلة العناوين redistributable: false، نيابةً عن ترخيص يمنع تسليم الملفات للغير (خط Big Shoulders Display نفسه مرخّص بترخيص OFL). يبقى ملفها خارج الحزمة، وتذكر warnings اسم العائلة. يضم الملف، وحجمه 81 KB، الفصل والإعدادات والرسوم الثلاثة وخمسة ملفات خطوط. لا يقرأ الإخراج customFonts أبدًا؛ فالصفحات تخرج كما هي من دونه (إنشاء حزمة).

الوصفة كاملة

Sandbox
// ═══ Postext Cookbook · Nº 040 · Brand fonts in layout, PDF and bundle ════════════
// https://postext.dev/en/cookbook/brand-fonts-identity-manual
// Code: MIT · Text and drawings: original (CC BY 4.0) · Metro de Alba is a fictional network
// Fonts: Public Sans, Big Shoulders Display, Spline Sans Mono (OFL 1.1) · Needs postext ≥ 1.25.0
import {
  buildDocument, renderPageToCanvas, registerResourceImage, defaultResourceTypes, setCellBackground,
  createBundle,
} 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 = 'brand-fonts-identity-manual';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region answer: the brand's font files, fetched once for the layout, the PDF and the bundle
// Your licensed files, one per face in FONTS. Fontsource's copies stand in for them here:
// point FONT_URL at your own server (same origin, or one that lets this page in by CORS).
const slug = (family) => family.toLowerCase().replaceAll(' ', '-');
const FONT_URL = ({ family, weight, style }) => `https://cdn.jsdelivr.net/npm/@fontsource/`
  + `${slug(family)}@5/files/${slug(family)}-latin-${weight}-${style}.woff2`;
const brandFaces = () => Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) => {
  const weight = parseInt(spec, 10), style = spec.endsWith('i') ? 'italic' : 'normal';
  return { family, weight, style, fileId: `${slug(family)}-${weight}-${style}.woff2` };
}));
const fontFiles = new Map(); // fileId → the WOFF2 bytes, fetched once

// 1 · Layout measures with document.fonts: register every face before the first build.
async function loadBrandFonts() {
  await Promise.all(brandFaces().map(async ({ family, weight, style, fileId }) => {
    const res = await fetch(FONT_URL({ family, weight, style }));
    if (!res.ok) throw new Error(`No file for ${family} ${weight} ${style}`);
    fontFiles.set(fileId, new Uint8Array(await res.arrayBuffer()));
    const face = new FontFace(family, fontFiles.get(fileId), { weight: `${weight}`, style });
    document.fonts.add(await face.load());
  }));
}

// 2 · The PDF embeds the same bytes as TrueType. renderToPdf asks for the faces the pages
// paint; a weight or slant the brand lacks gets the family's closest file, embedded once.
async function brandFontProvider(family, weight, style) {
  const cost = (f) => (f.style === style ? 0 : 1000) + Math.abs(f.weight - weight);
  const own = brandFaces().filter((f) => f.family === family);
  if (!own.length) throw new Error(`${family} is not one of the brand's fonts`);
  return decompressWoff2(fontFiles.get(own.reduce((a, b) => (cost(b) < cost(a) ? b : a)).fileId));
}

// 3 · The bundle: customFonts names each face's file by its fileId; createBundle packs the bytes
// of every family it may hand on. Layout never reads it (gotcha: custom-fonts-declarative).

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

تنويعات

#احزم خط العناوين أيضًا

إذا كان الترخيص يسمح لك بتسليم الملفات للغير، فاحذف العلامة، وستتضمّن الحزمة العائلات الثلاث في 96 KB.

-  name, redistributable: name !== DISPLAY, // the display face reaches suppliers another way
+  name,

#استعمل وزنًا عريضًا حقيقيًا

يضع boldFontWeight: 600 المقاطع العريضة ورؤوس الجداول وتسميات التعليقات بوزن SemiBold، لأن العلامة لا تملك وزن Bold؛ فإن كان لعائلتك وزن Bold فأضف ملفاته إلى FONTS، واحذف الإعداد، وأعد كتابة سطر العيّنة في المثال وعبارته «There is no Bold» التي لن تبقى صحيحة.

-    boldFontWeight: 600, // the brand has no Bold: its SemiBold sets **emphasis**
-  'Public Sans': ['400', '400i', '600', '600i'],
+  'Public Sans': ['400', '400i', '600', '600i', '700', '700i'],

أخطاء شائعة

خطأ شائع

customFonts لا يحمّل أي خط

لا يفعل config.customFonts إلا أن يسمّي ملفات الخطوط بمعرّف fileId: لا يقرؤه buildDocument ولا مُخرِجات Canvas وHTML وPDF، فالعائلة المذكورة فيه وغير المسجّلة تُقاس وتُرسَم بخط بديل. سجّل كل وجه بنفسك (FontFace من بايتاته) قبل البناء الأول، وأعطِ البايتات نفسها لمزوّد خطوط PDF. يقرأ createBundle القائمة ليحزم الملفات في ملف .postext، ويقرؤها Sandbox ليسجّل الأوجه. خطوطك الخاصة →

خطأ شائع

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

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

خطأ شائع

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

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

مرّر إلى createBundle بايتات كل خط تحت fileId الذي تحدّده له customFonts. النسخة التي لا بايتات لها تُستبعد مع تحذير «missing file, skipped»، والعائلة التي تفقد كل نسخها تسقط من البيان.

الحقوق

الوصفة
Ignacio Ferro
النص
  • The Metro de Alba identity manual, a fictional network · Ignacio Ferro · CC BY 4.0
الصور
  • The network drawing on the cover and the two map examples, drawn in code · Ignacio Ferro · CC BY 4.0
الخطوط
Public Sans (SIL OFL 1.1) · Big Shoulders Display (SIL OFL 1.1) · Spline Sans Mono (SIL OFL 1.1)
الشيفرة
MIT، مثل Postext
SandboxPDF