# A fifth ink for the corporate colour

> Process colour plus one exact corporate Pantone: the ink table gathers every name the blue goes by onto one plate, PANTONE 286 C.

- HTML version: https://postext.dev/en/cookbook/corporate-fifth-ink-report
- Recipe Nº 189 · Output & integration · Level 3 (Advanced) · Outputs: Canvas, PDF
- Genres: Reports
- Requires postext ≥ 1.84.0, postext-pdf ≥ 1.84.0 · tested with 1.84.0, postext-pdf 1.84.0 on 2026-11-13
- Pages: [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
- Open in Sandbox: https://postext.dev/en/sandbox#recipe=corporate-fifth-ink-report&lang=en (.postext: https://postext.dev/cookbook/corporate-fifth-ink-report/en/corporate-fifth-ink-report.postext)
- Last updated: 2026-11-13
- Other languages: [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), [ar](https://postext.dev/ar/cookbook/corporate-fifth-ink-report.md)

## In short

An annual report for a river charity, printed in the usual four inks plus one exact blue that is the charity's own colour. Each file calls the blue by another name, and the print file still puts it all on one plate.

## What you'll build

An eight-page A4 annual report for an invented river charity, printed in four colours and one fifth ink, its corporate blue. The blue is everywhere a brand would put it: the band across the cover, the bar over each section, the headings, the table heads, the chart bars and the back cover. Its 40 % and 12 % tints fill the planned bars, the total rows and the box of key figures, and they print as screens of the same ink, never as a process mix. The photographs and the text stay in process. The PDF/X-4 file has five plates, and the fifth is named as the printer stocks the ink, `PANTONE 286 C`, although nothing in the design calls it that.

**This recipe answers:**

- How do I print a report in four colours plus our corporate Pantone when every file names the ink differently?

## The short answer

One spot ink, three names: the ink table puts them on one plate.

```js
// script.js, lines 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 }] };
```

## Ingredients

**Teaches**

- [Spot inks and the ink table](https://postext.dev/en/docs/configuration-pdf-output.md#spot-colours): A colour with model 'spot' prints on a plate of its own, at its tint. The ink table names the plate as the printer knows it and merges the other names the palette, SVGs and imported files give the same ink.
- [CMYK and grayscale PDFs](https://postext.dev/en/docs/configuration-fonts-colors-viewers.md#pdf-generation-config): Colours carry a model (hex, rgb, cmyk, hsl), and the PDF can be forced to CMYK or grayscale for the printer or a proof.

**Also uses**

- [Semantic colour palette](https://postext.dev/en/docs/configuration-fonts-colors-viewers.md#color-palette)
- [Covers, title pages and colophons](https://postext.dev/en/docs/configuration-styles.md#heading-styles)
- [Designed openers](https://postext.dev/en/docs/configuration-headings.md#span-and-advanced-design)
- [Text, rules and boxes in page designs](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers)
- [Pictures in page designs](https://postext.dev/en/docs/configuration-headers-footers.md#image-elements)
- [Callout boxes](https://postext.dev/en/docs/configuration-callouts.md#callout-styles)
- [Table style](https://postext.dev/en/docs/configuration-resources.md#table-style)
- [Figures and tables as resources](https://postext.dev/en/docs/document-format-resources.md#resources)
- [PDF export](https://postext.dev/en/docs/configuration-pdf-output.md#generating-pdfs)
- [Pages on a canvas](https://postext.dev/en/docs/configuration-programmatic-usage.md#rendering-a-page-to-a-bitmap)
- [Columns in a box or in the text](https://postext.dev/en/docs/document-format-directives.md#columns)
- [Cell fills](https://postext.dev/en/docs/document-format-resources.md#block-embed-optional-explicit-inline-placement)
- [Citations that place figures](https://postext.dev/en/docs/document-format-resources.md#inline-reference-the-primary-form)
- [Heading attributes](https://postext.dev/en/docs/document-format.md#heading-attributes)
- [Heading styles](https://postext.dev/en/docs/configuration-styles.md#heading-styles)
- [Figures exactly here](https://postext.dev/en/docs/document-format-resources.md#block-embed-optional-explicit-inline-placement)
- [Full-width chapter band](https://postext.dev/en/docs/configuration-headings.md#span-and-advanced-design)
- [Paper colour](https://postext.dev/en/docs/configuration-page-layout.md#page)
- [Paragraph styles](https://postext.dev/en/docs/configuration-styles.md#paragraph-styles)
- [Fonts embedded in the PDF](https://postext.dev/en/docs/configuration-pdf-output.md#why-a-font-provider)
- [Custom resource types](https://postext.dev/en/docs/configuration-resources.md#resource-types)
- [Section geometry](https://postext.dev/en/docs/configuration-styles.md#heading-styles)
- [Running heads per section](https://postext.dev/en/docs/configuration-styles.md#heading-styles)
- [Boxes across the page](https://postext.dev/en/docs/configuration-callouts.md#the-callout-container)
- [Tables from data](https://postext.dev/en/docs/document-format-resources.md#block-embed-optional-explicit-inline-placement)
- [Unnumbered chapters](https://postext.dev/en/docs/configuration-styles.md#heading-styles)

**Config at a glance**

- [`bodyText`](https://postext.dev/en/docs/configuration-text.md#body-text), [`calloutStyles`](https://postext.dev/en/docs/configuration-callouts.md#callout-styles), [`captionStyle`](https://postext.dev/en/docs/configuration-resources.md#caption-style), [`colorPalette`](https://postext.dev/en/docs/configuration-fonts-colors-viewers.md#color-palette), [`footer`](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers), [`header`](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers), [`headingStyles`](https://postext.dev/en/docs/configuration-styles.md#heading-styles), [`headings`](https://postext.dev/en/docs/configuration-headings.md#headings), [`layout`](https://postext.dev/en/docs/configuration-page-layout.md#layout), [`locale`](https://postext.dev/en/docs/configuration-language.md#hyphenation), [`page`](https://postext.dev/en/docs/configuration-page-layout.md#page), [`paragraphStyles`](https://postext.dev/en/docs/configuration-styles.md#paragraph-styles), [`print`](https://postext.dev/en/docs/configuration-fonts-colors-viewers.md#print-production-config), [`resourceTypes`](https://postext.dev/en/docs/configuration-resources.md#resource-types), [`tableStyle`](https://postext.dev/en/docs/configuration-resources.md#table-style), [`unorderedLists`](https://postext.dev/en/docs/configuration-lists-math.md#unordered-lists)

**APIs**

- [`buildDocumentWithFonts`](https://postext.dev/en/docs/configuration-programmatic-usage.md#loading-fonts-before-layout), [`decompressWoff2`](https://postext.dev/en/docs/configuration-pdf-output.md#browser-font-provider-fontsource--woff2), [`inlineSvgFonts`](https://postext.dev/en/docs/configuration-resources.md#fonts-in-svg-text), [`parseTSV`](https://postext.dev/en/docs/document-format-resources.md#block-embed-optional-explicit-inline-placement), [`registerResourceImage`](https://postext.dev/en/docs/architecture.md#api-surface), [`renderPageToCanvas`](https://postext.dev/en/docs/configuration-programmatic-usage.md#rendering-a-page-to-a-bitmap), [`renderToPdf`](https://postext.dev/en/docs/configuration-pdf-output.md#generating-pdfs), [`setAlignment`](https://postext.dev/en/docs/document-format-resources.md#block-embed-optional-explicit-inline-placement), [`setCellBackground`](https://postext.dev/en/docs/document-format-resources.md#block-embed-optional-explicit-inline-placement)

**Typefaces**

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

## Method

### 1 · One ink under three names

The code is [the short answer](https://postext.dev/en/cookbook/corporate-fifth-ink-report.md#the-short-answer) above. The blue reaches the report under three names, as it does in real jobs: the designer's swatch says `Brand Blue`, an older palette wrote `Pantone 286C` for the 40 % tint, and the chart, drawn by the Spanish office, says `Azul Cauce`. Without an ink table each name would print on a plate of its own, and the printer would get three blues to mix. The [ink table](https://postext.dev/en/docs/configuration-pdf-output.md#spot-colours) entry names the plate and lists the other names as aliases; names match ignoring case and spaces, so every tint of every name lands on the one `PANTONE 286 C` separation. Its `cmyk` is the alternate a proof shows.

### 2 · The chart names its ink

```js
// script.js, lines 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>`;
}
```

An SVG says which ink a colour prints on with `data-spot`, and how strong with `data-spot-tint`, in percent. The bars of the chart name `Azul Cauce` at 100 % and at 40 %, and the alias puts them on the same plate as the rest of the blue. The grid lines and labels are plain colours and stay in process black. The bar of spending on the accounts page does the same with three segments, the third a process grey.

### 3 · The blue carries the design

```js
// script.js, lines 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) })),
  ] } } };
```

The cover photograph fills the top of the bleed with `fit: 'cover'`, and a box in the blue fills the rest; the type on it is white, which knocks out of the plate. The section bars, the running feet and the table heads use the same palette entry, so a change of ink is one line.

```js
// script.js, lines 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;
}
```

The tables come from TSV files next to the text. A row whose first cell is bold is a total and takes the 12 % tint; figures set right.

### 4 · The photographs stay in RGB

`convertImages: false` in the print settings keeps the photographs as RGB JPEGs tagged sRGB, which PDF/X-4 allows; the printer's RIP separates them. The file stays small, and the blue plate gets nothing from the photographs.

## The whole recipe

One file, composed from the recipe's folder with the sample text and the Cookbook's shared kit inlined; it builds its own page. To run it, put it in a `<script type="module">` on an empty page, or paste it into the JS panel of a new CodePen (as a module). It imports postext from esm.sh, so there is nothing to install or build.

- Source folder: 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 ───────────────────────────────────────────────────────────────────────
```

## Variations

### Print the blue in process

When the press has no fifth unit, one word in the ink table prints every tint of the blue in CMYK from its alternate.

```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' }] };
```

### Name the plate for another printer

Some printers want the plate under their own name. `pdfName` renames it and keeps the aliases.

```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'],
```

## Pitfalls

- A colour in a picture that neither names its ink nor matches a palette spot colour exactly stays in process, even when it looks like the blue. Mark the elements with `data-spot`, or give the palette a spot colour with exactly that hex.
- A family name with a digit, such as `Source Sans 3`, needs quotes in an SVG's `font-family`; unquoted, the browser drops the declaration and sets the labels in a serif.

## Credits

- Recipe: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Images: The river from the air, on the cover: Generated With Diffusion Models, original
- Images: The director on the river bank: Generated With Diffusion Models, original
- Images: Volunteers planting willow stakes: Generated With Diffusion Models, original
- Images: A water sample at a gauging station: Generated With Diffusion Models, original
- Images: A kingfisher on a willow branch: Generated With Diffusion Models, original
- Type: Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)
- Code: MIT · Sample content: CC-BY-4.0

## Related

- [Nº 037 · Annual report with flush columns](https://postext.dev/en/cookbook/annual-report-flush-columns.md): An energy co-op's annual report in two justified columns that end on the same grid line, with a key-figures box across the page and a closing page cut level. · Level 3 (Advanced) · Reports
- [Nº 024 · Print-ready PDF: bleed, crop marks and PDF/X](https://postext.dev/en/cookbook/print-ready-pdf.md): An exhibition leaflet with 3 mm of bleed and crop marks, exported as PDF/X-4 on FOGRA51 with print masters and a clean preflight. · Level 3 (Advanced) · Single sheets & ephemera
- [Nº 039 · Accessible tagged PDF (PDF/UA)](https://postext.dev/en/cookbook/accessible-tagged-pdf.md): A recycling guide exported as a tagged PDF/UA-1 file with alt text, table header cells, its language and linked contents; the preview draws the tags on page 3. · Level 2 (Intermediate) · Reports
