# 印在版心内、到裁切线和出血的艺术图版

> 一篇关于维米尔四幅室内画的展览文章：每幅画都是整页图版，或在版心内，或到裁切线，或印到出血；另有一幅宽60毫米的局部。

- HTML版本: https://postext.dev/zh/cookbook/art-plates-to-the-bleed
- 食谱 No. 183 · 图与图片 · 难度 2 (中级) · 输出: Canvas, PDF
- 体裁: 目录册
- 需要 postext ≥ 1.73.0, postext-pdf ≥ 1.73.0 · 已用 1.73.0, postext-pdf 1.73.0 测试，日期 2026-11-10
- 页面: [1](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p01.webp?v=98cf96f7), [2](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p02.webp?v=98cf96f7), [3](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p03.webp?v=98cf96f7), [4](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p04.webp?v=98cf96f7), [5](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p05.webp?v=98cf96f7), [6](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p06.webp?v=98cf96f7), [7](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p07.webp?v=98cf96f7)
- PDF: https://postext.dev/cookbook/art-plates-to-the-bleed/en/art-plates-to-the-bleed.pdf?v=98cf96f7
- 在沙盒中打开: https://postext.dev/zh/sandbox#recipe=art-plates-to-the-bleed&lang=en (.postext: https://postext.dev/cookbook/art-plates-to-the-bleed/en/art-plates-to-the-bleed.postext)
- 最后更新: 2026-11-10
- 其他语言: [en](https://postext.dev/en/cookbook/art-plates-to-the-bleed.md), [es](https://postext.dev/es/cookbook/art-plates-to-the-bleed.md), [ca](https://postext.dev/ca/cookbook/art-plates-to-the-bleed.md), [de](https://postext.dev/de/cookbook/art-plates-to-the-bleed.md), [fr](https://postext.dev/fr/cookbook/art-plates-to-the-bleed.md), [it](https://postext.dev/it/cookbook/art-plates-to-the-bleed.md), [pt](https://postext.dev/pt/cookbook/art-plates-to-the-bleed.md), [ja](https://postext.dev/ja/cookbook/art-plates-to-the-bleed.md), [ar](https://postext.dev/ar/cookbook/art-plates-to-the-bleed.md)

## 简单来说

说明每幅画在页面上铺到哪里：版心内、裁切线，还是越过裁切线；再用毫米给局部定宽。页面会自己排好。

## 成品一览

一本160 × 195毫米小型展览图录的七页，内容是荷兰国家博物馆、大都会艺术博物馆和美国国家美术馆收藏的四幅约翰内斯·维米尔室内画。文章从右页开始，标题下沉。文中提到的每幅画都单独占下一个完整的页面：《倒牛奶的女仆》在[第2页](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p02.webp?v=98cf96f7)，位于版心内，书眉照常；《拿水壶的年轻女子》和《读信的女人》在[第4、5页](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p04.webp?v=98cf96f7)相对，一幅齐裁切线，一幅越过裁切标记印进出血，两页都不排书眉和页码。天平的局部在[第7页](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p07.webp?v=98cf96f7)以60毫米宽印出，图注排在旁边。PDF带有裁切标记、TrimBox和BleedBox。

**这份食谱回答的问题:**

- 怎样把一幅画印成整页图版，放在版心内、到裁切线或印到出血？
- 怎样做艺术图录：左页放条目，对面右页放图版？
- 怎样制作带出血、裁切标记、书签、页码标签和色彩空间的可付印PDF？

## 简短回答

```js
// script.js, 行 41–53
// Every plate stands alone on the first whole page after its citation, as large as the area
// allows. true (or 'content') keeps it inside the margins with its running heads; 'trim'
// covers the page to the cut, 'bleed' to the bleed. Those two crop the picture about its
// centre, put the caption on a band of paper at the foot, and drop the heads and the folio.
const plateType = { id: 'plate', name: t({ en: 'Plate', es: 'Lámina' }),
  shortLabel: t({ en: 'plate', es: 'lámina' }), captionPrefix: t({ en: 'Plate', es: 'Lámina' }),
  numberingTemplate: '{n}', resetOn: 'never', counterFormat: 'decimal',
  defaultPlacement: { plate: true, captionMeasure: 'body' } }; // the caption as wide as it
const REACH = { milkmaid: 'content', pitcher: 'trim', letter: 'bleed', balance: 'content' };
// A width as a length is measured against the slot, not shared out of it: the detail prints
// 60 mm wide in any layout, 1.25 times the 48 mm of canvas it shows. Its caption stands
// beside it in what is left of the column.
const DETAIL = { width: { value: 60, unit: 'mm' }, captionSide: 'inside', align: 'left' };
```

## 用料

**讲解**

- [整页图版](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-resources.md#资源)
- [决定图位置的引用](https://postext.dev/zh/docs/document-format-resources.md#行内引用主要写法)
- [自定义资源类型](https://postext.dev/zh/docs/configuration-resources.md#资源类型)
- [编号题注](https://postext.dev/zh/docs/document-format-resources.md#按首次引用编号)
- [题注样式](https://postext.dev/zh/docs/configuration-resources.md#题注样式)
- [来源与出处行](https://postext.dev/zh/docs/configuration-resources.md#题注样式)
- [侧题注](https://postext.dev/zh/docs/document-format-resources.md#位置)
- [出血与裁切标记](https://postext.dev/zh/docs/configuration-page-layout.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-page-layout.md#对称页边距)
- [设计过的章首页](https://postext.dev/zh/docs/configuration-headings.md#通栏与高级设计)
- [标题属性](https://postext.dev/zh/docs/document-format.md#标题属性)
- [段落样式](https://postext.dev/zh/docs/configuration-styles.md#段落样式)
- [语义调色板](https://postext.dev/zh/docs/configuration-fonts-colors-viewers.md#调色板)
- [导出PDF](https://postext.dev/zh/docs/configuration-pdf-output.md#生成pdf)
- [纸张颜色](https://postext.dev/zh/docs/configuration-page-layout.md#页面)
- [嵌入PDF的字体](https://postext.dev/zh/docs/configuration-pdf-output.md#为什么需要字体提供函数)
- [标题中的换行](https://postext.dev/zh/docs/document-format-directives.md#标题中的换行)

**配置一览**

- [`bodyText`](https://postext.dev/zh/docs/configuration-text.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#页眉与页脚), [`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#段落样式), [`resourceTypes`](https://postext.dev/zh/docs/configuration-resources.md#资源类型)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/zh/docs/configuration-programmatic-usage.md#排版前加载字体), [`decompressWoff2`](https://postext.dev/zh/docs/configuration-pdf-output.md#浏览器字体提供函数fontsource--woff2), [`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)

**字体**

- Spectral (OFL-1.1), Cormorant Garamond (OFL-1.1), Jost (OFL-1.1)

## 做法

### 1 · 图版用一种类型，每幅画定一个范围

代码就是上面的[简短回答](https://postext.dev/zh/cookbook/art-plates-to-the-bleed.md#简短回答)。图版类型把`plate: true`设为默认位置，所以文章引用的画会进入第一个能完整占用的页面，放大到版心，图注在下。`REACH`逐幅改变它：`'trim'`和`'bleed'`铺满整页，并以画面中心裁切，所以最好选比例接近页面的画（这四幅宽高比为0.85到0.89，页面为0.82）。`captionMeasure: 'body'`让版心内图版的图注与画同宽。

### 2 · 文件大小按印刷位置来定

```js
// script.js, 行 150–202
// JPEGs in assets/ at the pixels each needs for 300 ppi where it prints: 2,400 px high for
// the plates that cover the page (195 mm + 2 × 3 mm of bleed is 7.9 in), less for the rest.
const PAINTINGS = {
  milkmaid: [[1617, 1800], { en: 'Johannes Vermeer, *The Milkmaid*, c. 1660',
    es: 'Johannes Vermeer, *La lechera*, h. 1660' }, { en: 'Oil on canvas, 45.5 × 41 cm. '
    + 'Rijksmuseum, Amsterdam, SK-A-2344, purchased with the support of the Vereniging '
    + 'Rembrandt. Public domain.', es: 'Óleo sobre lienzo, 45,5 × 41 cm. Rijksmuseum, '
    + 'Ámsterdam, SK-A-2344, adquirido con el apoyo de la Vereniging Rembrandt. Dominio '
    + 'público.' }, { en: 'A kitchen maid in a yellow bodice and blue apron pours milk from '
    + 'a jug into a bowl beside a basket of bread, under a window on the left.', es: 'Una '
    + 'criada con corpiño amarillo y delantal azul vierte leche de una jarra en un cuenco, '
    + 'junto a un cesto de pan, bajo una ventana a la izquierda.' }],
  pitcher: [[2116, 2400], { en: 'Johannes Vermeer, *Young Woman with a Water Pitcher*, '
    + 'c. 1662', es: 'Johannes Vermeer, *Joven con una jarra de agua*, h. 1662' },
  { en: 'Oil on canvas, 45.7 × 40.6 cm. The Metropolitan Museum of Art, New York, 89.15.21, '
    + 'Marquand Collection, gift of Henry G. Marquand, 1889. Public domain.', es: 'Óleo sobre '
    + 'lienzo, 45,7 × 40,6 cm. The Metropolitan Museum of Art, Nueva York, 89.15.21, '
    + 'colección Marquand, donación de Henry G. Marquand, 1889. Dominio público.' },
  { en: 'A young woman in a white linen hood opens a window with one hand and holds a '
    + 'silver-gilt pitcher in a basin with the other; a map hangs behind her.', es: 'Una joven '
    + 'con toca de lino blanco abre una ventana con una mano y sujeta con la otra una jarra '
    + 'de plata dorada sobre una palangana; detrás cuelga un mapa.' }],
  letter: [[2039, 2400], { en: 'Johannes Vermeer, *Woman Reading a Letter*, c. 1663',
    es: 'Johannes Vermeer, *Mujer leyendo una carta*, h. 1663' }, { en: 'Oil on canvas, '
    + '46.5 × 39 cm. Rijksmuseum, Amsterdam, SK-C-251, on loan from the City of Amsterdam '
    + '(A. van der Hoop Bequest). Public domain.', es: 'Óleo sobre lienzo, 46,5 × 39 cm. '
    + 'Rijksmuseum, Ámsterdam, SK-C-251, en préstamo de la ciudad de Ámsterdam (legado '
    + 'A. van der Hoop). Dominio público.' }, { en: 'A woman in a blue jacket stands reading '
    + 'a letter in front of a map of Holland, between two chairs, lit from the left.',
  es: 'Una mujer con chaqueta azul lee una carta de pie ante un mapa de Holanda, entre dos '
    + 'sillas, con la luz a la izquierda.' }],
  balance: [[1502, 1700], { en: 'Johannes Vermeer, *Woman Holding a Balance*, c. 1664',
    es: 'Johannes Vermeer, *Mujer con una balanza*, h. 1664' }, { en: 'Oil on canvas, '
    + '39.7 × 35.5 cm. National Gallery of Art, Washington, 1942.9.97, Widener Collection. '
    + 'Public domain.', es: 'Óleo sobre lienzo, 39,7 × 35,5 cm. National Gallery of Art, '
    + 'Washington, 1942.9.97, colección Widener. Dominio público.' }, { en: 'A woman stands '
    + 'at a table spread with pearls and coins, holding up a small balance; a painting of the '
    + 'Last Judgment hangs behind her.', es: 'Una mujer, de pie ante una mesa con perlas y '
    + 'monedas, sostiene en alto una pequeña balanza; detrás cuelga un Juicio Final.' }],
  'balance-detail': [[800, 1051], { en: 'Detail of :ref{id="balance"}: the beam and its two '
    + 'empty pans. The 48 mm of canvas it shows print 60 mm wide, 1.25 times their size.',
  es: 'Detalle de la :ref{id="balance"}: el astil y sus dos platillos vacíos. Los 48 mm de '
    + 'lienzo que muestra se imprimen a 60 mm, 1,25 veces su tamaño.' }, { en: 'National '
    + 'Gallery of Art, Washington. Public domain.', es: 'National Gallery of Art, Washington. '
    + 'Dominio público.' }, { en: 'A hand holds a small balance by its loop between thumb '
    + 'and forefinger; both pans hang empty.', es: 'Una mano sostiene una pequeña balanza por '
    + 'el aro entre el pulgar y el índice; los dos platillos cuelgan vacíos.' }],
};
const resources = Object.entries(PAINTINGS).map(([id, [[w, h], caption, note, alt]]) => ({
  id, typeId: REACH[id] ? 'plate' : 'detail', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: `${id}-${h > w ? h : w}.jpg`, format: 'jpeg', width: w, height: h },
  caption: t(caption), note: t(note), altText: t(alt),
  ...(REACH[id] && { placement: { plate: REACH[id] } }) }));
```

印前检查会把裁切算进去：这里的出血图版连出血高201毫米，文件要2400像素才能达到300 ppi；版心内的两幅需要的少一些。这几幅印出来在303到348 ppi之间。配置里的`page.cutLines`给纸张留出3毫米出血；没有它，`'bleed'`和`'trim'`一样停在裁切线。

### 3 · 书眉避开满版图版

```js
// script.js, 行 73–86
// pages: 'body' keeps them off the opener; a plate set to the trim or the bleed takes the
// 'plate' role, which no element here names, so its page prints bare.
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content,
  parity, pages: 'body', fontFamily: LABEL, fontSize: pt(7.5), color: col('muted'),
  placement: at('page', edge, x, 11), ...caps(7.5), ...extra });
const folio = { color: col('ink'), letterSpacing: pt(0.6) };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-title', '{title}', 'even', 'top-left', OUTER + 8),
  head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 8)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
const footer = { elements: [head('drop-folio', '{pageNumber}', 'all', 'top', 0,
  { ...folio, pages: 'opener', placement: at('container', 'top', 0, 8) })] };
```

到裁切线或出血的图版会让所在页获得`'plate'`角色。这些书眉写的是`pages: 'body'`，所以版心内图版的页面照常排书眉，第4、5页则不排。确实要在那里出现的元素，比如角落里的小号图片来源，可以在`pages`里写上`'plate'`。

### 4 · 尺寸可以说清楚的局部

局部类型设为`width: { value: 60, unit: 'mm' }`，并用`captionSide: 'inside'`。长度是拿来和所在位置比较的，而不是从中分一份：裁出的48毫米画布无论放在哪一栏、哪个版本，都印成60毫米宽，即放大1.25倍，图注也就能写明这一点。

## 完整食谱

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

- 食谱文件夹: https://github.com/drnachio/postext/tree/main/cookbook/art-plates-to-the-bleed

### script.js

```js
// ═══ Postext Cookbook · Nº 183 · Art plates to the margins, the trim and the bleed ═════
// https://postext.dev/en/cookbook/art-plates-to-the-bleed
// Code: MIT · Text: original (CC BY 4.0) · Paintings: Rijksmuseum, The Met, NGA (CC0)
// Fonts: Spectral, Cormorant Garamond, Jost (SIL OFL 1.1) · Needs postext ≥ 1.73.0
// An exhibition essay on four interiors by Vermeer. Each painting is a full-page plate: two
// inside the margins, one to the trimmed edge, one out to the bleed. A detail prints 60 mm wide.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} 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 = 'art-plates-to-the-bleed';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a warm paper and ink, and the ultramarine of the Delft jackets
const palette = {
  ink: '#22201c', // text: a warm near-black
  accent: '#2c4a7c', // kicker, caption labels: the blue of the reading woman's jacket
  rule: '#c9bfae', // the opener's hairline
  muted: '#6b6359', // running heads, folios, credit lines
  paper: '#fbf9f4', // the page, and the band under a caption set over a plate
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  // The engine's defaults link to 'main-color': pointed at the accent, no default blue shows.
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion
const [TEXT, DISPLAY, LABEL] = ['Spectral', 'Cormorant Garamond', 'Jost'];
const [PAGE_W, PAGE_H, TOP, BOTTOM, INNER, OUTER] = [160, 195, 20, 22, 18, 24]; // mm
const BLEED = 3; // mm of picture past the trim on the bleed plate, and the crop marks' offset
const LEAD = 13.5; // body leading in pt
const at = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(size && { size }) });
const caps = (size) => ({ fontWeight: 500, textTransform: 'uppercase',
  letterSpacing: pt(size * 0.2) });

// #region answer: a plate type, and how far each picture reaches
// Every plate stands alone on the first whole page after its citation, as large as the area
// allows. true (or 'content') keeps it inside the margins with its running heads; 'trim'
// covers the page to the cut, 'bleed' to the bleed. Those two crop the picture about its
// centre, put the caption on a band of paper at the foot, and drop the heads and the folio.
const plateType = { id: 'plate', name: t({ en: 'Plate', es: 'Lámina' }),
  shortLabel: t({ en: 'plate', es: 'lámina' }), captionPrefix: t({ en: 'Plate', es: 'Lámina' }),
  numberingTemplate: '{n}', resetOn: 'never', counterFormat: 'decimal',
  defaultPlacement: { plate: true, captionMeasure: 'body' } }; // the caption as wide as it
const REACH = { milkmaid: 'content', pitcher: 'trim', letter: 'bleed', balance: 'content' };
// A width as a length is measured against the slot, not shared out of it: the detail prints
// 60 mm wide in any layout, 1.25 times the 48 mm of canvas it shows. Its caption stands
// beside it in what is left of the column.
const DETAIL = { width: { value: 60, unit: 'mm' }, captionSide: 'inside', align: 'left' };
// #endregion

// #region opener: kicker, title, deck and a short rule, sunk into the first page
const opener = { enabled: true, minHeight: mm(74), slot: { elements: [
  { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: LABEL, fontSize: pt(7.8),
    color: col('accent'), align: 'left', placement: at('container', 'top-left', 0, 10),
    ...caps(7.8) },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY, fontWeight: 500,
    fontSize: pt(32), lineHeight: 1.02, color: col('ink'), align: 'left', overflow: 'wrap',
    placement: at('#kicker', 'below', 0, 3.5, { width: 'fill', height: 'auto' }) },
  { kind: 'text', id: 'deck', content: '{attr.deck}', fontFamily: DISPLAY, italic: true,
    fontWeight: 500, fontSize: pt(13), lineHeight: 1.2, color: col('ink'), align: 'left',
    overflow: 'wrap', placement: at('#title', 'below', 0, 3, { width: mm(96), height: 'auto' }) },
  { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(0.5), color: col('rule'),
    placement: at('#deck', 'below', 0, 6, { width: mm(22) }) },
] } };
// #endregion

// #region running-heads: the book on the verso, the essay on the recto, folios outside
// pages: 'body' keeps them off the opener; a plate set to the trim or the bleed takes the
// 'plate' role, which no element here names, so its page prints bare.
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content,
  parity, pages: 'body', fontFamily: LABEL, fontSize: pt(7.5), color: col('muted'),
  placement: at('page', edge, x, 11), ...caps(7.5), ...extra });
const folio = { color: col('ink'), letterSpacing: pt(0.6) };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-title', '{title}', 'even', 'top-left', OUTER + 8),
  head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 8)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
const footer = { elements: [head('drop-folio', '{pageNumber}', 'all', 'top', 0,
  { ...folio, pages: 'opener', placement: at('container', 'top', 0, 8) })] };
// #endregion

const config = {
  locale: t({ en: 'en-us', es: 'es' }), // the language the text is hyphenated in
  colorPalette,
  resourceTypes: [plateType, { ...plateType, id: 'detail', name: t({ en: 'Figure',
    es: 'Figura' }), shortLabel: t({ en: 'fig.', es: 'fig.' }), captionPrefix: t({ en: 'Fig.',
    es: 'Fig.' }), defaultPlacement: DETAIL }],
  page: { width: mm(PAGE_W), height: mm(PAGE_H), dpi: 150, backgroundColor: col('paper'),
    cutLines: { enabled: true, bleed: mm(BLEED) }, // without them 'bleed' stops at the trim
    margins: { top: mm(TOP), bottom: mm(BOTTOM), left: mm(INNER), right: mm(OUTER),
      mirror: true } },
  layout: { layoutType: 'single', gutterWidth: mm(5) }, // the gutter beside the detail
  bodyText: { fontFamily: TEXT, fontSize: pt(9.6), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    referenceBold: false, textAlign: 'justify', firstLineIndent: mm(4.5),
    indentAfterHeading: false, hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: DISPLAY, color: col('ink'), fontWeight: 500, levels: [
    { level: 1, fontSize: pt(32), breakBefore: { parity: 'odd' }, advancedDesign: opener },
    { level: 2, fontSize: pt(14), lineHeight: pt(LEAD), italic: true, marginTop: pt(LEAD),
      marginBottom: pt(LEAD / 3) },
  ] },
  paragraphStyles: [{ id: 'colophon', fontFamily: LABEL, fontSize: pt(7.2), lineHeight: pt(10),
    color: col('muted'), textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD) }],
  captionStyle: { fontFamily: LABEL, fontSize: pt(7.8), color: col('ink'), gap: pt(7),
    labelBold: true, labelColor: col('accent'), align: 'left',
    note: { fontSize: pt(6.8), color: col('muted') } },
  header,
  footer,
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Vermeer: Four Rooms in Delft"
---

# A Window \\ on the Left {kicker="Exhibition essay" deck="Four interiors by Johannes Vermeer, painted between about 1660 and 1664"}

Johannes Vermeer spent his working life in Delft, and fewer than forty paintings by him survive. Most of them show the corner of a room, one woman busy with something small, and a window on the left through which the daylight comes. The four interiors brought together in this room were painted within some five years of one another. They now belong to three museums, in Amsterdam, New York and Washington, and in each of them the same kind of window is in a different state: shut, open, out of sight, curtained.

In *The Milkmaid* (:ref{id="milkmaid" style="full" case="lower"}) the window is shut. The maid stands side-on to it, pouring a thin stream of milk from an earthenware jug into a bowl, and the light reaches everything she is busy with: the jug, the bread, the blue cloth pushed back on the table, her yellow bodice and the sleeves rolled to the elbow. Vermeer painted the crust of the bread and the rim of the basket with small raised dots of pale paint, so that the highlights stand a little off the surface and catch the light of the gallery as well as the light of the kitchen. A wicker basket and a brass pail hang by the window. Low on the back wall runs a row of Delft tiles, and on the floor in front of them stands a foot warmer.

Kitchen pieces of the time were often crowded with game, fish and pans. Vermeer keeps a handful of objects and spends his care on the wall behind them, which is not white at all but a run of greys, ochres and faint blues, scored with nail holes and the marks of things that once hung there.

In *Young Woman with a Water Pitcher* (:ref{id="pitcher" style="full" case="lower"}) the window stands open. She holds the casement with one hand and rests the other on a silver-gilt pitcher standing in its basin. The linen over her head and shoulders reads as white, but almost none of it is: Vermeer painted it in the blues of the glass and the greys of the wall, keeping pure white for the few places where the light falls hardest. A map of the Low Countries hangs behind her, and a red carpet covers the table.

*Woman Reading a Letter* (:ref{id="letter" style="full" case="lower"}) takes the window out of the picture altogether. We know where it is only from the light on the letter and on her face, and from the shadows that the chairs throw on the wall. Her jacket is painted with natural ultramarine, a blue ground from lapis lazuli and dearer than any other pigment of the day, and the same blue runs through the shadows on the plaster and the cloth on the chairs. She has stopped in the middle of the room to read, with her lips slightly apart, in front of a map of Holland.

*Woman Holding a Balance* (:ref{id="balance" style="full" case="lower"}) is the darkest of the four. A curtain hangs over most of the window, and the little light it lets through falls on her fingers, on the pearls and coins spread over the table and on the gilt edge of the frame behind her, which holds a painting of the Last Judgment. She holds the balance by its loop between thumb and forefinger and waits for the beam to settle. Under the microscope its two pans are empty (:ref{id="balance-detail"}): she is weighing nothing.

Whether these rooms were the rooms of the house on the Oude Langendijk, where Vermeer lived with his wife’s family, cannot be known. The same chairs with lion-head finials, the same leaded window and the same tiled floor return from one picture to the next, rearranged each time, as a stage is set again for another scene.

## A note on the plates

None of the four canvases is taller than 47 centimetres, smaller than most visitors expect. Plates 1 and 4 are printed inside the margins of the page, as large as the text block allows, under the running heads. Plate 2 is printed to the trimmed edge of the page and plate 3 runs past it into the bleed, so that after trimming the picture fills the page; on those two pages the running head and the folio are left off, and the caption stands on a band of paper at the foot. Every plate is printed from a file of at least 300 pixels per inch at the size it takes on the page. Figure 1 is printed at a fixed width of 60 millimetres, whatever the page around it.

:::paragraphs{style="colophon"}
Set in Spectral, Cormorant Garamond and Jost (SIL Open Font License). Essay written for this catalogue under a CC BY 4.0 licence. Paintings reproduced from the open-access images of the Rijksmuseum, The Metropolitan Museum of Art and the National Gallery of Art, all in the public domain.
:::
`; // content.<lang>.md, inlined by the Cookbook

// #region paintings: four plates and a detail, with their tombstones and credit lines
// JPEGs in assets/ at the pixels each needs for 300 ppi where it prints: 2,400 px high for
// the plates that cover the page (195 mm + 2 × 3 mm of bleed is 7.9 in), less for the rest.
const PAINTINGS = {
  milkmaid: [[1617, 1800], { en: 'Johannes Vermeer, *The Milkmaid*, c. 1660',
    es: 'Johannes Vermeer, *La lechera*, h. 1660' }, { en: 'Oil on canvas, 45.5 × 41 cm. '
    + 'Rijksmuseum, Amsterdam, SK-A-2344, purchased with the support of the Vereniging '
    + 'Rembrandt. Public domain.', es: 'Óleo sobre lienzo, 45,5 × 41 cm. Rijksmuseum, '
    + 'Ámsterdam, SK-A-2344, adquirido con el apoyo de la Vereniging Rembrandt. Dominio '
    + 'público.' }, { en: 'A kitchen maid in a yellow bodice and blue apron pours milk from '
    + 'a jug into a bowl beside a basket of bread, under a window on the left.', es: 'Una '
    + 'criada con corpiño amarillo y delantal azul vierte leche de una jarra en un cuenco, '
    + 'junto a un cesto de pan, bajo una ventana a la izquierda.' }],
  pitcher: [[2116, 2400], { en: 'Johannes Vermeer, *Young Woman with a Water Pitcher*, '
    + 'c. 1662', es: 'Johannes Vermeer, *Joven con una jarra de agua*, h. 1662' },
  { en: 'Oil on canvas, 45.7 × 40.6 cm. The Metropolitan Museum of Art, New York, 89.15.21, '
    + 'Marquand Collection, gift of Henry G. Marquand, 1889. Public domain.', es: 'Óleo sobre '
    + 'lienzo, 45,7 × 40,6 cm. The Metropolitan Museum of Art, Nueva York, 89.15.21, '
    + 'colección Marquand, donación de Henry G. Marquand, 1889. Dominio público.' },
  { en: 'A young woman in a white linen hood opens a window with one hand and holds a '
    + 'silver-gilt pitcher in a basin with the other; a map hangs behind her.', es: 'Una joven '
    + 'con toca de lino blanco abre una ventana con una mano y sujeta con la otra una jarra '
    + 'de plata dorada sobre una palangana; detrás cuelga un mapa.' }],
  letter: [[2039, 2400], { en: 'Johannes Vermeer, *Woman Reading a Letter*, c. 1663',
    es: 'Johannes Vermeer, *Mujer leyendo una carta*, h. 1663' }, { en: 'Oil on canvas, '
    + '46.5 × 39 cm. Rijksmuseum, Amsterdam, SK-C-251, on loan from the City of Amsterdam '
    + '(A. van der Hoop Bequest). Public domain.', es: 'Óleo sobre lienzo, 46,5 × 39 cm. '
    + 'Rijksmuseum, Ámsterdam, SK-C-251, en préstamo de la ciudad de Ámsterdam (legado '
    + 'A. van der Hoop). Dominio público.' }, { en: 'A woman in a blue jacket stands reading '
    + 'a letter in front of a map of Holland, between two chairs, lit from the left.',
  es: 'Una mujer con chaqueta azul lee una carta de pie ante un mapa de Holanda, entre dos '
    + 'sillas, con la luz a la izquierda.' }],
  balance: [[1502, 1700], { en: 'Johannes Vermeer, *Woman Holding a Balance*, c. 1664',
    es: 'Johannes Vermeer, *Mujer con una balanza*, h. 1664' }, { en: 'Oil on canvas, '
    + '39.7 × 35.5 cm. National Gallery of Art, Washington, 1942.9.97, Widener Collection. '
    + 'Public domain.', es: 'Óleo sobre lienzo, 39,7 × 35,5 cm. National Gallery of Art, '
    + 'Washington, 1942.9.97, colección Widener. Dominio público.' }, { en: 'A woman stands '
    + 'at a table spread with pearls and coins, holding up a small balance; a painting of the '
    + 'Last Judgment hangs behind her.', es: 'Una mujer, de pie ante una mesa con perlas y '
    + 'monedas, sostiene en alto una pequeña balanza; detrás cuelga un Juicio Final.' }],
  'balance-detail': [[800, 1051], { en: 'Detail of :ref{id="balance"}: the beam and its two '
    + 'empty pans. The 48 mm of canvas it shows print 60 mm wide, 1.25 times their size.',
  es: 'Detalle de la :ref{id="balance"}: el astil y sus dos platillos vacíos. Los 48 mm de '
    + 'lienzo que muestra se imprimen a 60 mm, 1,25 veces su tamaño.' }, { en: 'National '
    + 'Gallery of Art, Washington. Public domain.', es: 'National Gallery of Art, Washington. '
    + 'Dominio público.' }, { en: 'A hand holds a small balance by its loop between thumb '
    + 'and forefinger; both pans hang empty.', es: 'Una mano sostiene una pequeña balanza por '
    + 'el aro entre el pulgar y el índice; los dos platillos cuelgan vacíos.' }],
};
const resources = Object.entries(PAINTINGS).map(([id, [[w, h], caption, note, alt]]) => ({
  id, typeId: REACH[id] ? 'plate' : 'detail', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: `${id}-${h > w ? h : w}.jpg`, format: 'jpeg', width: w, height: h },
  caption: t(caption), note: t(note), altText: t(alt),
  ...(REACH[id] && { placement: { plate: REACH[id] } }) }));
// #endregion

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { // text, display and label faces, loaded before the build
  Spectral: ['400', '400i'], 'Cormorant Garamond': ['500', '500i'], Jost: ['400', '500', '600'] };

// ─── 4 · Build & show ───────────────────────────────────────────────────────
await Promise.all(resources.map((r) => loadImage(r.bitmap.fileId, asset(r.bitmap.fileId))));
const doc = await buildDocumentWithFonts({ markdown, resources }, config, kitFonts(FONTS));
showPages(doc, { title: t({ en: 'Plates to the margins, the trim and the bleed',
  es: 'Láminas a los márgenes, al corte y a sangre' }) });
offerPdf(() => renderToPdf(doc, { fontProvider: fontsourceProvider, resourceBytes: imageBytes }),
  `${RECIPE}.pdf`); // with crop marks, a TrimBox and a BleedBox

// ─── 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 ───────────────────────────────────────────────────────────────────────
```

## 变化

### 所有图版都印到出血

给每幅画同样的范围：每个图版都铺满整页，不排书眉和页码，只有裁切不同。

```diff
-const REACH = { milkmaid: 'content', pitcher: 'trim', letter: 'bleed', balance: 'content' };
+const REACH = { milkmaid: 'bleed', pitcher: 'bleed', letter: 'bleed', balance: 'bleed' };
```

### 按原大印局部

从博物馆的文件里裁出60毫米画布，宽度不变：图注就可以写1:1。这幅画的原始文件有1666 ppi，即使只有几毫米的局部也仍然超过300 ppi。

## 常见问题

- 和另一幅在同一段里被引用的图版会等到再下一页，因为已经有浮动体的页面会被跳过，最多三页。
- `pt`和`mm`宽度都有效；`px`和`em`不被当作长度，图会占满所在位置。
- 比页面宽得多的画，在到裁切线或出血的图版上会被裁掉两侧。横幅的画最好留在版心内，整幅都能看到。

## 致谢

- 食谱: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- 文字: The essay, the captions and the note on the plates: Postext Cookbook, CC-BY-4.0
- 图片: Plate 1, Johannes Vermeer, The Milkmaid, c. 1660, Rijksmuseum SK-A-2344; the museum’s image reduced to 1,800 px high: Rijksmuseum, Amsterdam ([来源](https://id.rijksmuseum.nl/200108369)), CC0-1.0
- 图片: Plate 2, Johannes Vermeer, Young Woman with a Water Pitcher, c. 1662, The Met 89.15.21; the museum’s image, its unpainted edges cut off, reduced to 2,400 px high: The Metropolitan Museum of Art, New York (Open Access) ([来源](https://www.metmuseum.org/art/collection/search/437881)), CC0-1.0
- 图片: Plate 3, Johannes Vermeer, Woman Reading a Letter, c. 1663, Rijksmuseum SK-C-251; the museum’s image reduced to 2,400 px high: Rijksmuseum, Amsterdam ([来源](https://id.rijksmuseum.nl/200108372)), CC0-1.0
- 图片: Plate 4, Johannes Vermeer, Woman Holding a Balance, c. 1664, National Gallery of Art 1942.9.97; the museum’s image reduced to 1,700 px high: National Gallery of Art, Washington (Open Access) ([来源](https://www.nga.gov/artworks/1236-woman-holding-balance)), CC0-1.0
- 图片: Figure 1, a 48 × 63 mm detail of plate 4 cut from the museum’s full-resolution image and reduced to 800 px wide: National Gallery of Art, Washington (Open Access) ([来源](https://www.nga.gov/artworks/1236-woman-holding-balance)), CC0-1.0
- 字体: Spectral (OFL-1.1), Cormorant Garamond (OFL-1.1), Jost (OFL-1.1)
- 代码: MIT · 示例内容: CC-BY-4.0

## 相关食谱

- [No. 034 · 与图版对页的图录条目](https://postext.dev/zh/cookbook/catalogue-facing-plates.md): 每个条目从左页开始，在评述的第一句引用它的图版；图版浮动到对面的右页，按扫描件比例缩小到填满版心。 · 难度 3 (高级) · 目录册
- [No. 068 · 满版出血图版的摄影随笔](https://postext.dev/zh/cookbook/photo-essay-full-bleed.md): 图版是由一个列表生成的标题样式，每张铺满整页直到成品边缘；暴风雨一图分成两半，跨过一个跨页的中缝。 · 难度 2 (中级) · 摄影集
- [No. 024 · 可付印的PDF：出血、裁切线与PDF/X](https://postext.dev/zh/cookbook/print-ready-pdf.md): 一份展览导览单，带3 mm出血和裁切线，连同印刷母版导出为按FOGRA51分色的PDF/X-4，印前检查没有发现问题。 · 难度 3 (高级) · 单页与零散印品
