# حبر خامس للون المؤسسي

> الألوان الأساسية الأربعة ومعها لون Pantone مؤسسي دقيق: جدول الأحبار يجمع كل اسم يُعرف به الأزرق على لوح واحد هو PANTONE 286 C.

- نسخة HTML: https://postext.dev/ar/cookbook/corporate-fifth-ink-report
- وصفة رقم 189 · الإخراج والدمج · المستوى 3 (متقدم) · المخرجات: Canvas, PDF
- الأنواع: التقارير
- تتطلب postext ≥ 1.84.0, postext-pdf ≥ 1.84.0 · اختُبرت مع 1.84.0, postext-pdf 1.84.0 بتاريخ 2026-11-13
- الصفحات: [1](https://postext.dev/cookbook/corporate-fifth-ink-report/en/p01.webp?v=d113be61), [2](https://postext.dev/cookbook/corporate-fifth-ink-report/en/p02.webp?v=d113be61), [3](https://postext.dev/cookbook/corporate-fifth-ink-report/en/p03.webp?v=d113be61), [4](https://postext.dev/cookbook/corporate-fifth-ink-report/en/p04.webp?v=d113be61), [5](https://postext.dev/cookbook/corporate-fifth-ink-report/en/p05.webp?v=d113be61), [6](https://postext.dev/cookbook/corporate-fifth-ink-report/en/p06.webp?v=d113be61), [7](https://postext.dev/cookbook/corporate-fifth-ink-report/en/p07.webp?v=d113be61), [8](https://postext.dev/cookbook/corporate-fifth-ink-report/en/p08.webp?v=d113be61)
- PDF: https://postext.dev/cookbook/corporate-fifth-ink-report/en/corporate-fifth-ink-report.pdf?v=d113be61
- افتح في Sandbox: https://postext.dev/ar/sandbox#recipe=corporate-fifth-ink-report&lang=en (.postext: https://postext.dev/cookbook/corporate-fifth-ink-report/en/corporate-fifth-ink-report.postext)
- آخر تحديث: 2026-11-13
- لغات أخرى: [en](https://postext.dev/en/cookbook/corporate-fifth-ink-report.md), [es](https://postext.dev/es/cookbook/corporate-fifth-ink-report.md), [ca](https://postext.dev/ca/cookbook/corporate-fifth-ink-report.md), [de](https://postext.dev/de/cookbook/corporate-fifth-ink-report.md), [fr](https://postext.dev/fr/cookbook/corporate-fifth-ink-report.md), [it](https://postext.dev/it/cookbook/corporate-fifth-ink-report.md), [pt](https://postext.dev/pt/cookbook/corporate-fifth-ink-report.md), [zh](https://postext.dev/zh/cookbook/corporate-fifth-ink-report.md), [ja](https://postext.dev/ja/cookbook/corporate-fifth-ink-report.md)

## باختصار

تقرير سنوي لمؤسسة تعتني بنهر، يُطبع بالأحبار الأربعة المعتادة وبلون أزرق دقيق هو لون المؤسسة. كل ملف يسمي الأزرق باسم مختلف، ومع ذلك يضعه ملف الطباعة كله على لوح واحد.

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

تقرير سنوي من ثماني صفحات بقياس A4 لمؤسسة متخيلة تعيد إحياء نهر، يُطبع بأربعة ألوان وحبر خامس هو أزرقها المؤسسي. يقع الأزرق حيث تضعه أي علامة: الشريط على الغلاف، والشريط فوق كل قسم، والعناوين، ورؤوس الجداول، وأعمدة الرسم البياني، والغلاف الخلفي. وتملأ درجتاه 40 % و12 % الأعمدة المخططة وصفوف المجموع وإطار الأرقام الرئيسية، وتُطبعان شبكةً من الحبر نفسه، لا مزيجًا من الألوان الأساسية. وتبقى الصور والنص بالألوان الأساسية الأربعة. في ملف PDF/X-4 خمسة ألواح، ويحمل الخامس الاسم الذي تحفظ به المطبعة الحبر، `PANTONE 286 C`، مع أن التصميم لا يسميه بهذا الاسم في أي موضع.

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

- كيف أطبع تقريرًا بأربعة ألوان ولون Pantone الخاص بنا حين يسمي كل ملف الحبر باسم مختلف؟

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

```js
// script.js, سطرًا 20–37
// The corporate blue as each source named it: the designer's swatch, an older palette that
// wrote it without the space, and the chart, drawn in Spanish, which says 'Azul Cauce'. The
// tints are the same ink at 40 % and 12 %: no process mix stands in for them.
const BLUE = { c: 100, m: 75, y: 0, k: 0 }; // what the ink looks like at 100 %, for a proof
const spot = (hex, name, tint) => ({ hex, model: 'spot', spot: { name, cmyk: BLUE, tint } });
const palette = {
  ink: { hex: '#1c2129', model: 'hex' }, // text, in process black
  muted: { hex: '#5d6573', model: 'hex' },
  blue: spot('#0033a0', 'Brand Blue'),
  blue40: spot('#99add9', 'Pantone 286C', 40),
  blue12: spot('#e0e6f3', 'Brand Blue', 12),
  ochre: { hex: '#c98a1b', model: 'hex' }, // the one process accent: the second data series
  paper: { hex: '#ffffff', model: 'hex' },
};
// The ink table: the plate's name is the printer's, and every other name prints on it.
const PRINT = { standard: 'pdfx4', outputProfile: 'fogra51', convertImages: false,
  inks: [{ name: 'PANTONE 286 C', aliases: ['Brand Blue', 'Pantone 286C', 'Azul Cauce'],
    cmyk: BLUE }] };
```

## المكونات

**تعلّم**

- [الألوان الخاصة وجدول الأحبار](https://postext.dev/ar/docs/configuration-pdf-output.md#الألوان-الخاصة): اللون ذو النموذج 'spot' يُطبع على لوح خاص به بنسبته. ويسمّي جدول الأحبار اللوح كما تعرفه المطبعة، ويجمع عليه الأسماء الأخرى التي تعطيها لوحة الألوان وملفات SVG والملفات المستوردة للحبر نفسه.
- [ملفات PDF بنظام CMYK وبالتدرج الرمادي](https://postext.dev/ar/docs/configuration-fonts-colors-viewers.md#إنتاج-pdf-الإعدادات): تحمل الألوان نموذجها (hex، rgb، cmyk، hsl)، ويمكن فرض CMYK أو التدرج الرمادي على PDF للمطبعة أو لبروفة.

**تستخدم أيضًا**

- [لوحة ألوان دلالية](https://postext.dev/ar/docs/configuration-fonts-colors-viewers.md#لوحة-الألوان)
- [الأغلفة وصفحات العنوان وبيانات النشر](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين)
- [صفحات افتتاح مصمَّمة](https://postext.dev/ar/docs/configuration-headings.md#الامتداد-والتصميم-المتقدم)
- [النصوص والخطوط والمربعات في تصاميم الصفحة](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات)
- [الصور في تصاميم الصفحة](https://postext.dev/ar/docs/configuration-headers-footers.md#عناصر-الصورة)
- [إطارات التنبيه](https://postext.dev/ar/docs/configuration-callouts.md#أنماط-الإطارات)
- [نمط الجدول](https://postext.dev/ar/docs/configuration-resources.md#نمط-الجداول)
- [الأشكال والجداول بوصفها موارد](https://postext.dev/ar/docs/document-format-resources.md#الموارد)
- [التصدير إلى PDF](https://postext.dev/ar/docs/configuration-pdf-output.md#توليد-ملفات-pdf)
- [صفحات على اللوحة (Canvas)](https://postext.dev/ar/docs/configuration-programmatic-usage.md#رسم-صفحة-في-صورة-نقطية)
- [أعمدة داخل الإطار أو النص](https://postext.dev/ar/docs/document-format-directives.md#columns)
- [تعبئة الخلايا](https://postext.dev/ar/docs/document-format-resources.md#التضمين-في-كتلة-اختياري-لوضع-صريح-داخل-التدفق)
- [استشهادات تضع الأشكال](https://postext.dev/ar/docs/document-format-resources.md#الإحالة-داخل-السطر-الصيغة-الأساسية)
- [سمات العنوان](https://postext.dev/ar/docs/document-format.md#سمات-العناوين)
- [أنماط العناوين](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين)
- [أشكال في هذا الموضع بالضبط](https://postext.dev/ar/docs/document-format-resources.md#التضمين-في-كتلة-اختياري-لوضع-صريح-داخل-التدفق)
- [شريط فصل بعرض الصفحة](https://postext.dev/ar/docs/configuration-headings.md#الامتداد-والتصميم-المتقدم)
- [لون الورق](https://postext.dev/ar/docs/configuration-page-layout.md#الصفحة)
- [أنماط الفقرات](https://postext.dev/ar/docs/configuration-styles.md#أنماط-الفقرات)
- [الخطوط المضمَّنة في PDF](https://postext.dev/ar/docs/configuration-pdf-output.md#لماذا-مزوّد-الخطوط)
- [أنواع موارد مخصّصة](https://postext.dev/ar/docs/configuration-resources.md#أنواع-الموارد)
- [هندسة القسم](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين)
- [ترويسات لكل قسم](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين)
- [إطارات بعرض الصفحة](https://postext.dev/ar/docs/configuration-callouts.md#الحاوية-callout)
- [جداول من البيانات](https://postext.dev/ar/docs/document-format-resources.md#التضمين-في-كتلة-اختياري-لوضع-صريح-داخل-التدفق)
- [فصول بلا أرقام](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين)

**الإعدادات في لمحة**

- [`bodyText`](https://postext.dev/ar/docs/configuration-text.md#نص-المتن), [`calloutStyles`](https://postext.dev/ar/docs/configuration-callouts.md#أنماط-الإطارات), [`captionStyle`](https://postext.dev/ar/docs/configuration-resources.md#نمط-التعليقات), [`colorPalette`](https://postext.dev/ar/docs/configuration-fonts-colors-viewers.md#لوحة-الألوان), [`footer`](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات), [`header`](https://postext.dev/ar/docs/configuration-headers-footers.md#الترويسات-والتذييلات), [`headingStyles`](https://postext.dev/ar/docs/configuration-styles.md#أنماط-العناوين), [`headings`](https://postext.dev/ar/docs/configuration-headings.md#العناوين), [`layout`](https://postext.dev/ar/docs/configuration-page-layout.md#التخطيط), [`locale`](https://postext.dev/ar/docs/configuration-language.md#تقسيم-الكلمات-بالواصلة), [`page`](https://postext.dev/ar/docs/configuration-page-layout.md#الصفحة), [`paragraphStyles`](https://postext.dev/ar/docs/configuration-styles.md#أنماط-الفقرات), [`print`](https://postext.dev/ar/docs/configuration-fonts-colors-viewers.md#الإنتاج-الطباعي-الإعدادات), [`resourceTypes`](https://postext.dev/ar/docs/configuration-resources.md#أنواع-الموارد), [`tableStyle`](https://postext.dev/ar/docs/configuration-resources.md#نمط-الجداول), [`unorderedLists`](https://postext.dev/ar/docs/configuration-lists-math.md#القوائم-غير-المرقّمة)

**واجهات API**

- [`buildDocumentWithFonts`](https://postext.dev/ar/docs/configuration-programmatic-usage.md#تحميل-الخطوط-قبل-الإخراج), [`decompressWoff2`](https://postext.dev/ar/docs/configuration-pdf-output.md#مزوّد-الخطوط-في-المتصفح-fontsource--woff2), [`inlineSvgFonts`](https://postext.dev/ar/docs/configuration-resources.md#الخطوط-في-نصوص-svg), [`parseTSV`](https://postext.dev/ar/docs/document-format-resources.md#التضمين-في-كتلة-اختياري-لوضع-صريح-داخل-التدفق), [`registerResourceImage`](https://postext.dev/ar/docs/architecture.md#واجهة-البرمجة-المتاحة-api), [`renderPageToCanvas`](https://postext.dev/ar/docs/configuration-programmatic-usage.md#رسم-صفحة-في-صورة-نقطية), [`renderToPdf`](https://postext.dev/ar/docs/configuration-pdf-output.md#توليد-ملفات-pdf), [`setAlignment`](https://postext.dev/ar/docs/document-format-resources.md#التضمين-في-كتلة-اختياري-لوضع-صريح-داخل-التدفق), [`setCellBackground`](https://postext.dev/ar/docs/document-format-resources.md#التضمين-في-كتلة-اختياري-لوضع-صريح-داخل-التدفق)

**الخطوط**

- Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)

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

### 1 · حبر واحد بثلاثة أسماء

الشيفرة هي [الجواب المختصر](https://postext.dev/ar/cookbook/corporate-fifth-ink-report.md#الجواب-المختصر) أعلاه. يصل الأزرق إلى التقرير بثلاثة أسماء، كما يحدث في الأعمال الحقيقية: عيّنة المصمم اسمها `Brand Blue`، ولوحة ألوان قديمة كتبت `Pantone 286C` للدرجة 40 %، والرسم البياني الذي رسمه مكتب إسبانيا يقول `Azul Cauce`. ولولا جدول الأحبار لخرج كل اسم على لوح خاص به، ولتسلمت المطبعة ثلاثة ألوان زرقاء عليها أن تمزجها. يسمي البند في [جدول الأحبار](https://postext.dev/ar/docs/configuration-pdf-output.md#الألوان-الخاصة) اللوح ويضع الأسماء الأخرى أسماءً بديلة؛ وتُقارن الأسماء دون اعتبار لحالة الأحرف ولا للمسافات، فتقع كل درجة من كل اسم على الفصل الوحيد `PANTONE 286 C`. وقيمة `cmyk` فيه هي اللون البديل الذي تُظهره البروفة.

### 2 · الرسم البياني يسمي حبره

```js
// script.js, سطرًا 328–371
// Kilometres of bank restored each year: the bars in the blue (data-spot="Azul Cauce"), the
// plan in its 40 % tint, the labels in process black. An alias brings both onto the plate.
const YEARS = [[2021, 3.1, 4], [2022, 4.6, 5], [2023, 6.2, 6], [2024, 7.4, 8], [2025, 9.8, 9]];
function chartArt() {
  const [W, H, BASE, LEFT, MAX] = [84, 56, 46, 8, 12];
  const y = (v) => BASE - (v / MAX) * (BASE - 4);
  const lines = [0, 4, 8, 12].map((v) => `<path d="M${LEFT} ${y(v)}H${W}" stroke="#c4cad4" `
    + `stroke-width="0.2"/><text x="${LEFT - 1.5}" y="${y(v) + 1}" font-size="2.6" `
    + `text-anchor="end" fill="#5d6573">${v}</text>`).join('');
  const bars = YEARS.map(([year, done, plan], i) => {
    const x = LEFT + 3 + i * 15;
    return `<rect x="${x}" y="${y(plan)}" width="5" height="${BASE - y(plan)}" fill="#99add9" `
      + `data-spot="Azul Cauce" data-spot-tint="40"/><rect x="${x + 5.6}" y="${y(done)}" `
      + `width="5" height="${BASE - y(done)}" fill="#0033a0" data-spot="Azul Cauce"/>`
      + `<text x="${x + 5.3}" y="${BASE + 5}" font-size="2.8" text-anchor="middle" `
      + `fill="#1c2129">${year}</text>`;
  }).join('');
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${W * 10}" height="${H * 10}" `
    + `viewBox="0 0 ${W} ${H}" font-family="'Source Sans 3'">${lines}${bars}</svg>`;
}
// Where each euro went: one bar across the text block, the river in the full ink, schools in
// its 40 % tint, the running costs in process grey.
const SPENT = [[1520, '#0033a0', 100, t({ en: 'Work on the river', es: 'Obras en el río' })],
  [340, '#99add9', 40, t({ en: 'Schools', es: 'Escuelas' })],
  [180, '#9aa1ad', 0, t({ en: 'Running costs', es: 'Funcionamiento' })]];
function euroArt() {
  const [W, H] = [174, 22];
  const total = SPENT.reduce((sum, [v]) => sum + v, 0);
  let x = 0;
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${W * 10}" height="${H * 10}" `
    + `viewBox="0 0 ${W} ${H}" font-family="'Source Sans 3'">`
    + `${SPENT.map(([v, hex, tint, name], i) => {
      const w = (v / total) * W;
      const ink = tint ? ` data-spot="Azul Cauce" data-spot-tint="${tint}"` : '';
      const end = i === SPENT.length - 1; // the last label sets flush right, under its segment
      const tx = `x="${end ? W : x}" text-anchor="${end ? 'end' : 'start'}"`;
      const part = `<rect x="${x}" y="0" width="${w - 0.6}" height="10" fill="${hex}"${ink}/>`
        + `<text ${tx} y="15.5" font-size="3.2" font-weight="700" fill="#1c2129">`
        + `${Math.round((v / total) * 100)} %</text><text ${tx} y="20" font-size="2.8" `
        + `fill="#5d6573">${name}</text>`;
      x += w;
      return part;
    }).join('')}</svg>`;
}
```

يذكر ملف SVG بالسمة `data-spot` الحبر الذي يُطبع به اللون، وبالسمة `data-spot-tint` قوته بالنسبة المئوية. تسمي أعمدة الرسم البياني `Azul Cauce` بنسبة 100 % وبنسبة 40 %، ويضعها الاسم البديل على اللوح نفسه الذي عليه بقية الأزرق. أما خطوط الشبكة والتسميات فألوان عادية تبقى في أسود الألوان الأساسية. ويفعل شريط النفقات في صفحة الحسابات الشيء نفسه بثلاثة أجزاء، ثالثها رمادي من الألوان الأساسية.

### 3 · الأزرق يحمل التصميم

```js
// script.js, سطرًا 55–73
const BAND = 172; // mm from the top of the bleed to the top of the blue band
const cover = { id: 'cover', numbered: false, toc: false, span: 'page',
  header: { elements: [] }, footer: { elements: [] },
  margins: { top: mm(0), bottom: mm(0), left: mm(0), right: mm(0) },
  advancedDesign: { enabled: true, minHeight: mm(TRIM_H), slot: { elements: [
    { kind: 'image', id: 'photo', resourceId: 'meander', fit: 'cover',
      placement: at('bleed', 'top-left', 0, 0, { width: 'fill', height: mm(BAND + 1) }) },
    { kind: 'box', id: 'band', style: { backgroundColor: col('blue') },
      placement: at('bleed', 'top-left', 0, BAND, { width: 'fill', height: mm(TRIM_H) }) },
    text('name', '{author}', label(10, col('paper')), at('page', 'top-left', 20, BAND + 14)),
    text('title', '{titleText}', { fontFamily: SANS, fontWeight: 800, fontSize: pt(46),
      lineHeight: 1, color: col('paper') }, at('#name', 'below', 0, 6, { width: mm(170) })),
    { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(3), color: col('blue40'),
      placement: at('#title', 'below', 0, 7, { width: mm(24) }) },
    text('strap', '{attr.strap}', { fontFamily: 'Source Serif 4', italic: true, fontSize: pt(15),
      lineHeight: 1.3, color: col('paper') }, at('#rule', 'below', 0, 6, { width: mm(120) })),
    text('credit', '{attr.credit}', { fontFamily: SANS, fontSize: pt(7), color: col('blue40') },
      at('page', 'bottom-left', 20, -14, { width: mm(170) })),
  ] } } };
```

تملأ صورة الغلاف أعلى منطقة النزف بالخيار `fit: 'cover'`، ويملأ إطار بالأزرق ما تبقى؛ والحروف فوقه بيضاء ومفرّغة من اللوح. وتستعمل أشرطة الأقسام وتذييلات الصفحات ورؤوس الجداول البند نفسه من لوحة الألوان، فيكفي تغيير سطر واحد لتغيير الحبر.

```js
// script.js, سطرًا 315–324
// A row whose first cell is bold is a total: it takes the tint. Figures align right.
function tsvTable(tsv, columnWidths) {
  let m = Object.assign(parseTSV(tsv, { headerRows: 1 }), { columnWidths });
  m.rows.forEach((row, r) => row.forEach((_, c) => {
    if (c > 0) m = setAlignment(m, { row: r, col: c }, 'right', 'middle');
    if (r && row[0].content.startsWith('**')) m = setCellBackground(m, { row: r, col: c },
      col('blue12'));
  }));
  return m;
}
```

تأتي الجداول من ملفات TSV بجوار النص. والصف الذي خليته الأولى بخط عريض صف مجموع يأخذ الدرجة 12 %؛ والأرقام تُصف إلى اليمين.

### 4 · الصور تبقى بنظام RGB

يُبقي `convertImages: false` في إعدادات الطباعة الصور ملفات JPEG بنظام RGB موسومة بملف sRGB، وهو ما يسمح به PDF/X-4؛ ويتولى RIP المطبعة فصلها. فيبقى الملف خفيفًا، ولا يصل إلى لوح الأزرق شيء من الصور.

## الوصفة كاملة

ملف واحد، مركّب من مجلد الوصفة ومعه نص المثال وأدوات دليل الوصفات المشتركة مضمّنة؛ وهو ينشئ صفحته بنفسه. لتشغيله، ضعه داخل `<script type="module">` في صفحة فارغة أو الصقه في لوحة JS في مثال CodePen جديد (وحدةً). يستورد postext من esm.sh، فلا حاجة إلى تثبيت أو بناء.

- مجلد الوصفة: https://github.com/drnachio/postext/tree/main/cookbook/corporate-fifth-ink-report

### script.js

```js
// ═══ Postext Cookbook · Nº 189 · A fifth ink for the corporate colour ═══════════════════
// https://postext.dev/en/cookbook/corporate-fifth-ink-report
// Code: MIT · Text: original (CC BY 4.0) · Photographs: diffusion models
// Fonts: Source Serif 4, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.84.0
//
// An annual report printed in four colours and one exact corporate blue. The palette, the
// chart and an older swatch call the blue by three names; the ink table gathers them on one
// plate named as the printer stocks the ink, PANTONE 286 C.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, parseTSV, setCellBackground,
  setAlignment, inlineSvgFonts,
} 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 = 'corporate-fifth-ink-report';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region answer: one spot ink, three names: the ink table puts them on one plate
// The corporate blue as each source named it: the designer's swatch, an older palette that
// wrote it without the space, and the chart, drawn in Spanish, which says 'Azul Cauce'. The
// tints are the same ink at 40 % and 12 %: no process mix stands in for them.
const BLUE = { c: 100, m: 75, y: 0, k: 0 }; // what the ink looks like at 100 %, for a proof
const spot = (hex, name, tint) => ({ hex, model: 'spot', spot: { name, cmyk: BLUE, tint } });
const palette = {
  ink: { hex: '#1c2129', model: 'hex' }, // text, in process black
  muted: { hex: '#5d6573', model: 'hex' },
  blue: spot('#0033a0', 'Brand Blue'),
  blue40: spot('#99add9', 'Pantone 286C', 40),
  blue12: spot('#e0e6f3', 'Brand Blue', 12),
  ochre: { hex: '#c98a1b', model: 'hex' }, // the one process accent: the second data series
  paper: { hex: '#ffffff', model: 'hex' },
};
// The ink table: the plate's name is the printer's, and every other name prints on it.
const PRINT = { standard: 'pdfx4', outputProfile: 'fogra51', convertImages: false,
  inks: [{ name: 'PANTONE 286 C', aliases: ['Brand Blue', 'Pantone 286C', 'Azul Cauce'],
    cmyk: BLUE }] };
// #endregion
const col = (id) => ({ ...palette[id], paletteId: id });
const colorPalette = [...Object.entries(palette).map(([id, value]) => ({ id, name: id, value })),
  { id: 'main-color', name: 'blue (defaults)', value: palette.blue }];

const [TRIM_W, TRIM_H] = [210, 297]; // A4
const MARGIN = { top: 24, bottom: 24, inner: 20, outer: 16 };
const LEAD = 13.2; // pt
const SANS = 'Source Sans 3';
const at = (to, edge, x = 0, y = 0, size) => ({ anchor: { to, edge },
  offset: { x: mm(x), y: mm(y) }, ...(size && { size }) });
const text = (id, content, look, placement) => ({ kind: 'text', id, content, align: 'left',
  overflow: 'wrap', placement, ...look });
const label = (size, color) => ({ fontFamily: SANS, fontWeight: 700, fontSize: pt(size),
  letterSpacing: pt(size * 0.14), textTransform: 'uppercase', color });

// #region cover: the river from the air over a band of the corporate blue
const BAND = 172; // mm from the top of the bleed to the top of the blue band
const cover = { id: 'cover', numbered: false, toc: false, span: 'page',
  header: { elements: [] }, footer: { elements: [] },
  margins: { top: mm(0), bottom: mm(0), left: mm(0), right: mm(0) },
  advancedDesign: { enabled: true, minHeight: mm(TRIM_H), slot: { elements: [
    { kind: 'image', id: 'photo', resourceId: 'meander', fit: 'cover',
      placement: at('bleed', 'top-left', 0, 0, { width: 'fill', height: mm(BAND + 1) }) },
    { kind: 'box', id: 'band', style: { backgroundColor: col('blue') },
      placement: at('bleed', 'top-left', 0, BAND, { width: 'fill', height: mm(TRIM_H) }) },
    text('name', '{author}', label(10, col('paper')), at('page', 'top-left', 20, BAND + 14)),
    text('title', '{titleText}', { fontFamily: SANS, fontWeight: 800, fontSize: pt(46),
      lineHeight: 1, color: col('paper') }, at('#name', 'below', 0, 6, { width: mm(170) })),
    { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(3), color: col('blue40'),
      placement: at('#title', 'below', 0, 7, { width: mm(24) }) },
    text('strap', '{attr.strap}', { fontFamily: 'Source Serif 4', italic: true, fontSize: pt(15),
      lineHeight: 1.3, color: col('paper') }, at('#rule', 'below', 0, 6, { width: mm(120) })),
    text('credit', '{attr.credit}', { fontFamily: SANS, fontSize: pt(7), color: col('blue40') },
      at('page', 'bottom-left', 20, -14, { width: mm(170) })),
  ] } } };
// #endregion

// #region opener: a section opens under a blue bar that carries its kicker
const opener = { enabled: true, minHeight: mm(51), slot: { elements: [
  { kind: 'box', id: 'bar', style: { backgroundColor: col('blue') },
    placement: at('container', 'top-left', 0, 0, { width: 'fill', height: mm(9) }) },
  text('kicker', '{attr.kicker}', label(8, col('paper')), at('container', 'top-left', 4, 2.4)),
  text('title', '{titleText}', { fontFamily: SANS, fontWeight: 800, fontSize: pt(30),
    lineHeight: 1.04, color: col('blue') }, at('#bar', 'below', 0, 9, { width: mm(150) })),
  text('lead', '{attr.lead}', { fontFamily: 'Source Serif 4', italic: true, fontSize: pt(12.5),
    lineHeight: 1.3, color: col('ink') }, at('#title', 'below', 0, 4, { width: mm(150) })),
] } };
// #endregion

// #region feet: the folio and the report on every page, a short blue rule over them
const foot = (id, content, parity, edge, x, look = {}) => text(id, content, { ...label(7,
  col('muted')), parity, align: edge.endsWith('left') ? 'left' : 'right', ...look },
at('page', edge, x, -12));
const footer = { elements: [
  { kind: 'rule', id: 'rule-v', parity: 'even', direction: 'horizontal', thickness: pt(2),
    color: col('blue'), placement: at('page', 'bottom-left', MARGIN.outer, -18,
      { width: mm(10) }) },
  { kind: 'rule', id: 'rule-r', parity: 'odd', direction: 'horizontal', thickness: pt(2),
    color: col('blue'), placement: at('page', 'bottom-right', -MARGIN.outer, -18,
      { width: mm(10) }) },
  foot('folio-v', '{pageNumber}', 'even', 'bottom-left', MARGIN.outer, { color: col('blue') }),
  foot('title-v', '{title}', 'even', 'bottom-left', MARGIN.outer + 9),
  foot('part-r', '{chapterTitle}', 'odd', 'bottom-right', -(MARGIN.outer + 9)),
  foot('folio-r', '{pageNumber}', 'odd', 'bottom-right', -MARGIN.outer, { color: col('blue') }),
] };
// #endregion

// A photograph across the head of the page, a volunteer's words on the blue's 12 % tint.
const PHOTO = 168; // mm of bleed the photograph takes
const plate = { id: 'plate', numbered: false, toc: false, span: 'page',
  header: { elements: [] }, footer: { elements: [] },
  advancedDesign: { enabled: true, minHeight: mm(TRIM_H - 48), slot: { elements: [
    { kind: 'image', id: 'photo', resourceId: 'volunteers', fit: 'cover',
      placement: at('bleed', 'top-left', 0, 0, { width: 'fill', height: mm(PHOTO) }) },
    { kind: 'box', id: 'field', style: { backgroundColor: col('blue12') },
      placement: at('bleed', 'top-left', 0, PHOTO, { width: 'fill', height: mm(TRIM_H) }) },
    text('caption', '{attr.caption}', { fontFamily: SANS, fontSize: pt(8), color: col('muted') },
      at('page', 'top-left', 20, PHOTO + 2, { width: mm(170) })),
    text('quote', '“{attr.quote}”', { fontFamily: 'Source Serif 4', italic: true,
      fontSize: pt(20), lineHeight: 1.3, color: col('blue') },
    at('page', 'top-left', 20, PHOTO + 22, { width: mm(150) })),
    { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(3), color: col('blue'),
      placement: at('#quote', 'below', 0, 8, { width: mm(24) }) },
    text('who', '{attr.who}', label(8, col('blue')), at('#rule', 'below', 0, 4)),
  ] } } };

// The back cover: all blue, the address and how the report was printed, in white.
const back = { id: 'back', numbered: false, toc: false, span: 'page',
  breakBefore: { enabled: true, parity: 'even' }, header: { elements: [] },
  footer: { elements: [] }, advancedDesign: { enabled: true, minHeight: mm(TRIM_H - 48),
    slot: { elements: [
      { kind: 'box', id: 'field', style: { backgroundColor: col('blue') },
        placement: at('bleed', 'top-left', 0, 0, { width: 'fill', height: 'fill' }) },
      text('name', '{titleText}', { fontFamily: SANS, fontWeight: 800, fontSize: pt(22),
        color: col('paper') }, at('page', 'top-left', 20, 210)),
      text('address', '{attr.address}', { fontFamily: SANS, fontSize: pt(9), lineHeight: 1.4,
        color: col('paper') }, at('#name', 'below', 0, 4, { width: mm(90) })),
      text('inks', '{attr.inks}', { fontFamily: SANS, fontSize: pt(7.5), lineHeight: 1.4,
        color: col('blue40') }, at('#address', 'below', 0, 8, { width: mm(110) })),
    ] } } };

const config = () => ({
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette, resourceTypes,
  page: { sizePreset: 'custom', width: mm(TRIM_W), height: mm(TRIM_H), dpi: 150,
    backgroundColor: col('paper'), margins: { top: mm(MARGIN.top), bottom: mm(MARGIN.bottom),
      left: mm(MARGIN.inner), right: mm(MARGIN.outer), mirror: true } },
  layout: { layoutType: 'double', gutterWidth: mm(7) },
  bodyText: { fontFamily: 'Source Serif 4', fontSize: pt(9.6), lineHeight: pt(LEAD),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('blue'),
    textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false,
    hyphenation: { enabled: true }, avoidWidows: true, avoidOrphans: true },
  headings: { fontFamily: SANS, fontWeight: 700, color: col('blue'), levels: [
    { level: 1, span: 'page', breakBefore: { enabled: true, parity: 'any' },
      advancedDesign: opener },
    { level: 2, fontSize: pt(11), lineHeight: pt(LEAD), marginTop: pt(LEAD),
      marginBottom: pt(0) }] },
  headingStyles: [cover, plate, back],
  unorderedLists: { bulletChar: '•', color: col('blue'), marginTop: pt(0), marginBottom: pt(0) },
  calloutStyles: [{ id: 'figures', background: col('blue12'), columnGap: mm(7),
    padding: { top: mm(4), right: mm(5), bottom: mm(4), left: mm(5) },
    marginTop: pt(LEAD), marginBottom: pt(LEAD),
    titleStyle: { ...label(7.5, col('blue')), gap: mm(2.5) },
    body: { fontFamily: SANS, fontSize: pt(8.8), lineHeight: pt(12), color: col('ink'),
      textAlign: 'left', firstLineIndent: pt(0) } }],
  paragraphStyles: [
    { id: 'figure', fontFamily: SANS, fontWeight: 800, fontSize: pt(24), lineHeight: pt(28),
      color: col('blue'), boldColor: col('blue'), textAlign: 'left', firstLineIndent: pt(0) },
    { id: 'signoff', fontFamily: SANS, fontSize: pt(8.5), color: col('muted'), textAlign: 'left',
      firstLineIndent: pt(0) },
  ],
  tableStyle: { rules: 'horizontal', borderColor: col('blue40'), borderWidth: pt(0.5),
    headerBackground: col('blue'), headerColor: col('paper'), headerFontFamily: SANS,
    headerFontSize: pt(8), bodyFontFamily: SANS, bodyFontSize: pt(8.4), bodyColor: col('ink'),
    cellPadding: mm(1.3) },
  captionStyle: { fontFamily: SANS, fontSize: pt(8), color: col('ink'), gap: mm(2),
    labelBold: true, labelColor: col('blue'), note: { fontSize: pt(7), color: col('muted') } },
  print: PRINT,
  header: { elements: [] }, footer,
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Annual Report 2025"
author: "Cauce Foundation"
---

# Annual Report 2025 {style="cover" strap="Giving the Alcarrán room to be a river again" credit="The Cauce Foundation and the Alcarrán valley are fictional: every name and figure in this report is invented. Photographs generated with diffusion models."}

# A river given room {kicker="From the director" lead="We restored 9.8 kilometres of bank, more than in any year since the foundation began, and the river answered with its cleanest water on record."}

::resource{id="director"}

When the foundation was set up in 2014, the Alcarrán ran between earth banks pushed up by bulldozers after the floods of the 1970s. Its gravel bars had been dredged for building, its poplars cut for paper, and in summer whole reaches below Valtierra stood still and green. Ten years on, a walk along the same banks tells another story. In 2025 we took down two more of the old embankments, planted 41,000 willows, alders and ash trees, and gave the river back 64 hectares of floodplain where it can spread when it rises.

None of it would have happened without the 1,240 volunteers who came out on cold Saturdays to plant, to pull invasive cane and to count birds, or without the 37 farmers who agreed to let a strip of their land go wild along the water. Their patience is the foundation’s real capital. Several of them told us this year that the river now floods their fields less often, not more, because the water has somewhere else to go.

The monthly samples our volunteers take at nine stations show the result. Nitrate fell for the fourth year running, dissolved oxygen in August stayed above the level trout need at every station for the first time, and the otter, gone from the middle valley since the 1980s, left its tracks at Fuentelsaz in October.

:::callout{type="figures" span="page" title="2025 in three numbers"}
:::columns{count=3 breaks="3,5"}
:::paragraphs{style="figure"}
**9.8 km**
:::

of river bank restored, against 7.4 in 2024

:::paragraphs{style="figure"}
**41,000**
:::

native trees and shrubs planted by volunteers

:::paragraphs{style="figure"}
**€1.86 m**
:::

spent on the river, 87 cents of every euro we raised
:::
:::

Next year we start on the hardest reach of all, the four kilometres through the town of Alcarrán itself, where the river runs in a concrete channel. The council has given us the land; the design is ready. I hope you will walk it with us.

:::paragraphs{style="signoff"}
Inés Barrera, director
:::

# Work along the river {kicker="Projects" lead="Two embankments taken down, three side channels reopened and a weir removed at the old mill of Somaén."}

The foundation works in reaches: stretches of a few kilometres where the land on both banks belongs to owners who have agreed to the plan. In 2025 we worked on five of them (:ref{id="projects"}), from the headwaters above Fuentelsaz down to the confluence with the Jalón, and restored more bank than in any year before (:ref{id="banks"}).

## Embankments and side channels

At Valtierra and Maluenda, machines removed 2.6 kilometres of earth embankment and spread the material over the old fields, so that the bank now slopes gently into the water instead of standing as a wall. Below Valtierra the river had cut three side channels before it was straightened; we reopened them, and by the autumn floods they were carrying water again.

## The weir at Somaén

The weir at the old flour mill, 2.3 metres high, had stopped fish moving upstream since 1904. The mill’s owners gave it up to us in 2024, and in July a crew took it down over three weeks of low water. By December the river had washed the trapped sediment downstream and shaped a run of riffles and pools where the millpond stood.

## Planting

Volunteers planted 41,000 trees and shrubs in 46 working days between November and March, all of them grown from cuttings and seed collected in the valley. Willow and alder go nearest the water, ash and poplar behind them. The bank restored each year has risen steadily since 2021, and for the first time it went beyond what the plan called for.

# Planting day {style="plate" quote="We came for one Saturday in 2019. Now the willows we planted are taller than our children, and the river runs clear under them." who="Marta and Jorge Sanz, volunteers at Valtierra" caption="Volunteers planting willow stakes on the bank at Valtierra, in March."}

# Cleaner water {kicker="River health" lead="Nine stations, sampled every month by volunteers and checked twice a year by an independent laboratory."}

Water quality is the measure we care about most, because it tells us whether the river is working as a river. Volunteers sample nine stations on the first Sunday of each month and test them on the bank for temperature, dissolved oxygen, nitrate and phosphate. Twice a year an independent laboratory takes its own samples at the same points, and the two sets of readings have agreed within 5% since 2022.

::resource{id="sample"}

Nitrate fell to an average of 11 milligrams a litre, from 19 in 2021 (:ref{id="water"}). The largest fall was below Maluenda, where a willow strip now stands between the river and the fields that drain into it. Phosphate is falling more slowly, because much of it lies in the old sediment and is released when the river moves it.

In August, the hardest month for a river in this valley, dissolved oxygen stayed above 7 milligrams a litre at every station. Trout need about 6. A survey by the regional fisheries service in September counted brown trout at seven of the nine stations, against three in 2021.

# Accounts {kicker="Finance" lead="Income rose by 11%, and 87 cents of every euro went to work on the river and to schools."}

The foundation’s income for the year was 2.14 million euros (:ref{id="accounts"}). Monthly donors gave 1.12 million, 6% more than in 2024. Grants from public bodies and the new agreement with the regional water company brought in 0.81 million, and the rest came from legacies and the sale of willow cuttings to other projects.

We spent 2.04 million euros (:ref{id="euro"}). Work on the river, from earthmoving to the nursery, took 1.52 million, and the schools programme, which brought 3,100 pupils to the river this year, 0.34 million. Administration and fundraising cost 0.18 million, 9% of spending. The surplus of 0.10 million goes to the reserve for the works in the town of Alcarrán.

The accounts were audited by an independent firm and approved by the board of trustees on 12 March 2026. The full accounts can be requested from the foundation’s office.

# With thanks {kicker="Supporters" lead="The foundation’s work rests on the people and organisations who gave their time, their land and their money in 2025."}

::resource{id="kingfisher"}

We thank the 6,800 monthly donors who give us the freedom to plan years ahead, and the 1,240 volunteers who gave 19,600 hours to the river. We thank the 37 farmers and landowners who signed agreements to let the bank go wild, and the families who left the foundation a gift in their wills.

## What we saw

Volunteers recorded 112 species of bird along the restored reaches, among them the kingfisher at all five, the penduline tit nesting in the willows at Valtierra, and a pair of black storks feeding in the reopened side channels in spring. The otter’s tracks at Fuentelsaz in October were the first sign of it in the middle valley for forty years.

## Partners

- Alcarrán Town Council
- Jalón Valley Water Company
- Regional Fisheries Service
- University of the Valley, Department of Ecology
- Valtierra Irrigation Community

# Cauce Foundation {style="back" address="Calle del Molino 14 · 50300 Alcarrán · hola@cauce.example" inks="Printed in four colours and one fifth ink, PANTONE 286 C, on uncoated recycled paper."}
`; // content.<lang>.md, inlined by the Cookbook
const projects = String.raw`Project	km	Volunteers	€ thousand
Valtierra: embankment removed, three side channels reopened	3.4	410	612
Maluenda: embankment removed, willow strip	2.1	260	355
Somaén: mill weir removed	0.6	40	288
Fuentelsaz: headwater fencing and planting	2.4	330	174
Jalón confluence: cane cleared, planting	1.3	200	91
**All projects**	**9.8**	**1,240**	**1,520**
`; // the tables: TSV, pasted from a spreadsheet
const accounts = String.raw`€ thousand	2025	2024
Monthly donors	1,120	1,057
Grants and agreements	810	690
Legacies and other income	210	180
**Total income**	**2,140**	**1,927**
Work on the river	1,520	1,410
Schools programme	340	300
Administration and fundraising	180	170
**Total spending**	**2,040**	**1,880**
**Surplus for the year**	**100**	**47**
`;
const water = String.raw`Station	Nitrate 2021	Nitrate 2025	Oxygen, August 2025
Fuentelsaz	9	6	9.1
Torrehermosa	12	8	8.6
Somaén	15	10	8.2
Valtierra, above	18	11	7.9
Valtierra, below	22	12	7.6
Maluenda	27	13	7.4
Alcarrán bridge	24	14	7.2
Alcarrán mill	21	13	7.3
Jalón confluence	23	14	7.1
**Average**	**19**	**11**	**7.9**
`;

// #region tables: the header in the blue, the totals on its 12 % tint
// A row whose first cell is bold is a total: it takes the tint. Figures align right.
function tsvTable(tsv, columnWidths) {
  let m = Object.assign(parseTSV(tsv, { headerRows: 1 }), { columnWidths });
  m.rows.forEach((row, r) => row.forEach((_, c) => {
    if (c > 0) m = setAlignment(m, { row: r, col: c }, 'right', 'middle');
    if (r && row[0].content.startsWith('**')) m = setCellBackground(m, { row: r, col: c },
      col('blue12'));
  }));
  return m;
}
// #endregion

// #region chart: the SVG names its ink in Spanish, and the ink table merges it
// Kilometres of bank restored each year: the bars in the blue (data-spot="Azul Cauce"), the
// plan in its 40 % tint, the labels in process black. An alias brings both onto the plate.
const YEARS = [[2021, 3.1, 4], [2022, 4.6, 5], [2023, 6.2, 6], [2024, 7.4, 8], [2025, 9.8, 9]];
function chartArt() {
  const [W, H, BASE, LEFT, MAX] = [84, 56, 46, 8, 12];
  const y = (v) => BASE - (v / MAX) * (BASE - 4);
  const lines = [0, 4, 8, 12].map((v) => `<path d="M${LEFT} ${y(v)}H${W}" stroke="#c4cad4" `
    + `stroke-width="0.2"/><text x="${LEFT - 1.5}" y="${y(v) + 1}" font-size="2.6" `
    + `text-anchor="end" fill="#5d6573">${v}</text>`).join('');
  const bars = YEARS.map(([year, done, plan], i) => {
    const x = LEFT + 3 + i * 15;
    return `<rect x="${x}" y="${y(plan)}" width="5" height="${BASE - y(plan)}" fill="#99add9" `
      + `data-spot="Azul Cauce" data-spot-tint="40"/><rect x="${x + 5.6}" y="${y(done)}" `
      + `width="5" height="${BASE - y(done)}" fill="#0033a0" data-spot="Azul Cauce"/>`
      + `<text x="${x + 5.3}" y="${BASE + 5}" font-size="2.8" text-anchor="middle" `
      + `fill="#1c2129">${year}</text>`;
  }).join('');
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${W * 10}" height="${H * 10}" `
    + `viewBox="0 0 ${W} ${H}" font-family="'Source Sans 3'">${lines}${bars}</svg>`;
}
// Where each euro went: one bar across the text block, the river in the full ink, schools in
// its 40 % tint, the running costs in process grey.
const SPENT = [[1520, '#0033a0', 100, t({ en: 'Work on the river', es: 'Obras en el río' })],
  [340, '#99add9', 40, t({ en: 'Schools', es: 'Escuelas' })],
  [180, '#9aa1ad', 0, t({ en: 'Running costs', es: 'Funcionamiento' })]];
function euroArt() {
  const [W, H] = [174, 22];
  const total = SPENT.reduce((sum, [v]) => sum + v, 0);
  let x = 0;
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${W * 10}" height="${H * 10}" `
    + `viewBox="0 0 ${W} ${H}" font-family="'Source Sans 3'">`
    + `${SPENT.map(([v, hex, tint, name], i) => {
      const w = (v / total) * W;
      const ink = tint ? ` data-spot="Azul Cauce" data-spot-tint="${tint}"` : '';
      const end = i === SPENT.length - 1; // the last label sets flush right, under its segment
      const tx = `x="${end ? W : x}" text-anchor="${end ? 'end' : 'start'}"`;
      const part = `<rect x="${x}" y="0" width="${w - 0.6}" height="10" fill="${hex}"${ink}/>`
        + `<text ${tx} y="15.5" font-size="3.2" font-weight="700" fill="#1c2129">`
        + `${Math.round((v / total) * 100)} %</text><text ${tx} y="20" font-size="2.8" `
        + `fill="#5d6573">${name}</text>`;
      x += w;
      return part;
    }).join('')}</svg>`;
}
// #endregion

const type = (id, name) => ({ id, name, captionPrefix: name, numberingTemplate: '{n}',
  resetOn: 'never', counterFormat: 'decimal' });
const resourceTypes = [type('figure', t({ en: 'Figure', es: 'Figura' })),
  type('table', t({ en: 'Table', es: 'Tabla' })),
  { ...type('photo', ''), captionPrefix: '', numberingTemplate: '' }];
const photo = (id, file, [w, h], extra) => ({ id, typeId: 'photo', kind: 'bitmap',
  createdAt: 0, updatedAt: 0, bitmap: { fileId: file, format: 'jpeg', width: w, height: h },
  ...extra });
const resources = [
  photo('meander', 'meander.jpg', [1120, 853], { altText: t({
    en: 'The river from the air: a green meander between poplars, gravel bars and fields.',
    es: 'El río desde el aire: un meandro verde entre chopos, playas de grava y campos.' }) }),
  photo('director', 'director.jpg', [800, 1000], { placement: { position: 'top' },
    caption: t({ en: 'Inés Barrera, director', es: 'Inés Barrera, directora' }),
    altText: t({ en: 'A woman in a rain jacket on a river bank.',
      es: 'Una mujer con chubasquero en la orilla de un río.' }) }),
  photo('volunteers', 'volunteers.jpg', [1200, 800], { altText: t({
    en: 'People in boots planting stakes along a muddy bank.',
    es: 'Gente con botas plantando estacas en una orilla embarrada.' }) }),
  photo('sample', 'sample.jpg', [900, 900], { placement: { position: 'top', width: 0.62 },
    caption: t({ en: 'A monthly water sample at the Fuentelsaz gauge.',
      es: 'Una muestra mensual de agua en la estación de Fuentelsaz.' }),
    altText: t({ en: 'Hands holding a sample bottle over clear water.',
      es: 'Unas manos sostienen un frasco de muestra sobre agua clara.' }) }),
  photo('kingfisher', 'kingfisher.jpg', [1050, 700], { placement: { position: 'bottom',
    span: 'page' }, caption: t({ en: 'A kingfisher on a willow at Valtierra, one of those '
      + 'planted in 2019.', es: 'Un martín pescador en un sauce de Valtierra, de los plantados '
      + 'en 2019.' }), altText: t({ en: 'A kingfisher perched on a willow branch over a clear '
      + 'river.', es: 'Un martín pescador posado en una rama de sauce sobre un río claro.' }) }),
  { id: 'banks', typeId: 'figure', kind: 'svg', createdAt: 0, updatedAt: 0,
    svg: { fileId: 'banks.svg', width: 840, height: 560 }, placement: { position: 'top' },
    caption: t({ en: 'River bank restored each year, in kilometres: :swatch{color="blue"} done '
      + 'and :swatch{color="blue40"} planned.', es: 'Orilla restaurada cada año, en kilómetros: '
      + ':swatch{color="blue"} hecha y :swatch{color="blue40"} prevista.' }),
    altText: YEARS.map(([year, done]) => `${year}: ${done} km`).join(', ') },
  { id: 'projects', typeId: 'table', kind: 'table', createdAt: 0, updatedAt: 0,
    table: { model: tsvTable(projects, [5, 1.4, 1.6, 1.6]) }, placement: { position: 'bottom',
      span: 'page' }, caption: t({ en: 'The year’s projects.', es: 'Los proyectos del año.' }) },
  { id: 'water', typeId: 'table', kind: 'table', createdAt: 0, updatedAt: 0,
    table: { model: tsvTable(water, [3, 1.4, 1.4, 1.8]) }, placement: { position: 'bottom',
      span: 'page' }, caption: t({ en: 'Nitrate and dissolved oxygen at the nine stations, in '
      + 'milligrams a litre.', es: 'Nitrato y oxígeno disuelto en las nueve estaciones, en '
      + 'miligramos por litro.' }) },
  { id: 'euro', typeId: 'figure', kind: 'svg', createdAt: 0, updatedAt: 0,
    svg: { fileId: 'euro.svg', width: 1740, height: 220 }, placement: { position: 'bottom',
      span: 'page' }, caption: t({ en: 'Where each euro we spent went in 2025.',
      es: 'A qué fue cada euro que gastamos en 2025.' }),
    altText: SPENT.map(([v, , , name]) => `${name}: ${v}`).join(', ') },
  { id: 'accounts', typeId: 'table', kind: 'table', createdAt: 0, updatedAt: 0,
    table: { model: tsvTable(accounts, [4, 1.3, 1.3]) }, placement: { position: 'top' },
    caption: t({ en: 'Income and spending, in thousands of euros.',
      es: 'Ingresos y gastos, en miles de euros.' }) },
];

await Promise.all([loadImage('meander.jpg', asset('meander-1120.jpg')),
  loadImage('director.jpg', asset('director-800.jpg')),
  loadImage('volunteers.jpg', asset('volunteers-1200.jpg')),
  loadImage('sample.jpg', asset('sample-900.jpg')),
  loadImage('kingfisher.jpg', asset('kingfisher-1050.jpg')), loadSvg('banks.svg', chartArt()),
  loadSvg('euro.svg', euroArt())]);

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = {
  'Source Serif 4': ['400', '400i', '700'],
  'Source Sans 3': ['400', '700', '800'],
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
showPages(doc, { title: t({ en: 'Cauce Foundation · annual report in a fifth ink',
  es: 'Fundación Cauce · memoria anual con una quinta tinta' }) });
offerPdf(() => renderToPdf(doc, { fontProvider: fontsourceProvider, resourceBytes: imageBytes,
  profileBaseUrl: 'https://postext.dev/icc/' }), `${RECIPE}.pdf`);

// ─── Kit ── helpers shared by every Cookbook recipe · postext.dev/cookbook ─────

// ─── Kit · core v1 ── the same in every recipe · postext.dev/cookbook
function mm(value) { return { value, unit: 'mm' }; }
function pt(value) { return { value, unit: 'pt' }; }
function em(value) { return { value, unit: 'em' }; }
/** The sample language's string: t({ en: 'Figure', es: 'Figura' }). */
function t(strings) { return strings[LANG] ?? Object.values(strings)[0]; }
/** A file in this recipe's assets folder, served from the Postext repo by jsDelivr. */
function asset(file) { return `https://cdn.jsdelivr.net/gh/drnachio/postext@main/cookbook/${RECIPE}/assets/${file}`; }

// ─── Kit · fonts v3 ── the same in every recipe · postext.dev/cookbook
// Postext loads the faces a config asks for before layout and asks the kit
// for Fontsource's files, the ones the PDF embeds too.

/** buildDocumentWithFonts' options: the resolver, and FONTS' faces loaded
 *  with the config's. FONTS = { 'Family Name': ['400', '400i', '700'] }. */
function kitFonts(FONTS = {}) {
  const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) =>
    ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));
  return { resolve: fontsourceResolver, faces };
}

/** A face's files with their ranges: latin, then latin-ext and greek when
 *  `text` needs them (kitSubsetsFor). Null for a face Fontsource lacks. */
async function fontsourceResolver(family, weight, style, { text = '' } = {}) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  if (meta && !(await fontsourceWeights(family, style)).includes(weight)) return null;
  kitStatus('Loading fonts…');
  const at = await fontsourceAt(id);
  return ['latin', ...kitSubsetsFor(text, meta)].map((subset) => ({
    source: `${at}files/${id}-${subset}-${weight}-${style}.woff2`,
    unicodeRange: kitRanges()[subset],
  }));
}

/** Each file's unicode-range (a function: the kit runs after the pen's code). */
function kitRanges() {
  return {
    latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
      + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
    'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
      + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF',
    greek: 'U+0370-03FF',
  };
}

/** For the cjk, arabic and comics blocks: loads `faces` (as FONTS) for the
 *  sample `text`; `optional` skips a face Fontsource lacks. Files are added in
 *  the order asked, the last winning a shared character. Resolves to the count. */
async function loadFonts(faces, text = '', { optional = false } = {}) {
  kitStatus('Loading fonts…');
  const ranges = kitRanges();
  const jobs = [];
  for (const [family, specs] of Object.entries(faces)) {
    const id = fontsourceId(family);
    const todo = [...new Set(specs)].map((spec) => [parseInt(spec, 10), spec.endsWith('i') ? 'italic' : 'normal'])
      .filter(([weight, style]) => !hasFace(family, weight, style)); // before any await
    const at = fontsourceAt(id);
    const meta = optional || /[^\0-ÿ]/u.test(text) ? await fontsourceMeta(family) : null;
    const subsets = ['latin', ...kitSubsetsFor(text, meta)];
    for (const [weight, style] of todo) {
      if (optional && !(meta && (await fontsourceWeights(family, style)).includes(weight))) continue;
      for (const subset of subsets) {
        const url = `${await at}files/${id}-${subset}-${weight}-${style}.woff2`;
        const face = new FontFace(family, `url(${url}) format('woff2')`,
          { weight: String(weight), style, unicodeRange: ranges[subset] });
        jobs.push(face.load().catch(() => {
          if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        }));
      }
    }
  }
  const ready = await Promise.all(jobs).catch((error) => { kitFail(error); throw error; });
  return ready.filter((face) => face && document.fonts.add(face)).length;
}

/** A loaded FontFace covers this face (fonts.check() says yes to any family). */
function hasFace(family, weight, style) {
  for (const face of document.fonts) {
    if (face.status !== 'loaded' || face.style !== style) continue;
    if (face.family.replace(/^["']|["']$/g, '') !== family) continue;
    const [low, high = low] = face.weight.split(' ').map(Number);
    if (weight >= low && weight <= high) return true;
  }
  return false;
}

/** The files beyond latin `text` needs that `meta`'s family ships. */
function kitSubsetsFor(text, meta) {
  return [[/[Ā-˿ᴀ-ᶿḀ-ỿ†ℓⱠ-Ɀ꜠-ꟿ]/u, 'latin-ext'], [/[Ͱ-Ͽ]/u, 'greek']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** Fontsource's id for a family: 'Source Serif 4' → 'source-serif-4'. */
function fontsourceId(family) { return family.toLowerCase().replace(/\s+/g, '-'); }

/** A package's folder at the one version @5 names now (#766). */
function fontsourceAt(id, u = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@`) {
  return (fontsourceAt.c ??= {})[id] ??= fetch(u + '5/package.json').then((r) => r.json())
    .then((p) => p.version || 5, () => 5).then((v) => `${u}${v}/`);
}

/** The family's Fontsource metadata (weights, styles, subsets), or null. */
function fontsourceMeta(family, id = fontsourceId(family)) {
  return (fontsourceMeta.c ??= {})[id] ??= fetch(`https://api.fontsource.org/v1/fonts/${id}`)
    .then((res) => (res.ok ? res.json() : null), () => null);
}

/** The weights the package ships in `style`: the API pairs none (no Libre
 *  Caslon 700 italic file), so italics are read from latin-italic.css. */
function fontsourceWeights(family, style, id = fontsourceId(family)) {
  return (fontsourceWeights.c ??= {})[id + style] ??= fontsourceMeta(family).then(async (m) => {
    if (!m?.styles.includes(style)) return m ? [] : [400, 700];
    const css = style === 'italic' ? await fetch(`${await fontsourceAt(id)}latin-italic.css`).then((r) => (r.ok ? r.text() : ''), () => '') : '';
    const w = [...css.matchAll(/weight: (\d+)/g)].map((x) => +x[1]);
    return w.length ? w : m.weights;
  });
}

// ─── Kit · viewer v2 ── the same in every recipe · postext.dev/cookbook
/** The pages as spreads on a dark desk, page 1 alone, then verso | recto,
 *  each painted when it scrolls near. Other options go to renderPageToCanvas. */
function showPages(docs, { title, width = 460, ...render } = {}) {
  const root = viewer(title);
  const pages = [docs].flat().flatMap((doc) =>
    doc.pages.map((page) => ({ doc, page, n: (doc.pageIndexOffset ?? 0) + page.index })));
  const spreads = [];
  let verso = null;
  for (const p of pages) {
    if (p.n % 2 === 1) { if (verso) spreads.push([verso, null]); verso = p; }
    else { spreads.push([verso, p]); verso = null; }
  }
  if (verso) spreads.push([verso, null]);
  const density = Math.min(window.devicePixelRatio || 1, 2);
  showPages.painter?.disconnect();
  const painter = new IntersectionObserver((entries) => {
    for (const { isIntersecting, target } of entries) {
      if (!isIntersecting) continue;
      painter.unobserve(target);
      const { doc, page } = target.postext;
      renderPageToCanvas(page, doc, target, { ...render, scale: (width * density) / page.width });
    }
  }, { rootMargin: '800px' });
  showPages.painter = painter;
  root.replaceChildren(...spreads.map((pair) => {
    const spread = document.createElement('div');
    spread.className = 'pt-spread';
    for (const p of pair) {
      const figure = document.createElement('figure');
      if (p) {
        const label = p.page.pageLabel || String(p.n + 1);
        const canvas = document.createElement('canvas');
        canvas.postext = p;
        canvas.style.aspectRatio = `${p.page.width} / ${p.page.height}`;
        canvas.setAttribute('role', 'img');
        canvas.setAttribute('aria-label', `Page ${label}`);
        const folio = document.createElement('figcaption');
        folio.textContent = label;
        figure.append(canvas, folio);
        painter.observe(canvas);
      } else figure.className = 'pt-blank';
      spread.append(figure);
    }
    return spread;
  }));
  kitStatus(`${pages.length} ${pages.length === 1 ? 'page' : 'pages'}`);
  document.documentElement.dataset.postext = 'ready';
  return pages.length;
}

/** The desk, the bar and the error reporting, created once. */
function viewer(title) {
  if (!document.getElementById('pt-kit')) {
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit">
      :root { color-scheme: dark; }
      body { margin: 0; background: #0e1014; color: #b9bcc4; font: 13px/1.45 system-ui, sans-serif; }
      #pt-bar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; align-items: center;
        gap: 6px 16px; padding: 10px 16px; background: rgb(14 16 20 / .92); backdrop-filter: blur(6px);
        border-bottom: 1px solid #23262d; }
      #pt-bar strong { color: #f4f1ea; font-weight: 600; }
      #pt-actions { display: flex; gap: 12px; margin-left: auto; }
      #pt-actions a, #pt-actions button { color: #d8a21a; font: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
      #pages { display: grid; justify-items: center; gap: 48px; padding: 32px 16px 72px; }
      .pt-spread { display: flex; }
      .pt-spread figure { margin: 0; width: min(460px, 44vw); }
      .pt-spread canvas { display: block; width: 100%; background: #fff;
        box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figure:first-child canvas { box-shadow: inset -14px 0 14px -14px rgb(0 0 0 / .18), 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figcaption { margin-top: 10px; text-align: center; font: 600 10px/1 system-ui, sans-serif;
        letter-spacing: .18em; text-transform: uppercase; color: #6c7079; }
      .pt-blank { visibility: hidden; }
      @media (max-width: 760px) {
        .pt-spread { flex-direction: column; gap: 32px; }
        .pt-spread figure { width: min(460px, 92vw); }
        .pt-blank { display: none; }
      }
    </style>`);
    document.body.insertAdjacentHTML('afterbegin',
      '<header id="pt-bar"><strong id="pt-title"></strong><span id="pt-status" role="status"></span><span id="pt-actions"></span></header>');
    document.getElementById('pt-title').textContent = document.title || 'Postext';
    addEventListener('error', (event) => kitFail(event.error ?? event.message));
    addEventListener('unhandledrejection', (event) => kitFail(event.reason));
  }
  if (title) document.getElementById('pt-title').textContent = title;
  return document.getElementById('pages')
    ?? document.body.appendChild(Object.assign(document.createElement('main'), { id: 'pages' }));
}

function kitStatus(text) {
  viewer();
  document.getElementById('pt-status').textContent = text;
}

function kitFail(error) {
  document.documentElement.dataset.postext = 'error';
  kitStatus(`Error: ${error?.message ?? error}`);
}

// ─── Kit · pdf v3 ── the same in every recipe that exports a PDF
/** The Fontsource files the screen used, as TrueType, with their range and
 *  place: the nearest weight the family ships in that style, upright with no italic;
 *  latin, then what its letters need (kitSubsetsFor). */
async function fontsourceProvider(family, weight, style, request) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  const s = style === 'italic' && meta && !meta.styles.includes('italic') ? 'normal' : style;
  const shipped = meta ? await fontsourceWeights(family, s) : [];
  const weights = shipped.length ? shipped : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const text = String.fromCodePoint(...(request?.codePoints ?? []));
  const files = await Promise.all(['latin', ...kitSubsetsFor(text, meta)].map(async (subset, order) => {
    const res = await fetch(`${await fontsourceAt(id)}files/${id}-${subset}-${w}-${s}.woff2`);
    if (!res.ok) throw new Error(`Fontsource has no ${family} ${w} ${s} ${subset}`);
    return Object.assign(await decompressWoff2(new Uint8Array(await res.arrayBuffer())),
      { unicodeRange: kitRanges()[subset], order });
  }));
  return files.length === 1 ? files[0] : files;
}

/** A "Build the PDF" button; then "Open the PDF" (a new tab: CodePen's frame
 *  shows no PDFs) and a download link. */
function offerPdf(makePdf, filename) {
  viewer();
  const button = Object.assign(document.createElement('button'), { type: 'button', textContent: 'Build the PDF' });
  button.dataset.postextPdf = filename;
  button.addEventListener('click', async () => {
    button.disabled = true;
    button.textContent = 'Building the PDF…';
    try {
      const bytes = await makePdf();
      const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
      const size = `${Math.max(1, Math.round(bytes.length / 1024))} KB`;
      button.replaceWith(
        Object.assign(document.createElement('a'), { href: url, target: '_blank', rel: 'noopener', textContent: 'Open the PDF ↗' }),
        Object.assign(document.createElement('a'), { href: url, download: filename, textContent: `Download ${filename} · ${size}` }));
    } catch (error) {
      button.disabled = false;
      button.textContent = 'Build the PDF';
      kitFail(error);
    }
  });
  document.getElementById('pt-actions').append(button);
}

// ─── Kit · images v3 ── recipes with pictures · postext.dev/cookbook
/** Registers a photo or PNG for the canvas and keeps its bytes for the PDF.
 *  fetch → ImageBitmap never taints the canvas (a plain cross-origin <img> would). */
async function loadImage(fileId, url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`Image not found (${res.status}): ${url}`);
  const bytes = new Uint8Array(await res.arrayBuffer());
  registerResourceImage(fileId, await createImageBitmap(new Blob([bytes])));
  (loadImage.bytes ??= new Map()).set(fileId, bytes);
}

/** Registers SVG markup as a vector image, its fonts inside (inlineSvgFonts, ≥ 1.25).
 *  `options` go to registerResourceImage: { singleInk: true } tints it on the canvas. */
async function loadSvg(fileId, svg, options) {
  if (typeof inlineSvgFonts === 'function') svg = await inlineSvgFonts(svg, svgFaces);
  const img = new Image();
  img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
  await img.decode();
  registerResourceImage(fileId, img, options);
  (loadImage.bytes ??= new Map()).set(fileId, new TextEncoder().encode(svg));
}

/** A face's Fontsource files: nearest weight; latin + what the SVG sets. */
async function svgFaces(family, weight, style, { codePoints = [] } = {}) {
  const [id, m] = [fontsourceId(family), await fontsourceMeta(family)];
  const w = m?.weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a)) ?? weight;
  const s = m?.styles.includes(style) === false ? 'normal' : style;
  return Promise.all(['latin', ...kitSubsetsFor(String.fromCodePoint(...codePoints), m)].map(async (x) => new Uint8Array(
    await (await fetch(`${await fontsourceAt(id)}files/${id}-${x}-${w}-${s}.woff2`)).arrayBuffer())));
}

/** renderToPdf({ resourceBytes: imageBytes }) */
function imageBytes(fileId) { return loadImage.bytes?.get(fileId); }

/** renderToHtml({ resourceImageUrl: imageUrl }) */
function imageUrl(fileId) {
  const bytes = imageBytes(fileId);
  if (!bytes) return undefined;
  imageUrl.urls ??= new Map();
  if (!imageUrl.urls.has(fileId)) {
    const type = /\.svg$/i.test(fileId) ? 'image/svg+xml' : /\.png$/i.test(fileId) ? 'image/png' : 'image/jpeg';
    imageUrl.urls.set(fileId, URL.createObjectURL(new Blob([bytes], { type })));
  }
  return imageUrl.urls.get(fileId);
}

// ─── /Kit ───────────────────────────────────────────────────────────────────────
```

## تنويعات

### اطبع الأزرق بالألوان الأساسية

حين لا تكون في المطبعة وحدة خامسة، تكفي كلمة واحدة في جدول الأحبار لطباعة كل درجة من الأزرق بنظام CMYK انطلاقًا من لونه البديل.

```diff
-  inks: [{ name: 'PANTONE 286 C', aliases: ['Brand Blue', 'Pantone 286C', 'Azul Cauce'],
-    cmyk: BLUE }] };
+  inks: [{ name: 'PANTONE 286 C', aliases: ['Brand Blue', 'Pantone 286C', 'Azul Cauce'],
+    cmyk: BLUE, output: 'process' }] };
```

### سمِّ اللوح باسم مطبعة أخرى

بعض المطابع تريد اللوح باسمها هي. يعيد `pdfName` تسميته ويحتفظ بالأسماء البديلة.

```diff
-  inks: [{ name: 'PANTONE 286 C', aliases: ['Brand Blue', 'Pantone 286C', 'Azul Cauce'],
+  inks: [{ name: 'PANTONE 286 C', pdfName: 'PANTONE 286 U', aliases: ['Brand Blue', 'Pantone 286C', 'Azul Cauce'],
```

## أخطاء شائعة

- اللون في صورة لا يسمي حبره ولا يطابق تمامًا لونًا خاصًا في لوحة الألوان يبقى بالألوان الأساسية، حتى لو بدا هو الأزرق نفسه. علّم العناصر بالسمة `data-spot`، أو أضف إلى لوحة الألوان لونًا خاصًا بقيمة `hex` نفسها تمامًا.
- اسم العائلة الذي فيه رقم، مثل `Source Sans 3`، يحتاج إلى علامتي تنصيص في `font-family` داخل ملف SVG؛ ومن دونهما يُسقط المتصفح التعريف ويصف التسميات بخط ذي زوائد.

## الحقوق

- الوصفة: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- الصور: The river from the air, on the cover: Generated With Diffusion Models, أصلي
- الصور: The director on the river bank: Generated With Diffusion Models, أصلي
- الصور: Volunteers planting willow stakes: Generated With Diffusion Models, أصلي
- الصور: A water sample at a gauging station: Generated With Diffusion Models, أصلي
- الصور: A kingfisher on a willow branch: Generated With Diffusion Models, أصلي
- الخطوط: Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)
- الشيفرة: MIT · محتوى المثال: CC-BY-4.0

## وصفات ذات صلة

- [رقم 037 · تقرير سنوي بأعمدة تنتهي على سطر واحد](https://postext.dev/ar/cookbook/annual-report-flush-columns.md): التقرير السنوي لتعاونية طاقة في عمودين مضبوطين ينتهيان على السطر نفسه من الشبكة، مع إطار للأرقام الرئيسية بعرض الصفحة وصفحة ختامية مقطوعة على مستوى واحد. · المستوى 3 (متقدم) · التقارير
- [رقم 024 · PDF جاهز للطباعة: النزف وعلامات القص وPDF/X](https://postext.dev/ar/cookbook/print-ready-pdf.md): مطوية معرض بنزف 3 مم وعلامات قص، مصدَّرة إلى PDF/X-4 على FOGRA51 مع نُسخ طباعة أصلية، ويمر الفحص قبل الطباعة دون ملاحظات. · المستوى 3 (متقدم) · الأوراق المفردة والمطبوعات العابرة
- [رقم 039 · ملف PDF موسوم ومتاح للجميع (PDF/UA)](https://postext.dev/ar/cookbook/accessible-tagged-pdf.md): دليل لإعادة التدوير يُصدَّر ملف PDF/UA-1 موسومًا فيه نص بديل وخلايا عناوين للجداول ولغة المستند ومحتويات مرتبطة، وترسم المعاينة الوسوم على الصفحة 3. · المستوى 2 (متوسط) · التقارير
