# 给企业标准色加印第五色

> 四色加一个准确的企业Pantone：油墨表把蓝色的每一个名称都归到同一块印版PANTONE 286 C上。

- HTML版本: https://postext.dev/zh/cookbook/corporate-fifth-ink-report
- 食谱 No. 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
- 在沙盒中打开: https://postext.dev/zh/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), [ja](https://postext.dev/ja/cookbook/corporate-fifth-ink-report.md), [ar](https://postext.dev/ar/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/zh/docs/configuration-pdf-output.md#专色): 模型为 'spot' 的颜色按其网点百分比印在自己的印版上。油墨表按印厂的叫法命名印版，并把调色板、SVG 和导入文件给同一种油墨起的其他名字合并到这块版上。
- [CMYK与灰度PDF](https://postext.dev/zh/docs/configuration-fonts-colors-viewers.md#pdf生成配置): 颜色带有色彩模型（hex、rgb、cmyk、hsl），PDF可以强制转为CMYK或灰度，交付印厂或做校样。

**还用到**

- [语义调色板](https://postext.dev/zh/docs/configuration-fonts-colors-viewers.md#调色板)
- [封面、扉页和版权页](https://postext.dev/zh/docs/configuration-styles.md#标题样式)
- [设计过的章首页](https://postext.dev/zh/docs/configuration-headings.md#通栏与高级设计)
- [页面设计中的文字、线条和框](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚)
- [页面设计中的图片](https://postext.dev/zh/docs/configuration-headers-footers.md#图像元素)
- [标注框](https://postext.dev/zh/docs/configuration-callouts.md#标注框样式)
- [表格样式](https://postext.dev/zh/docs/configuration-resources.md#表格样式)
- [作为资源的图和表](https://postext.dev/zh/docs/document-format-resources.md#资源)
- [导出PDF](https://postext.dev/zh/docs/configuration-pdf-output.md#生成pdf)
- [在Canvas上绘制页面](https://postext.dev/zh/docs/configuration-programmatic-usage.md#把页面渲染为位图)
- [框内或正文中的分栏](https://postext.dev/zh/docs/document-format-directives.md#columns)
- [单元格填色](https://postext.dev/zh/docs/document-format-resources.md#块级嵌入可选显式的行内放置)
- [决定图位置的引用](https://postext.dev/zh/docs/document-format-resources.md#行内引用主要写法)
- [标题属性](https://postext.dev/zh/docs/document-format.md#标题属性)
- [标题样式](https://postext.dev/zh/docs/configuration-styles.md#标题样式)
- [图就放在这里](https://postext.dev/zh/docs/document-format-resources.md#块级嵌入可选显式的行内放置)
- [通栏章首色带](https://postext.dev/zh/docs/configuration-headings.md#通栏与高级设计)
- [纸张颜色](https://postext.dev/zh/docs/configuration-page-layout.md#页面)
- [段落样式](https://postext.dev/zh/docs/configuration-styles.md#段落样式)
- [嵌入PDF的字体](https://postext.dev/zh/docs/configuration-pdf-output.md#为什么需要字体提供函数)
- [自定义资源类型](https://postext.dev/zh/docs/configuration-resources.md#资源类型)
- [分节版式](https://postext.dev/zh/docs/configuration-styles.md#标题样式)
- [分节书眉](https://postext.dev/zh/docs/configuration-styles.md#标题样式)
- [横跨页面的框](https://postext.dev/zh/docs/configuration-callouts.md#callout容器)
- [由数据生成的表](https://postext.dev/zh/docs/document-format-resources.md#块级嵌入可选显式的行内放置)
- [不编号的章](https://postext.dev/zh/docs/configuration-styles.md#标题样式)

**配置一览**

- [`bodyText`](https://postext.dev/zh/docs/configuration-text.md#正文), [`calloutStyles`](https://postext.dev/zh/docs/configuration-callouts.md#标注框样式), [`captionStyle`](https://postext.dev/zh/docs/configuration-resources.md#题注样式), [`colorPalette`](https://postext.dev/zh/docs/configuration-fonts-colors-viewers.md#调色板), [`footer`](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚), [`header`](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚), [`headingStyles`](https://postext.dev/zh/docs/configuration-styles.md#标题样式), [`headings`](https://postext.dev/zh/docs/configuration-headings.md#标题), [`layout`](https://postext.dev/zh/docs/configuration-page-layout.md#版式), [`locale`](https://postext.dev/zh/docs/configuration-language.md#断词), [`page`](https://postext.dev/zh/docs/configuration-page-layout.md#页面), [`paragraphStyles`](https://postext.dev/zh/docs/configuration-styles.md#段落样式), [`print`](https://postext.dev/zh/docs/configuration-fonts-colors-viewers.md#印刷输出配置), [`resourceTypes`](https://postext.dev/zh/docs/configuration-resources.md#资源类型), [`tableStyle`](https://postext.dev/zh/docs/configuration-resources.md#表格样式), [`unorderedLists`](https://postext.dev/zh/docs/configuration-lists-math.md#无序列表)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/zh/docs/configuration-programmatic-usage.md#排版前加载字体), [`decompressWoff2`](https://postext.dev/zh/docs/configuration-pdf-output.md#浏览器字体提供函数fontsource--woff2), [`inlineSvgFonts`](https://postext.dev/zh/docs/configuration-resources.md#svg文字中的字体), [`parseTSV`](https://postext.dev/zh/docs/document-format-resources.md#块级嵌入可选显式的行内放置), [`registerResourceImage`](https://postext.dev/zh/docs/architecture.md#api接口), [`renderPageToCanvas`](https://postext.dev/zh/docs/configuration-programmatic-usage.md#把页面渲染为位图), [`renderToPdf`](https://postext.dev/zh/docs/configuration-pdf-output.md#生成pdf), [`setAlignment`](https://postext.dev/zh/docs/document-format-resources.md#块级嵌入可选显式的行内放置), [`setCellBackground`](https://postext.dev/zh/docs/document-format-resources.md#块级嵌入可选显式的行内放置)

**字体**

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

## 做法

### 1 · 一种油墨，三个名称

代码就是上面的[简短回答](https://postext.dev/zh/cookbook/corporate-fifth-ink-report.md#简短回答)。蓝色带着三个名称进入这份报告，真实的活儿里也常这样：设计师的色板叫`Brand Blue`，一套旧调色板给40 %色调写的是`Pantone 286C`，西班牙办公室画的图表则写`Azul Cauce`。没有油墨表的话，每个名称都会单独出一块印版，印刷厂会收到三种要调的蓝。[油墨表](https://postext.dev/zh/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`以百分比说明浓度。图表的柱子写的是100 %和40 %的`Azul Cauce`，别名把它们放到和其余蓝色同一块印版上。网格线和标签是普通颜色，留在四色黑里。财务页上的支出长条也一样，分三段，第三段是四色灰。

### 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`让照片保持为带sRGB标签的RGB JPEG，PDF/X-4允许这样做；由印刷厂的RIP来分色。文件很小，蓝色印版上也不会沾到照片的任何东西。

## 完整食谱

一个文件，由食谱文件夹合成，示例文本和排版食谱的公共工具包都已内联；它自己排出页面。要运行它，把它放进空白页面的`<script type="module">`，或粘贴到新建CodePen的JS面板里（设为模块）。它从esm.sh导入postext，不需要安装或构建。

- 食谱文件夹: 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`，在SVG的`font-family`里要加引号；不加的话浏览器会丢掉这条声明，用衬线体排标签。

## 致谢

- 食谱: 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

## 相关食谱

- [No. 037 · 各栏齐底的年度报告](https://postext.dev/zh/cookbook/annual-report-flush-columns.md): 一家能源合作社的年度报告，两栏两端对齐的正文都止于同一条网格线，一个关键数据框横跨页面，末页各栏齐平收尾。 · 难度 3 (高级) · 报告
- [No. 024 · 可付印的PDF：出血、裁切线与PDF/X](https://postext.dev/zh/cookbook/print-ready-pdf.md): 一份展览导览单，带3 mm出血和裁切线，连同印刷母版导出为按FOGRA51分色的PDF/X-4，印前检查没有发现问题。 · 难度 3 (高级) · 单页与零散印品
- [No. 039 · 带标签的无障碍PDF（PDF/UA）](https://postext.dev/zh/cookbook/accessible-tagged-pdf.md): 一份垃圾分类指南，导出为符合PDF/UA-1的带标签PDF，带替代文字、表头单元格、文档语言和可跳转的目录；预览在第3页上画出了各个标签。 · 难度 2 (中级) · 报告
