# Una quinta tinta para el color corporativo

> Cuatricromía más un Pantone corporativo exacto: la tabla de tintas reúne en una plancha, PANTONE 286 C, cada nombre que recibe el azul.

- Versión HTML: https://postext.dev/es/cookbook/corporate-fifth-ink-report
- Receta N.º 189 · Salida e integración · Nivel 3 (Avanzado) · Salidas: Canvas, PDF
- Géneros: Informes y memorias
- Requiere postext ≥ 1.84.0, postext-pdf ≥ 1.84.0 · probada con 1.84.0, postext-pdf 1.84.0 el 2026-11-13
- Páginas: [1](https://postext.dev/cookbook/corporate-fifth-ink-report/es/p01.webp?v=aec18c8a), [2](https://postext.dev/cookbook/corporate-fifth-ink-report/es/p02.webp?v=aec18c8a), [3](https://postext.dev/cookbook/corporate-fifth-ink-report/es/p03.webp?v=aec18c8a), [4](https://postext.dev/cookbook/corporate-fifth-ink-report/es/p04.webp?v=aec18c8a), [5](https://postext.dev/cookbook/corporate-fifth-ink-report/es/p05.webp?v=aec18c8a), [6](https://postext.dev/cookbook/corporate-fifth-ink-report/es/p06.webp?v=aec18c8a), [7](https://postext.dev/cookbook/corporate-fifth-ink-report/es/p07.webp?v=aec18c8a), [8](https://postext.dev/cookbook/corporate-fifth-ink-report/es/p08.webp?v=aec18c8a)
- PDF: https://postext.dev/cookbook/corporate-fifth-ink-report/es/corporate-fifth-ink-report.pdf?v=aec18c8a
- Abrir en el Sandbox: https://postext.dev/es/sandbox#recipe=corporate-fifth-ink-report&lang=es (.postext: https://postext.dev/cookbook/corporate-fifth-ink-report/es/corporate-fifth-ink-report.postext)
- Última actualización: 2026-11-13
- Otros idiomas: [en](https://postext.dev/en/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)

## En pocas palabras

Una memoria anual de una fundación que cuida un río, impresa con las cuatro tintas de siempre y un azul exacto que es el color de la fundación. Cada archivo llama al azul de una manera, y el de imprenta lo pone todo en una plancha.

## Lo que vas a componer

Una memoria anual de ocho páginas A4 para una fundación inventada que restaura un río, impresa a cuatro tintas y una quinta, su azul corporativo. El azul está donde lo pondría una marca: la franja de la cubierta, la barra sobre cada sección, los títulos, las cabeceras de tabla, las barras del gráfico y la contracubierta. Sus tintes al 40 % y al 12 % rellenan las barras previstas, las filas de total y la caja de cifras, y se imprimen como tramas de la misma tinta, nunca como una mezcla de cuatricromía. Las fotografías y el texto van en cuatricromía. El PDF/X-4 tiene cinco planchas, y la quinta lleva el nombre con que el impresor guarda la tinta, `PANTONE 286 C`, aunque en el diseño nada la llama así.

**Esta receta responde a:**

- ¿Cómo imprimo una memoria a cuatro tintas y nuestro Pantone si cada archivo llama a la tinta de una manera?

## La respuesta corta

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

## Ingredientes

**Enseña**

- [Tintas planas y tabla de tintas](https://postext.dev/es/docs/configuration-pdf-output.md#tintas-planas): Un color con modelo 'spot' se imprime en su propia plancha, a su porcentaje. La tabla de tintas nombra la plancha como la conoce el impresor y reúne los otros nombres que la paleta, los SVG y los archivos importados dan a la misma tinta.
- [PDF en CMYK y en escala de grises](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#generación-de-pdf-configuración): Los colores llevan su modelo (hex, rgb, cmyk, hsl) y el PDF puede forzarse a CMYK o a escala de grises para la imprenta o una prueba.

**También usa**

- [Paleta de color semántica](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores)
- [Cubiertas, portadas y colofones](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Aperturas diseñadas](https://postext.dev/es/docs/configuration-headings.md#apertura-a-toda-página-y-diseño-avanzado)
- [Textos, filetes y cajas en los diseños de página](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies)
- [Imágenes en los diseños de página](https://postext.dev/es/docs/configuration-headers-footers.md#elementos-de-imagen)
- [Recuadros](https://postext.dev/es/docs/configuration-callouts.md#estilos-de-recuadro)
- [Estilo de tablas](https://postext.dev/es/docs/configuration-resources.md#estilo-de-tablas)
- [Figuras y tablas como recursos](https://postext.dev/es/docs/document-format-resources.md#recursos)
- [Exportación a PDF](https://postext.dev/es/docs/configuration-pdf-output.md#generación-de-pdf)
- [Páginas en un canvas](https://postext.dev/es/docs/configuration-programmatic-usage.md#renderizar-una-página-como-mapa-de-bits)
- [Columnas en un recuadro o en el texto](https://postext.dev/es/docs/document-format-directives.md#columns)
- [Rellenos de celda](https://postext.dev/es/docs/document-format-resources.md#inserción-en-bloque-opcional-colocación-en-línea-explícita)
- [Citas que colocan las figuras](https://postext.dev/es/docs/document-format-resources.md#referencia-en-línea-la-forma-principal)
- [Atributos de título](https://postext.dev/es/docs/document-format.md#atributos-de-encabezado)
- [Estilos de título](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Figuras justo aquí](https://postext.dev/es/docs/document-format-resources.md#inserción-en-bloque-opcional-colocación-en-línea-explícita)
- [Banda de capítulo a todo el ancho](https://postext.dev/es/docs/configuration-headings.md#apertura-a-toda-página-y-diseño-avanzado)
- [Color del papel](https://postext.dev/es/docs/configuration-page-layout.md#página)
- [Estilos de párrafo](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo)
- [Fuentes incrustadas en el PDF](https://postext.dev/es/docs/configuration-pdf-output.md#por-qué-un-proveedor-de-fuentes)
- [Tipos de recurso propios](https://postext.dev/es/docs/configuration-resources.md#tipos-de-recurso)
- [Geometría por sección](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Cabeceras por sección](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Recuadros a todo el ancho](https://postext.dev/es/docs/configuration-callouts.md#el-contenedor-callout)
- [Tablas a partir de datos](https://postext.dev/es/docs/document-format-resources.md#inserción-en-bloque-opcional-colocación-en-línea-explícita)
- [Capítulos sin número](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)

**La configuración de un vistazo**

- [`bodyText`](https://postext.dev/es/docs/configuration-text.md#texto-base), [`calloutStyles`](https://postext.dev/es/docs/configuration-callouts.md#estilos-de-recuadro), [`captionStyle`](https://postext.dev/es/docs/configuration-resources.md#estilo-de-pies-de-recurso), [`colorPalette`](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores), [`footer`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`header`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`headingStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado), [`headings`](https://postext.dev/es/docs/configuration-headings.md#encabezados), [`layout`](https://postext.dev/es/docs/configuration-page-layout.md#disposición), [`locale`](https://postext.dev/es/docs/configuration-language.md#separación-silábica), [`page`](https://postext.dev/es/docs/configuration-page-layout.md#página), [`paragraphStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo), [`print`](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#producción-para-imprenta-configuración), [`resourceTypes`](https://postext.dev/es/docs/configuration-resources.md#tipos-de-recurso), [`tableStyle`](https://postext.dev/es/docs/configuration-resources.md#estilo-de-tablas), [`unorderedLists`](https://postext.dev/es/docs/configuration-lists-math.md#listas-no-ordenadas)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/es/docs/configuration-programmatic-usage.md#cargar-las-fuentes-antes-de-componer), [`decompressWoff2`](https://postext.dev/es/docs/configuration-pdf-output.md#proveedor-de-fuentes-en-el-navegador-fontsource--woff2), [`inlineSvgFonts`](https://postext.dev/es/docs/configuration-resources.md#fuentes-en-el-texto-de-los-svg), [`parseTSV`](https://postext.dev/es/docs/document-format-resources.md#inserción-en-bloque-opcional-colocación-en-línea-explícita), [`registerResourceImage`](https://postext.dev/es/docs/architecture.md#api-pública), [`renderPageToCanvas`](https://postext.dev/es/docs/configuration-programmatic-usage.md#renderizar-una-página-como-mapa-de-bits), [`renderToPdf`](https://postext.dev/es/docs/configuration-pdf-output.md#generación-de-pdf), [`setAlignment`](https://postext.dev/es/docs/document-format-resources.md#inserción-en-bloque-opcional-colocación-en-línea-explícita), [`setCellBackground`](https://postext.dev/es/docs/document-format-resources.md#inserción-en-bloque-opcional-colocación-en-línea-explícita)

**Tipografías**

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

## Elaboración

### 1 · Una tinta con tres nombres

El código es [la respuesta corta](https://postext.dev/es/cookbook/corporate-fifth-ink-report.md#la-respuesta-corta) de arriba. El azul llega a la memoria con tres nombres, como pasa en los trabajos de verdad: la muestra del diseñador dice `Brand Blue`, una paleta antigua escribió `Pantone 286C` para el tinte al 40 %, y el gráfico, dibujado en la oficina de España, dice `Azul Cauce`. Sin tabla de tintas cada nombre saldría en su propia plancha, y el impresor recibiría tres azules que mezclar. La entrada de la [tabla de tintas](https://postext.dev/es/docs/configuration-pdf-output.md#tintas-planas) da nombre a la plancha y pone los demás como alias; los nombres se comparan sin mirar mayúsculas ni espacios, así que cada tinte de cada nombre cae en la única separación `PANTONE 286 C`. Su `cmyk` es la alternativa que enseña una prueba.

### 2 · El gráfico nombra su tinta

```js
// script.js, líneas 327–370
// 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>`;
}
```

Un SVG dice en qué tinta se imprime un color con `data-spot`, y con qué fuerza con `data-spot-tint`, en porcentaje. Las barras del gráfico nombran `Azul Cauce` al 100 % y al 40 %, y el alias las pone en la misma plancha que el resto del azul. Las líneas de la rejilla y las etiquetas son colores corrientes y quedan en el negro de cuatricromía. La barra de gastos de la página de cuentas hace lo mismo con tres tramos, el tercero un gris de cuatricromía.

### 3 · El azul lleva el diseño

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

La foto de cubierta llena la parte alta del sangrado con `fit: 'cover'`, y una caja en el azul llena el resto; la letra encima es blanca y calada en la plancha. Las barras de sección, los pies de página y las cabeceras de tabla usan la misma entrada de la paleta, así que cambiar de tinta es una línea.

```js
// script.js, líneas 314–323
// 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;
}
```

Las tablas salen de archivos TSV junto al texto. Una fila cuya primera celda va en negrita es un total y toma el tinte al 12 %; las cifras van a la derecha.

### 4 · Las fotografías siguen en RGB

`convertImages: false` en los ajustes de impresión deja las fotografías como JPEG en RGB con perfil sRGB, que PDF/X-4 admite; el RIP del impresor las separa. El archivo queda ligero, y la plancha azul no recibe nada de las fotos.

## La receta completa

Un solo archivo, compuesto a partir de la carpeta de la receta con el texto de ejemplo y el kit común del Recetario ya incluidos; construye su propia página. Para ejecutarlo, ponlo en un `<script type="module">` de una página vacía o pégalo en el panel JS de un pen nuevo de CodePen (como módulo). Importa postext desde esm.sh, así que no hay nada que instalar ni compilar.

- Carpeta de la receta: 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 = 'es'; // @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: "Memoria anual 2025"
author: "Fundación Cauce"
---

# Memoria anual 2025 {style="cover" strap="Devolver al Alcarrán el sitio que necesita para volver a ser un río" credit="La Fundación Cauce y el valle del Alcarrán son inventados, como cada nombre y cada cifra de esta memoria. Fotografías generadas con modelos de difusión."}

# Un río con sitio {kicker="Carta de la directora" lead="Restauramos 9,8 kilómetros de orilla, más que en ningún año desde que nació la fundación, y el río respondió con el agua más limpia que hemos medido."}

::resource{id="director"}

Cuando se creó la fundación, en 2014, el Alcarrán corría entre motas de tierra levantadas con excavadoras después de las riadas de los años setenta. Le habían sacado la grava y talado los chopos, y en verano tramos enteros por debajo de Valtierra se quedaban quietos y verdes. Diez años después, un paseo por esas mismas orillas cuenta otra historia. En 2025 derribamos otras dos motas, plantamos 41.000 sauces, alisos y fresnos, y devolvimos al río 64 hectáreas de llanura donde puede extenderse cuando crece.

Nada de esto habría pasado sin los 1.240 voluntarios que salieron los sábados de frío a plantar, a arrancar caña invasora y a contar aves, ni sin los 37 agricultores que aceptaron dejar asilvestrarse una franja de su tierra junto al agua. Varios nos dijeron este año que el río les inunda ahora los campos menos que antes, no más, porque el agua tiene otro sitio adonde ir.

Las muestras mensuales de nueve estaciones enseñan el resultado. El nitrato bajó por cuarto año seguido, el oxígeno disuelto de agosto se mantuvo por primera vez en todas las estaciones por encima del que necesita la trucha, y la nutria, desaparecida del valle medio desde los años ochenta, dejó sus huellas en Fuentelsaz en octubre.

:::callout{type="figures" span="page" title="2025 en tres cifras"}
:::columns{count=3 breaks="3,5"}
:::paragraphs{style="figure"}
**9,8 km**
:::

de orilla restaurada, frente a 7,4 en 2024

:::paragraphs{style="figure"}
**41.000**
:::

árboles y arbustos autóctonos plantados por voluntarios

:::paragraphs{style="figure"}
**1,86 M€**
:::

invertidos en el río, 87 céntimos de cada euro recaudado
:::
:::

El año que viene empezamos el tramo más difícil de todos, los cuatro kilómetros que cruzan el propio pueblo de Alcarrán, donde el río corre por un canal de hormigón. El ayuntamiento nos ha cedido los terrenos; el proyecto está listo. Espero que lo recorráis con nosotros.

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

# Trabajo a lo largo del río {kicker="Proyectos" lead="Dos motas derribadas, tres brazos secundarios abiertos de nuevo y un azud retirado en el viejo molino de Somaén."}

La fundación trabaja por tramos: unos pocos kilómetros en los que la tierra de las dos orillas es de propietarios que han aceptado el plan. En 2025 trabajamos en cinco (:ref{id="projects"}), desde la cabecera por encima de Fuentelsaz hasta la confluencia con el Jalón, y restauramos más orilla que en ningún año anterior (:ref{id="banks"}).

## Motas y brazos secundarios

En Valtierra y Maluenda, las máquinas retiraron 2,6 kilómetros de mota de tierra y extendieron el material sobre los antiguos campos, de modo que la orilla baja ahora suave hasta el agua en lugar de alzarse como un muro. Por debajo de Valtierra el río había abierto tres brazos secundarios antes de que lo canalizaran; los recuperamos, y con las crecidas de otoño volvían a llevar agua.

## El azud de Somaén

El azud del viejo molino harinero, de 2,3 metros de alto, impedía a los peces remontar el río desde 1904. Los dueños del molino nos lo cedieron en 2024, y en julio una cuadrilla lo desmontó en tres semanas de aguas bajas. En diciembre el río ya había arrastrado aguas abajo el sedimento retenido y había dibujado una sucesión de rápidos y pozas donde estaba la balsa.

## Plantación

Los voluntarios plantaron 41.000 árboles y arbustos en 46 jornadas entre noviembre y marzo, todos criados en el valle de estaquillas y semillas. La orilla restaurada cada año ha crecido sin parar desde 2021, y por primera vez superó lo que pedía el plan.

# Día de plantación {style="plate" quote="Vinimos un sábado de 2019. Ahora los sauces que plantamos son más altos que nuestros hijos, y el río corre limpio bajo ellos." who="Marta y Jorge Sanz, voluntarios en Valtierra" caption="Voluntarios plantando estacas de sauce en la orilla de Valtierra, en marzo."}

# Agua más limpia {kicker="Salud del río" lead="Nueve estaciones, muestreadas cada mes por voluntarios y comprobadas dos veces al año por un laboratorio independiente."}

La calidad del agua es la medida que más nos importa, porque nos dice si el río funciona como un río. Los voluntarios muestrean nueve estaciones el primer domingo de cada mes y miden en la orilla la temperatura, el oxígeno disuelto, el nitrato y el fosfato. Dos veces al año un laboratorio independiente toma sus propias muestras en los mismos puntos, y desde 2022 las dos series de lecturas coinciden con una diferencia inferior al 5 %.

::resource{id="sample"}

El nitrato bajó a una media de 11 miligramos por litro, desde 19 en 2021 (:ref{id="water"}). La mayor bajada fue por debajo de Maluenda, donde una franja de sauces se interpone ahora entre el río y los campos que drenan en él. El fosfato baja más despacio, porque buena parte está en el sedimento antiguo y se libera cuando el río lo mueve.

En agosto, el mes más duro para un río de este valle, el oxígeno disuelto se mantuvo por encima de 7 miligramos por litro en todas las estaciones. La trucha necesita unos 6. Un muestreo del servicio regional de pesca en septiembre encontró trucha común en siete de las nueve estaciones, frente a tres en 2021.

# Cuentas {kicker="Finanzas" lead="Los ingresos crecieron un 11 %, y 87 céntimos de cada euro fueron al trabajo en el río y a las escuelas."}

Los ingresos de la fundación en el año fueron 2,14 millones de euros (:ref{id="accounts"}). Los socios mensuales aportaron 1,12 millones, un 6 % más que en 2024. Las subvenciones públicas y el nuevo convenio con la empresa regional de aguas sumaron 0,81 millones, y el resto llegó de herencias y de la venta de estaquillas de sauce a otros proyectos.

Gastamos 2,04 millones de euros (:ref{id="euro"}). Las obras en el río, del movimiento de tierras al vivero, se llevaron 1,52 millones, y el programa escolar, que trajo al río a 3.100 alumnos este año, 0,34 millones. La administración y la captación de fondos costaron 0,18 millones, el 9 % del gasto. El superávit de 0,10 millones va a la reserva para las obras en el pueblo de Alcarrán.

Las cuentas las auditó una firma independiente y las aprobó el patronato el 12 de marzo de 2026. Las cuentas completas pueden pedirse en la oficina de la fundación.

# Gracias {kicker="Apoyos" lead="El trabajo de la fundación descansa en las personas y entidades que en 2025 dieron su tiempo, su tierra y su dinero."}

::resource{id="kingfisher"}

Damos las gracias a los 6.800 socios mensuales que nos dan libertad para planificar con años de antelación, y a los 1.240 voluntarios que dedicaron 19.600 horas al río. Gracias a los 37 agricultores y propietarios que firmaron acuerdos para dejar que la orilla se asilvestre, y a las familias que legaron a la fundación parte de su herencia.

## Lo que vimos

Los voluntarios anotaron 112 especies de aves en los tramos restaurados, entre ellas el martín pescador en los cinco, el pájaro moscón criando en los sauces de Valtierra y una pareja de cigüeñas negras comiendo en primavera en los brazos recuperados. Las huellas de la nutria en Fuentelsaz fueron su primera señal en el valle medio en cuarenta años.

## Entidades colaboradoras

- Ayuntamiento de Alcarrán
- Aguas del Valle del Jalón
- Servicio Regional de Pesca
- Universidad del Valle

# Fundación Cauce {style="back" address="Calle del Molino 14 · 50300 Alcarrán · hola@cauce.example" inks="Impreso a cuatro tintas y una quinta tinta, PANTONE 286 C, en papel reciclado no estucado."}
`; // content.<lang>.md, inlined by the Cookbook
const projects = String.raw`Proyecto	km	Voluntarios	Miles de €
Valtierra: mota retirada, tres brazos recuperados	3,4	410	612
Maluenda: mota retirada, franja de sauces	2,1	260	355
Somaén: azud del molino retirado	0,6	40	288
Fuentelsaz: cercado y plantación en cabecera	2,4	330	174
Confluencia del Jalón: caña retirada, plantación	1,3	200	91
**Todos los proyectos**	**9,8**	**1.240**	**1.520**
`; // the tables: TSV, pasted from a spreadsheet
const accounts = String.raw`Miles de €	2025	2024
Socios mensuales	1.120	1.057
Subvenciones y convenios	810	690
Herencias y otros ingresos	210	180
**Total ingresos**	**2.140**	**1.927**
Obras en el río	1.520	1.410
Programa escolar	340	300
Administración y captación de fondos	180	170
**Total gastos**	**2.040**	**1.880**
**Superávit del año**	**100**	**47**
`;
const water = String.raw`Estación	Nitrato 2021	Nitrato 2025	Oxígeno, agosto 2025
Fuentelsaz	9	6	9,1
Torrehermosa	12	8	8,6
Somaén	15	10	8,2
Valtierra, aguas arriba	18	11	7,9
Valtierra, aguas abajo	22	12	7,6
Maluenda	27	13	7,4
Puente de Alcarrán	24	14	7,2
Molino de Alcarrán	21	13	7,3
Confluencia del Jalón	23	14	7,1
**Media**	**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 ───────────────────────────────────────────────────────────────────────
```

## Variantes

### Imprime el azul en cuatricromía

Cuando la máquina no tiene quinto cuerpo, una palabra en la tabla de tintas imprime cada tinte del azul en CMYK a partir de su alternativa.

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

### Nombra la plancha para otra imprenta

Hay imprentas que quieren la plancha con su propio nombre. `pdfName` la renombra y conserva los alias.

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

## Errores frecuentes

- Un color de una imagen que ni nombra su tinta ni coincide exactamente con un color plano de la paleta queda en cuatricromía, aunque parezca el azul. Marca los elementos con `data-spot`, o da a la paleta un color plano con ese hex exacto.
- Un nombre de familia con un número, como `Source Sans 3`, necesita comillas en el `font-family` de un SVG; sin ellas, el navegador descarta la declaración y compone las etiquetas en una serif.

## Créditos

- Receta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Imágenes: El río desde el aire, en la cubierta: Generated With Diffusion Models, original
- Imágenes: La directora en la orilla: Generated With Diffusion Models, original
- Imágenes: Voluntarios plantando estacas de sauce: Generated With Diffusion Models, original
- Imágenes: Una muestra de agua en una estación de aforo: Generated With Diffusion Models, original
- Imágenes: Un martín pescador en una rama de sauce: Generated With Diffusion Models, original
- Tipografías: Source Serif 4 (OFL-1.1), Source Sans 3 (OFL-1.1)
- Código: MIT · Contenido de ejemplo: CC-BY-4.0

## Relacionadas

- [N.º 037 · Memoria anual con columnas a ras](https://postext.dev/es/cookbook/annual-report-flush-columns.md): La memoria anual de una cooperativa energética a dos columnas que acaban en la misma línea, con un recuadro de cifras a lo ancho y la última página igualada. · Nivel 3 (Avanzado) · Informes y memorias
- [N.º 024 · PDF listo para imprenta: sangrado, marcas de corte y PDF/X](https://postext.dev/es/cookbook/print-ready-pdf.md): Un folleto de exposición con 3 mm de sangrado y marcas de corte, exportado a PDF/X-4 sobre FOGRA51 con másteres de impresión y un preflight limpio. · Nivel 3 (Avanzado) · Hojas sueltas y efímeros
- [N.º 039 · PDF accesible y etiquetado (PDF/UA)](https://postext.dev/es/cookbook/accessible-tagged-pdf.md): Una guía de reciclaje en PDF/UA-1 etiquetado, con texto alternativo, celdas de cabecera, idioma e índice con enlaces; la vista previa dibuja las etiquetas. · Nivel 2 (Intermedio) · Informes y memorias
