# 金箔押し、部分ニス、エンボスの表紙

> マンリーケ『父の死を悼む歌』の並製本。絵に部分グロスニス、エンボスの上に金箔押しのカルトゥーシュ、表4に空押し。加工ごとに版が1枚ずつ。

- HTML版: https://postext.dev/ja/cookbook/cover-foil-varnish-emboss
- レシピ No. 199 · 出力と組み込み · 難易度 3 (上級) · 出力: Canvas, PDF
- ジャンル: 詩歌
- 必要なもの postext ≥ 1.93.0, postext-pdf ≥ 1.93.0 · テスト環境 1.93.0, postext-pdf 1.93.0 ／テスト日 2026-11-23
- ページ: [1](https://postext.dev/cookbook/cover-foil-varnish-emboss/en/p01.webp?v=e7e2d550), [3](https://postext.dev/cookbook/cover-foil-varnish-emboss/en/p03.webp?v=e7e2d550), [4](https://postext.dev/cookbook/cover-foil-varnish-emboss/en/p04.webp?v=e7e2d550), [5](https://postext.dev/cookbook/cover-foil-varnish-emboss/en/p05.webp?v=e7e2d550), [6](https://postext.dev/cookbook/cover-foil-varnish-emboss/en/p06.webp?v=e7e2d550), [27](https://postext.dev/cookbook/cover-foil-varnish-emboss/en/p27.webp?v=e7e2d550), [1](https://postext.dev/cookbook/cover-foil-varnish-emboss/en/p28.webp?v=e7e2d550)
- PDF: https://postext.dev/cookbook/cover-foil-varnish-emboss/en/cover-foil-varnish-emboss.pdf?v=e7e2d550
- Sandboxで開く: https://postext.dev/ja/sandbox#recipe=cover-foil-varnish-emboss&lang=en (.postext: https://postext.dev/cookbook/cover-foil-varnish-emboss/en/cover-foil-varnish-emboss.postext)
- 最終更新: 2026-11-23
- 他の言語: [en](https://postext.dev/en/cookbook/cover-foil-varnish-emboss.md), [es](https://postext.dev/es/cookbook/cover-foil-varnish-emboss.md), [ca](https://postext.dev/ca/cookbook/cover-foil-varnish-emboss.md), [de](https://postext.dev/de/cookbook/cover-foil-varnish-emboss.md), [fr](https://postext.dev/fr/cookbook/cover-foil-varnish-emboss.md), [it](https://postext.dev/it/cookbook/cover-foil-varnish-emboss.md), [pt](https://postext.dev/pt/cookbook/cover-foil-varnish-emboss.md), [zh](https://postext.dev/zh/cookbook/cover-foil-varnish-emboss.md), [ar](https://postext.dev/ar/cookbook/cover-foil-varnish-emboss.md)

## かんたんな説明

古典の詩を収めた薄い本と、その表紙用紙です。表紙は印刷のあとに加工が入ります。絵につやのあるニス、金箔を押した枠、厚紙から浮き出させた形。それぞれがどこにかかるかをページで見せます。

## できあがり

ホルヘ・マンリーケが父の死に寄せた『Coplas』を、英語版はロングフェローの訳で、スペイン語版は原文で、125 × 200 mmの並製本にします。表紙用紙も作ります。4色を刷り終えたあと、加工所に回る用紙です。加工は3つ。カルトゥーシュの上下の絵に部分グロスニスをかけます。カルトゥーシュの二重の枠は金箔押しにし、枠の中のパネルはエンボスで持ち上げるので、書名は浮き出た面に載ります。表4には菱形の空押し。インキは使わず、厚紙を押し上げるだけです。本の下には用紙を4回描きます。刷り上がりのまま、ニス版と箔版を擬似カラーで、斜めの光の下で、そして型を彫る人が使うエンボス版として。PDFはPDF/X-4で、加工ごとに版を持ちます。

**このレシピが答える問い:**

- 表紙に部分ニス、金箔押し、エンボスの書名を入れるには？

## 手短な答え

```js
// script.js, 行 65–104
// A slim paperback: PUR perfect binding, the spine from the pages on 120 g/m² wove. The
// spine is under the 6 mm a spine is lettered from by default, so this version letters it
// from 4.5 mm.
const production = {
  bindings: [{ id: 'pur', name: 'PUR perfect binding', style: 'perfect', signature: 16,
    measures: { bleed: 3, spineAllowance: 0.5 } }],
  versions: [{ id: 'paperback', name: t({ en: 'Paperback', es: 'Rústica' }), binding: 'pur',
    isbn: '978-84-0000-199-5', spineText: { minSpine: 4.5 } }],
};
const folio = { paper: { type: 'bookWove', grammage: 120, bulk: 2.2, shade: '#f7f1e3' } };
const cover = {
  background: col('ground'),
  elements: [
    { id: 'art', kind: 'image', zone: 'front', x: 0, y: -3, width: 128, height: 206,
      resourceId: 'river', fit: 'cover' },
    // The title's panel, a shade darker than the ground, and the frame round it. The frame
    // prints nothing in four colours (it has the panel's colour): the foil plate carries it.
    { id: 'panel', kind: 'shape', zone: 'front', x: 14, y: 77, width: CW, height: CH,
      color: col('panel'), path: [{ closed: true, nodes: contour(0, 6) }] },
    { id: 'cartouche', kind: 'shape', zone: 'front', x: 14, y: 77, width: CW, height: CH,
      color: col('panel'), path: cartouche },
  ],
  finishes: [
    // A spot gloss over the painting above and below the panel, 4 mm clear of it, so the
    // varnish never lies on the foil. The back and the spine stay matt.
    ...[[-3, 76], [127, 76]].map(([y, height], i) => ({ id: `gloss-${i + 1}`, process: 'varnish',
      ink: col('varnish'), shape: { box: { zone: 'front', x: 0, y, width: 128, height } } })),
    // Gold foil on the frame, and the whole panel embossed: the title prints on a raised
    // field, the foil stamped round its edge.
    { id: 'gold', process: 'foil', ink: col('foil'), shape: { element: 'cartouche' } },
    { id: 'relief', process: 'emboss', shape: { element: 'panel' } },
    // A blind emboss: no ink and no foil, only the paper raised.
    { id: 'emblem', process: 'emboss', shape: { outline: emblem,
      box: { zone: 'back', x: 52.5, y: 30, width: 20, height: 20 } } },
  ],
  verticalAlign: { front: 'middle', back: 'middle' },
};
// The press file: PDF/X-4. The varnish and the foil are spot inks with a finish, each on
// its plate; the emboss goes on a plate named Emboss, beside the die line.
const print = { standard: 'pdfx4', outputProfile: 'fogra51', convertImages: false };
```

## 材料

**学べること**

- [表紙の加工と技術版](https://postext.dev/ja/docs/print-covers.md#加工と技術版): cover.finishesは、ニスや箔を表紙デザインの形に合わせて専用の特色版に載せ、空押しや凹押しは印刷しない技術版に載せて、製本所の型の元にします。
- [表紙の用紙](https://postext.dev/ja/docs/print-covers.md#用紙とその各部): buildCoverは印刷版の表紙用紙を組みます。表4、背、表1に袖を付け、上製なら表紙、カバー、見返しも、裁ち落としと折りトンボ付きで作ります。デザインはcover設定、各部の文字は本のMarkdown文書が受け持ちます。
- [特殊インキ](https://postext.dev/ja/docs/special-inks-die-cuts.md#加工): 加工の種類を持つ特色です。メタリック、箔押し、蛍光、不透明白、ニスがあります。専用の版に出力され、キャンバスでは光沢や加工マップを表示でき、Folioでは光が当たります。

**ほかに使うもの**

- [印刷版、ISBN、背幅](https://postext.dev/ja/docs/print-covers.md#本の版)
- [表紙、扉、奥付](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [見出しスタイル](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [デザインした章扉](https://postext.dev/ja/docs/configuration-headings.md#幅と詳細デザイン)
- [ページデザインのテキスト・罫・ボックス](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル)
- [文書のメタデータ](https://postext.dev/ja/docs/document-format.md#フロントマター)
- [段落スタイル](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル)
- [行ごとの詩](https://postext.dev/ja/docs/document-format-directives.md#verse)
- [柱とノンブル](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル)
- [リソースとしての図と表](https://postext.dev/ja/docs/document-format-resources.md#リソース)
- [セマンティックカラーパレット](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット)
- [PDFの書き出し](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)
- [CMYKとグレースケールのPDF](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#pdf生成設定)
- [キャンバス上のページ](https://postext.dev/ja/docs/configuration-programmatic-usage.md#ページをビットマップに描画する)
- [用紙、綴じ、机、照明（Folio）](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#folioビューアー設定)
- [見出しの属性](https://postext.dev/ja/docs/document-format.md#見出しの属性)
- [用紙の色](https://postext.dev/ja/docs/configuration-page-layout.md#ページ)
- [ページの役割ごとの柱](https://postext.dev/ja/docs/configuration-headers-footers.md#テキスト要素)
- [PDFに埋め込むフォント](https://postext.dev/ja/docs/configuration-pdf-output.md#なぜフォントプロバイダーが必要か)
- [節ごとの柱](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [特色とインキ表](https://postext.dev/ja/docs/configuration-pdf-output.md#特色)
- [番号のない章](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)

**設定の一覧**

- [`bodyText`](https://postext.dev/ja/docs/configuration-text.md#本文), [`colorPalette`](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット), [`cover`](https://postext.dev/ja/docs/print-covers.md#表紙のデザイン), [`folio`](https://postext.dev/ja/docs/configuration-html-folio-epub.md#外観), [`footer`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`header`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`headingStyles`](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル), [`headings`](https://postext.dev/ja/docs/configuration-headings.md#見出し), [`layout`](https://postext.dev/ja/docs/configuration-page-layout.md#レイアウト), [`locale`](https://postext.dev/ja/docs/configuration-language.md#ハイフネーション), [`page`](https://postext.dev/ja/docs/configuration-page-layout.md#ページ), [`paragraphStyles`](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル), [`print`](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#印刷出力設定), [`production`](https://postext.dev/ja/docs/print-covers.md#本の版)

**API**

- [`buildCover`](https://postext.dev/ja/docs/print-covers.md#コードから), [`buildDocumentWithFonts`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#レイアウトの前にフォントを読み込む), [`decompressWoff2`](https://postext.dev/ja/docs/configuration-pdf-output.md#ブラウザー向けフォントプロバイダーfontsource--woff2), [`inlineSvgFonts`](https://postext.dev/ja/docs/configuration-resources.md#svgの文字のフォント), `preflightDocument`, [`registerResourceImage`](https://postext.dev/ja/docs/architecture.md#apiの概要), [`renderPageToCanvas`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#ページをビットマップに描画する), [`renderToPdf`](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)

**書体**

- Alegreya (OFL-1.1), Alegreya SC (OFL-1.1), Alegreya Sans SC (OFL-1.1)

## 作り方

### 1 · 加工はデザインの図形に沿う

コードは上の[手短な答え](https://postext.dev/ja/cookbook/cover-foil-varnish-emboss.md#手短な答え)にあります。加工には工程、刷るインキがあればそのインキ、そして形を指定します。表紙の要素（`{ element: 'cartouche' }`）、ゾーンの中の矩形、矩形の中の輪郭のどれかです。ニスと箔はパレットで`finish`を持つ特色なので、PDFではそれぞれが版になり、プリフライトにも並びます。エンボスは何も刷りません。印刷ファイルがEmbossと呼ぶ技術版に載り、型を彫る人はこれを使います。ページには描かれません。

ニスは2つの矩形で、1つはカルトゥーシュの上、もう1つは下にあり、どちらもカルトゥーシュの4 mm手前で止まるので、ニスが箔に重なることはありません。表4と背はマットのままです。本は27ページ、120 g/m²、嵩高2.2の書籍用紙で、16ページ折で綴じると32ページになり、背幅は4.7 mmです。標準では6 mm未満の背に文字を入れないので、版で`spineText.minSpine`を4.5にしています。このISBNは見本の番号で、どの本にも割り当てられていません。

### 2 · カルトゥーシュは画像ではなく、デザインのパス

```js
// script.js, 行 36–61
// Fractions of its box, so the frame stretches with it. Two rings, each an outer contour and
// an inner one run the other way round: the hole between them stays empty, and the foil and
// the emboss take exactly this outline.
const [CW, CH] = [97, 46]; // the cartouche's box, mm
const K = 0.5523; // a quarter circle as a cubic
function contour(inset, notch) {
  const [tx, ty, rx, ry] = [inset / CW, inset / CH, (notch + inset) / CW, (notch + inset) / CH];
  // Each corner: the point on the edge before it and on the edge after it, a hollow arc
  // between them whose handles leave each edge square.
  const corners = [
    [[1 - rx, ty], [1 - tx, ry], 'h'], [[1 - tx, 1 - ry], [1 - rx, 1 - ty], 'v'],
    [[rx, 1 - ty], [tx, 1 - ry], 'h'], [[tx, ry], [rx, ty], 'v']];
  return corners.flatMap(([[ax, ay], [bx, by], edge]) => [
    { x: ax, y: ay, out: edge === 'h' ? { x: ax, y: ay + K * (by - ay) }
      : { x: ax + K * (bx - ax), y: ay } },
    { x: bx, y: by, in: edge === 'h' ? { x: bx - K * (bx - ax), y: by }
      : { x: bx, y: by - K * (by - ay) } }]);
}
const reversed = (nodes) => nodes.slice().reverse()
  .map(({ x, y, in: i, out: o }) => ({ x, y, ...(o && { in: o }), ...(i && { out: i }) }));
const ring = (outer, inner, notch) => [{ closed: true, nodes: contour(outer, notch) },
  { closed: true, nodes: reversed(contour(inner, notch)) }];
const cartouche = [...ring(0, 1.3, 6), ...ring(2.3, 2.75, 6)];
// The emblem on the back: a lozenge with a lozenge cut out of it, as a saved outline.
const lozenge = (d) => [[0.5, d], [1 - d, 0.5], [0.5, 1 - d], [d, 0.5]].map(([x, y]) => ({ x, y }));
const emblem = [lozenge(0), lozenge(0.24).reverse()];
```

箔とエンボスは指定した要素の輪郭どおりにかかるので、枠はエンジンがパスを知っている図形でなければなりません。表紙のパスは閉じた輪郭のリストで、節点は要素の矩形に対する比率、曲線には入りと出のハンドルがあります。角はそれぞれ内向きの四分円で、3次曲線で描きます。環は外側の輪郭と、逆向きに回る内側の輪郭の組です。nonzeroの規則で、その間は空いたままになります。環2つで二重の枠になります。枠はパネルと同じ色なので4色では何も刷られず、箔版が受け持ちます。表4の紋章は保存した輪郭で、菱形2つ、小さいほうは逆向きです。

### 3 · 表紙の文字のスタイル

```js
// script.js, 行 108–124
const style = (id, fontFamily, size, lead, color, extra) => ({ id, fontFamily, fontSize: pt(size),
  lineHeight: pt(lead), color, italicColor: color, firstLineIndent: mm(0), textAlign: 'left',
  hyphenation: false, ...extra });
const caps = (tracking) => ({ fontWeight: 700, letterSpacing: pt(tracking) });
const mid = { textAlign: 'center' };
const coverStyles = [
  style('cover-title', 'Alegreya SC', 40, 40, col('cream'), { ...mid, fontWeight: 500 }),
  style('cover-subtitle', 'Alegreya', 13, 17, col('cream'), { ...mid, italic: true }),
  style('cover-author', 'Alegreya Sans SC', 9, 12, col('ochre'), { ...mid, ...caps(1.6),
    marginTop: pt(9) }),
  style('cover-spine', 'Alegreya Sans SC', 7, 8, col('cream'), { ...mid, ...caps(1.1) }),
  style('cover-quote', 'Alegreya', 13, 17, col('ochre'), { ...mid, italic: true,
    marginBottom: pt(16) }),
  style('cover-blurb', 'Alegreya', 10.5, 14.5, col('cream'), { marginBottom: pt(7) }),
  style('cover-note', 'Alegreya Sans SC', 8, 11, col('ochre'), { ...caps(1.2),
    marginTop: pt(4) }),
];
```

`cover-title`、`cover-subtitle`、`cover-author`、`cover-spine`は、`buildCover`が置くメタデータに付ける名前です。`cover-quote`、`cover-blurb`、`cover-note`は表紙のMarkdownで指定します。表1は高さ方向の中央揃え（`verticalAlign`）なので、書名は文字の大きさにかかわらずカルトゥーシュに収まります。

### 4 · 本文

```js
// script.js, 行 128–167
const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [125, 200, 22, 24, 19, 17, 15]; // mm, pt
const at = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(size && { size }) });
const text = (id, content, look, place) => ({ kind: 'text', id, content, align: 'center',
  overflow: 'wrap', placement: place, ...look });
const face = (fontFamily, size, color, x) => ({ fontFamily, fontSize: pt(size), color, ...x });
const label = (size, color = col('muted')) => face('Alegreya Sans SC', size, color, caps(size / 6));
const sc = (size, extra) => face('Alegreya SC', size, col('ink'), { fontWeight: 500, ...extra });
const none = { header: { elements: [] }, footer: { elements: [] }, numbered: false, toc: false };
const design = (minHeight, elements) => ({ enabled: true, minHeight: mm(minHeight),
  slot: { elements } });
const page = (parity) => ({ breakBefore: { enabled: true, parity } });
const rule = (id, y, to = 'page') => ({ kind: 'rule', id, direction: 'horizontal',
  thickness: pt(0.6), color: col('accent'), placement: at(to, 'top', 0, y, { width: mm(12) }) });
const headingStyles = [
  { ...none, id: 'half-title', advancedDesign: design(60, [
    text('t', '{title}', sc(18), at('page', 'top', 0, 64))]) },
  { ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
    text('t', '{title}', sc(34), at('page', 'top', 0, 50)),
    text('s', '{subtitle}', face('Alegreya', 13, col('ink'), { italic: true }),
      at('page', 'top', 0, 66)),
    rule('r', 76),
    text('a', '{author}', label(8.5, col('accent')), at('page', 'top', 0, 81)),
    text('c', '{attr.credit}', face('Alegreya', 9.5, col('muted'), { italic: true }),
      at('page', 'top', 0, 120, { width: mm(76) })),
    text('i', '{attr.imprint}', label(7.5), at('page', 'bottom', 0, -28)),
  ]) },
  { ...none, ...page('even'), id: 'rights',
    advancedDesign: design(92, [rule('r', 86, 'container')]) },
  // The poem opens on a recto, sunk 46 mm, its title in small capitals over a short rule.
  { ...page('odd'), id: 'poem', toc: false, header: { elements: [] }, advancedDesign: design(46, [
    text('t', '{titleText}', sc(19), at('container', 'top', 0, 18)),
    text('n', '{attr.note}', face('Alegreya', 10.5, col('muted'), { italic: true }),
      at('container', 'top', 0, 28, { width: mm(80) })),
    rule('r', 38, 'container')]) },
  { ...none, ...page('odd'), id: 'colophon', advancedDesign: design(64, [
    rule('r', 56, 'container')]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.8), parity, pages: 'body' },
  at('page', 'top', 0, 11));
```

半扉、扉、権利表記、そして詩が奇数ページから46 mm下げて始まります。連を2ページに分けない詩の組み方です。柱は偶数ページに著者、奇数ページに書名。奥付は最後の奇数ページで本を閉じます。

### 5 · 組んだページから用紙を作る

```js
// script.js, 行 858–866
const built = buildCover({ config, version: 'paperback', pages: book.pages, markdown: coverText,
  metadata: book.metadata, resources });
if (!('config' in built)) throw new Error(built.issues.map((i) => i.kind).join(', '));
// The barcode's digits name OCR-B, which no font server has: the label face sets them.
for (const [id, bytes] of Object.entries(built.files)) {
  await loadSvg(id, new TextDecoder().decode(bytes)
    .replace(/font-family="[^"]*"/g, 'font-family="Alegreya Sans SC"'));
}
const sheet = await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS));
```

`buildCover`はページ、メタデータ、表紙のMarkdownを受け取り、`buildDocumentWithFonts`に渡す文書と、SVGのバーコードを返します。バーコードの数字はOCR-Bを求めますが、どのフォントサーバーにもないので、読み込み済みのAlegreya Sans SCで組みます。

### 6 · それぞれの版がかかる範囲

```js
// script.js, 行 873–931
// 'flat' paints the inks: the foil in its colour, the varnish and the emboss not at all.
// 'map' marks the special plates in false colour over a faded sheet, 'sheen' rakes a light
// across it. The emboss plate is drawn from the page's technical plates, the outlines the
// PDF fills on its Emboss separation.
const leaf = sheet.pages[0];
const scale = 1100 / leaf.width;
const outline = (ctx, paths) => {
  ctx.beginPath();
  for (const c of paths.flat()) {
    if (c.op === 'M') ctx.moveTo(c.x, c.y);
    else if (c.op === 'L') ctx.lineTo(c.x, c.y);
    else if (c.op === 'C') ctx.bezierCurveTo(c.x1, c.y1, c.x2, c.y2, c.x, c.y);
    else if (c.op === 'Q') ctx.quadraticCurveTo(c.x1, c.y1, c.x, c.y);
    else ctx.closePath();
  }
  ctx.fill('nonzero');
};
const VIEWS = [
  ['flat', t({ en: 'As it prints', es: 'Como se imprime' })],
  ['map', t({ en: 'The varnish and foil plates', es: 'Las planchas de barniz y oro' })],
  ['sheen', t({ en: 'Under a raking light', es: 'Con luz rasante' })],
  ['emboss', t({ en: 'The Emboss plate', es: 'La plancha de gofrado' })],
];
const views = document.createElement('section');
views.id = 'finish-views';
views.style.cssText = 'display: grid; grid-template-columns: repeat(2, minmax(0, 560px)); '
  + 'gap: 18px; justify-content: center; padding: 24px max(16px, calc(50% - 520px)); color: #ddd; '
  + 'font: 14px sans-serif';
for (const [mode, name] of VIEWS) {
  const [figure, canvas, caption] = ['figure', 'canvas', 'figcaption']
    .map((tag) => document.createElement(tag));
  figure.style.margin = '0';
  canvas.style.cssText = 'display: block; width: 100%';
  canvas.setAttribute('role', 'img');
  canvas.setAttribute('aria-label', `${t({ en: 'The cover sheet', es: 'El pliego' })}: ${name}`);
  renderPageToCanvas(leaf, sheet, canvas, { scale, finishes: mode === 'emboss' ? 'flat' : mode });
  if (mode === 'emboss') {
    // The die-maker's film: the plate in black on white, the sheet faded under it.
    const ctx = canvas.getContext('2d');
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.fillStyle = 'rgba(255, 255, 255, 0.86)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.setTransform(scale, 0, 0, scale, 0, 0);
    ctx.fillStyle = '#111';
    outline(ctx, (leaf.plates ?? []).flatMap((p) => p.paths));
  }
  caption.textContent = name;
  figure.append(canvas, caption);
  views.append(figure);
}
// What the preflight reads from the sheet: its spot plates and the reliefs it checks.
const spots = preflightDocument(sheet).find((i) => i.kind === 'spotInks');
const list = document.createElement('p');
list.style.cssText = 'grid-column: 1 / -1; margin: 0; text-align: center';
list.textContent = `${t({ en: 'Plates beside CMYK', es: 'Planchas además de CMYK' })}: `
  + [...(spots?.inks ?? []), ...new Set((leaf.plates ?? [])
    .map((p) => `${p.process[0].toUpperCase()}${p.process.slice(1)}`))].join(' · ');
views.append(list);
document.getElementById('pages').before(views);
```

`renderPageToCanvas`は加工を3通りに描きます。`flat`は印刷機が載せるとおりにインキを描きます。箔はその色で、ニスは描きません。`map`は用紙を淡くし、特色版を擬似カラーで示します。`sheen`は用紙に斜めの光を当て、ニスと箔が光ります。エンボスは何も刷らないので3つのどれにも出ません。4つ目の図は、淡くした用紙の上にページの技術版（`page.plates`）を黒で描きます。PDFがEmbossの分版で塗る輪郭です。下の1行は、特色を`preflightDocument`から、工程を技術版から読んでいます。

## レシピの全体

レシピのフォルダーから合成した1つのファイルで、サンプルのテキストとレシピ集の共通キットを埋め込んであり、自分でページを組み立てます。動かすには、空のページの`<script type="module">`に入れるか、新しいCodePenのpenのJSパネルに貼り付けます（モジュールとして）。esm.shからpostextを読み込むので、インストールもビルドも要りません。

- レシピのフォルダー: https://github.com/drnachio/postext/tree/main/cookbook/cover-foil-varnish-emboss

### script.js

```js
// ═══ Postext Cookbook · Nº 199 · A cover in foil, spot varnish and emboss ═══════════════
// https://postext.dev/en/cookbook/cover-foil-varnish-emboss
// Code: MIT · Text: Manrique, tr. H. W. Longfellow (public domain) · Art: diffusion models
// Fonts: Alegreya, Alegreya SC, Alegreya Sans SC (SIL OFL 1.1) · Needs postext ≥ 1.93.0
//
// Manrique's Coplas as a slim paperback whose cover goes to the finisher after the press: a
// spot gloss over the painting, a gold-foil cartouche stamped over an emboss of the same
// shape, and a blind emboss on the back. Each finish is a shape of the cover's design; the
// varnish and the foil get spot plates of their own, the emboss a plate that prints nothing.
import { buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, inlineSvgFonts,
  preflightDocument } from 'https://esm.sh/postext';
import { buildCover } from 'https://esm.sh/postext/production';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'cover-foil-varnish-emboss';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The pages' four colours, then the cover's: a bottle-green ground and its darker panel.
const palette = { ink: '#262320', accent: '#8a3b2a', muted: '#6d655b', paper: '#fbf7ef',
  ground: '#1d2b27', panel: '#15201d', cream: '#efe5cf', ochre: '#c8a15a' };
// The two inks the finisher is asked for: spot colours that each make a plate of their own.
const spot = (hex, name, cmyk, kind) => ({ hex, model: 'spot',
  spot: { name, cmyk, finish: { kind, sheen: 'gloss' } } });
const inks = { foil: spot('#b8963e', 'Gold foil', { c: 0, m: 20, y: 60, k: 25 }, 'foil'),
  varnish: spot('#eef0e6', 'Gloss varnish', { c: 0, m: 0, y: 0, k: 0 }, 'varnish') };
const col = (id) => (inks[id] ? { ...inks[id], paletteId: id }
  : { hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  ...Object.entries(inks).map(([id, value]) => ({ id, name: value.spot.name, value })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];

// #region art: the cartouche, a frame with hollow corners, drawn as a shape of the design
// Fractions of its box, so the frame stretches with it. Two rings, each an outer contour and
// an inner one run the other way round: the hole between them stays empty, and the foil and
// the emboss take exactly this outline.
const [CW, CH] = [97, 46]; // the cartouche's box, mm
const K = 0.5523; // a quarter circle as a cubic
function contour(inset, notch) {
  const [tx, ty, rx, ry] = [inset / CW, inset / CH, (notch + inset) / CW, (notch + inset) / CH];
  // Each corner: the point on the edge before it and on the edge after it, a hollow arc
  // between them whose handles leave each edge square.
  const corners = [
    [[1 - rx, ty], [1 - tx, ry], 'h'], [[1 - tx, 1 - ry], [1 - rx, 1 - ty], 'v'],
    [[rx, 1 - ty], [tx, 1 - ry], 'h'], [[tx, ry], [rx, ty], 'v']];
  return corners.flatMap(([[ax, ay], [bx, by], edge]) => [
    { x: ax, y: ay, out: edge === 'h' ? { x: ax, y: ay + K * (by - ay) }
      : { x: ax + K * (bx - ax), y: ay } },
    { x: bx, y: by, in: edge === 'h' ? { x: bx - K * (bx - ax), y: by }
      : { x: bx, y: by - K * (by - ay) } }]);
}
const reversed = (nodes) => nodes.slice().reverse()
  .map(({ x, y, in: i, out: o }) => ({ x, y, ...(o && { in: o }), ...(i && { out: i }) }));
const ring = (outer, inner, notch) => [{ closed: true, nodes: contour(outer, notch) },
  { closed: true, nodes: reversed(contour(inner, notch)) }];
const cartouche = [...ring(0, 1.3, 6), ...ring(2.3, 2.75, 6)];
// The emblem on the back: a lozenge with a lozenge cut out of it, as a saved outline.
const lozenge = (d) => [[0.5, d], [1 - d, 0.5], [0.5, 1 - d], [d, 0.5]].map(([x, y]) => ({ x, y }));
const emblem = [lozenge(0), lozenge(0.24).reverse()];
// #endregion

// #region answer: three finishes, each over a shape of the cover's design
// A slim paperback: PUR perfect binding, the spine from the pages on 120 g/m² wove. The
// spine is under the 6 mm a spine is lettered from by default, so this version letters it
// from 4.5 mm.
const production = {
  bindings: [{ id: 'pur', name: 'PUR perfect binding', style: 'perfect', signature: 16,
    measures: { bleed: 3, spineAllowance: 0.5 } }],
  versions: [{ id: 'paperback', name: t({ en: 'Paperback', es: 'Rústica' }), binding: 'pur',
    isbn: '978-84-0000-199-5', spineText: { minSpine: 4.5 } }],
};
const folio = { paper: { type: 'bookWove', grammage: 120, bulk: 2.2, shade: '#f7f1e3' } };
const cover = {
  background: col('ground'),
  elements: [
    { id: 'art', kind: 'image', zone: 'front', x: 0, y: -3, width: 128, height: 206,
      resourceId: 'river', fit: 'cover' },
    // The title's panel, a shade darker than the ground, and the frame round it. The frame
    // prints nothing in four colours (it has the panel's colour): the foil plate carries it.
    { id: 'panel', kind: 'shape', zone: 'front', x: 14, y: 77, width: CW, height: CH,
      color: col('panel'), path: [{ closed: true, nodes: contour(0, 6) }] },
    { id: 'cartouche', kind: 'shape', zone: 'front', x: 14, y: 77, width: CW, height: CH,
      color: col('panel'), path: cartouche },
  ],
  finishes: [
    // A spot gloss over the painting above and below the panel, 4 mm clear of it, so the
    // varnish never lies on the foil. The back and the spine stay matt.
    ...[[-3, 76], [127, 76]].map(([y, height], i) => ({ id: `gloss-${i + 1}`, process: 'varnish',
      ink: col('varnish'), shape: { box: { zone: 'front', x: 0, y, width: 128, height } } })),
    // Gold foil on the frame, and the whole panel embossed: the title prints on a raised
    // field, the foil stamped round its edge.
    { id: 'gold', process: 'foil', ink: col('foil'), shape: { element: 'cartouche' } },
    { id: 'relief', process: 'emboss', shape: { element: 'panel' } },
    // A blind emboss: no ink and no foil, only the paper raised.
    { id: 'emblem', process: 'emboss', shape: { outline: emblem,
      box: { zone: 'back', x: 52.5, y: 30, width: 20, height: 20 } } },
  ],
  verticalAlign: { front: 'middle', back: 'middle' },
};
// The press file: PDF/X-4. The varnish and the foil are spot inks with a finish, each on
// its plate; the emboss goes on a plate named Emboss, beside the die line.
const print = { standard: 'pdfx4', outputProfile: 'fogra51', convertImages: false };
// #endregion

// #region cover-type: the paragraph styles the cover's text is set in
const style = (id, fontFamily, size, lead, color, extra) => ({ id, fontFamily, fontSize: pt(size),
  lineHeight: pt(lead), color, italicColor: color, firstLineIndent: mm(0), textAlign: 'left',
  hyphenation: false, ...extra });
const caps = (tracking) => ({ fontWeight: 700, letterSpacing: pt(tracking) });
const mid = { textAlign: 'center' };
const coverStyles = [
  style('cover-title', 'Alegreya SC', 40, 40, col('cream'), { ...mid, fontWeight: 500 }),
  style('cover-subtitle', 'Alegreya', 13, 17, col('cream'), { ...mid, italic: true }),
  style('cover-author', 'Alegreya Sans SC', 9, 12, col('ochre'), { ...mid, ...caps(1.6),
    marginTop: pt(9) }),
  style('cover-spine', 'Alegreya Sans SC', 7, 8, col('cream'), { ...mid, ...caps(1.1) }),
  style('cover-quote', 'Alegreya', 13, 17, col('ochre'), { ...mid, italic: true,
    marginBottom: pt(16) }),
  style('cover-blurb', 'Alegreya', 10.5, 14.5, col('cream'), { marginBottom: pt(7) }),
  style('cover-note', 'Alegreya Sans SC', 8, 11, col('ochre'), { ...caps(1.2),
    marginTop: pt(4) }),
];
// #endregion

// #region pages: the book block, a chapbook of verse
const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [125, 200, 22, 24, 19, 17, 15]; // mm, pt
const at = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(size && { size }) });
const text = (id, content, look, place) => ({ kind: 'text', id, content, align: 'center',
  overflow: 'wrap', placement: place, ...look });
const face = (fontFamily, size, color, x) => ({ fontFamily, fontSize: pt(size), color, ...x });
const label = (size, color = col('muted')) => face('Alegreya Sans SC', size, color, caps(size / 6));
const sc = (size, extra) => face('Alegreya SC', size, col('ink'), { fontWeight: 500, ...extra });
const none = { header: { elements: [] }, footer: { elements: [] }, numbered: false, toc: false };
const design = (minHeight, elements) => ({ enabled: true, minHeight: mm(minHeight),
  slot: { elements } });
const page = (parity) => ({ breakBefore: { enabled: true, parity } });
const rule = (id, y, to = 'page') => ({ kind: 'rule', id, direction: 'horizontal',
  thickness: pt(0.6), color: col('accent'), placement: at(to, 'top', 0, y, { width: mm(12) }) });
const headingStyles = [
  { ...none, id: 'half-title', advancedDesign: design(60, [
    text('t', '{title}', sc(18), at('page', 'top', 0, 64))]) },
  { ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
    text('t', '{title}', sc(34), at('page', 'top', 0, 50)),
    text('s', '{subtitle}', face('Alegreya', 13, col('ink'), { italic: true }),
      at('page', 'top', 0, 66)),
    rule('r', 76),
    text('a', '{author}', label(8.5, col('accent')), at('page', 'top', 0, 81)),
    text('c', '{attr.credit}', face('Alegreya', 9.5, col('muted'), { italic: true }),
      at('page', 'top', 0, 120, { width: mm(76) })),
    text('i', '{attr.imprint}', label(7.5), at('page', 'bottom', 0, -28)),
  ]) },
  { ...none, ...page('even'), id: 'rights',
    advancedDesign: design(92, [rule('r', 86, 'container')]) },
  // The poem opens on a recto, sunk 46 mm, its title in small capitals over a short rule.
  { ...page('odd'), id: 'poem', toc: false, header: { elements: [] }, advancedDesign: design(46, [
    text('t', '{titleText}', sc(19), at('container', 'top', 0, 18)),
    text('n', '{attr.note}', face('Alegreya', 10.5, col('muted'), { italic: true }),
      at('container', 'top', 0, 28, { width: mm(80) })),
    rule('r', 38, 'container')]) },
  { ...none, ...page('odd'), id: 'colophon', advancedDesign: design(64, [
    rule('r', 56, 'container')]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.8), parity, pages: 'body' },
  at('page', 'top', 0, 11));
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(W), height: mm(H), dpi: 300,
    backgroundColor: col('paper'),
    margins: { top: mm(TOP), bottom: mm(FOOT), left: mm(INNER), right: mm(OUTER), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Alegreya', fontSize: pt(11), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false, avoidWidows: true,
    hyphenation: { enabled: true }, optimalLineBreaking: true, avoidOrphans: true },
  headings: { fontFamily: 'Alegreya SC', color: col('ink'), textAlign: 'center' },
  headingStyles,
  paragraphStyles: [
    style('verse', 'Alegreya', 11, LEAD, col('ink')),
    style('rights', 'Alegreya', 8, 11, col('muted'), { marginBottom: pt(5) }),
    style('colophon', 'Alegreya', 9.5, 13, col('muted'), { ...mid, italic: true }),
    ...coverStyles,
  ],
  header: { elements: [head('v', '{author}', 'even'), head('r', '{title}', 'odd')] },
  footer: { elements: [text('f', '{pageNumber}', { ...face('Alegreya', 9, col('ink')),
    pages: 'body' }, at('page', 'bottom', 0, -13))] },
  print, production, cover, folio,
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The poem runs on through two files (each within the Cookbook's 2,500 words), cut between
// stanzas. The cover's text is a third: the back cover's frame.
const markdown = String.raw`---
title: "Coplas"
subtitle: "on the Death of His Father"
author: "Jorge Manrique"
---

# Coplas {style="half-title"}

# Coplas {style="title-page" credit="Translated from the Spanish by Henry Wadsworth Longfellow" imprint="Taller de la Mar · Ocaña"}

# Rights {style="rights"}

:::paragraphs{style="rights"}
Jorge Manrique wrote the *Coplas* after the death of his father, Rodrigo Manrique, Master of the Order of Santiago, at Ocaña on 11 November 1476. Henry Wadsworth Longfellow’s translation was first published in Boston in 1833; the text follows the Household Edition of his poems (1902), Project Gutenberg eBook 1365, and is in the public domain.

Paperback · ISBN 978-84-0000-199-5 · a sample number, assigned to no book.

Cover: four colours on 300 g/m² board, a spot gloss varnish over the painting, the cartouche in gold foil stamped over an emboss, and a blind emboss on the back. Cover painting generated with diffusion models.

Set in Alegreya, Alegreya SC and Alegreya Sans SC (SIL OFL) on 120 g/m² cream book wove.
:::

# Coplas de Manrique {style="poem" note="On the death of Don Rodrigo Manrique, his father"}

:::verse{style="verse" keepStanzas=6}
O let the soul her slumbers break,
Let thought be quickened, and awake;
    Awake to see
How soon this life is past and gone,
And death comes softly stealing on,
    How silently!

Swiftly our pleasures glide away,
Our hearts recall the distant day
    With many sighs;
The moments that are speeding fast
We heed not, but the past,—the past,
    More highly prize.

Onward its course the present keeps,
Onward the constant current sweeps,
    Till life is done;
And, did we judge of time aright,
The past and future in their flight
    Would be as one.

Let no one fondly dream again,
That Hope and all her shadowy train
    Will not decay;
Fleeting as were the dreams of old,
Remembered like a tale that’s told,
    They pass away.

Our lives are rivers, gliding free
To that unfathomed, boundless sea,
    The silent grave!
Thither all earthly pomp and boast
Roll, to be swallowed up and lost
    In one dark wave.

Thither the mighty torrents stray,
Thither the brook pursues its way,
    And tinkling rill,
There all are equal; side by side
The poor man and the son of pride
    Lie calm and still.

I will not here invoke the throng
Of orators and sons of song,
    The deathless few;
Fiction entices and deceives,
And, sprinkled o’er her fragrant leaves,
    Lies poisonous dew.

To One alone my thoughts arise,
The Eternal Truth, the Good and Wise,
    To Him I cry,
Who shared on earth our common lot,
But the world comprehended not
    His deity.

This world is but the rugged road
Which leads us to the bright abode
    Of peace above;
So let us choose that narrow way,
Which leads no traveller’s foot astray
    From realms of love,

Our cradle is the starting-place,
Life is the running of the race,
    We reach the goal
When, in the mansions of the blest,
Death leaves to its eternal rest
    The weary soul.

Did we but use it as we ought,
This world would school each wandering thought
    To its high state.
Faith wings the soul beyond the sky,
Up to that better world on high,
    For which we wait.

Yes, the glad messenger of love,
To guide us to our home above,
    The Saviour came;
Born amid mortal cares and fears.
He suffered in this vale of tears
    A death of shame.

Behold of what delusive worth
The bubbles we pursue on earth,
    The shapes we chase,
Amid a world of treachery!
They vanish ere death shuts the eye,
    And leave no trace.

Time steals them from us, chances strange,
Disastrous accident, and change,
    That come to all;
Even in the most exalted state,
Relentless sweeps the stroke of fate;
    The strongest fall.

Tell me, the charms that lovers seek
In the clear eye and blushing cheek,
    The hues that play
O’er rosy lip and brow of snow,
When hoary age approaches slow,
    Ah; where are they?

The cunning skill, the curious arts,
The glorious strength that youth imparts
    In life’s first stage;
These shall become a heavy weight,
When Time swings wide his outward gate
    To weary age.

The noble blood of Gothic name,
Heroes emblazoned high to fame,
    In long array;
How, in the onward course of time,
The landmarks of that race sublime
    Were swept away!

Some, the degraded slaves of lust,
Prostrate and trampled in the dust,
    Shall rise no more;
Others, by guilt and crime, maintain
The scutcheon, that without a stain,
    Their fathers bore.

Wealth and the high estate of pride,
With what untimely speed they glide,
    How soon depart!
Bid not the shadowy phantoms stay,
The vassals of a mistress they,
    Of fickle heart.

These gifts in Fortune’s hands are found;
Her swift revolving wheel turns round,
    And they are gone!
No rest the inconstant goddess knows,
But changing, and without repose,
    Still hurries on.

Even could the hand of avarice save
Its gilded baubles till the grave
    Reclaimed its prey,
Let none on such poor hopes rely;
Life, like an empty dream, flits by,
    And where are they?

Earthly desires and sensual lust
Are passions springing from the dust,
    They fade and die;
But in the life beyond the tomb,
They seal the immortal spirits doom
    Eternally!

The pleasures and delights, which mask
In treacherous smiles life’s serious task,
    What are they, all,
But the fleet coursers of the chase,
And death an ambush in the race,
    Wherein we fall?

No foe, no dangerous pass, we heed,
Brook no delay, but onward speed
    With loosened rein;
And, when the fatal snare is near,
We strive to check our mad career,
    But strive in vain.

Could we new charms to age impart,
And fashion with a cunning art
    The human face,
As we can clothe the soul with light,
And make the glorious spirit bright
    With heavenly grace,

How busily each passing hour
Should we exert that magic power,
    What ardor show,
To deck the sensual slave of sin,
Yet leave the freeborn soul within,
    In weeds of woe!

Monarchs, the powerful and the strong,
Famous in history and in song
    Of olden time,
Saw, by the stern decrees of fate,
Their kingdoms lost, and desolate
    Their race sublime.

Who is the champion? who the strong?
Pontiff and priest, and sceptred throng?
    On these shall fall
As heavily the hand of Death,
As when it stays the shepherd’s breath
    Beside his stall.

I speak not of the Trojan name,
Neither its glory nor its shame
    Has met our eyes;
Nor of Rome’s great and glorious dead,
Though we have heard so oft, and read,
    Their histories.

Little avails it now to know
Of ages passed so long ago,
    Nor how they rolled;
Our theme shall be of yesterday,
Which to oblivion sweeps away,
    Like day’s of old.

Where is the King, Don Juan?  Where
Each royal prince and noble heir
    Of Aragon?
Where are the courtly gallantries?
The deeds of love and high emprise,
    In battle done?

Tourney and joust, that charmed the eye,
And scarf, and gorgeous panoply,
    And nodding plume,
What were they but a pageant scene?
What but the garlands, gay and green,
    That deck the tomb?

Where are the high-born dames, and where
Their gay attire, and jewelled hair,
    And odors sweet?
Where are the gentle knights, that came
To kneel, and breathe love’s ardent flame,
    Low at their feet?

Where is the song of Troubadour?
Where are the lute and gay tambour
    They loved of yore?
Where is the mazy dance of old,
The flowing robes, inwrought with gold,
    The dancers wore?

And he who next the sceptre swayed,
Henry, whose royal court displayed
    Such power and pride;
O, in what winning smiles arrayed,
The world its various pleasures laid
    His throne beside!

But O how false and full of guile
That world, which wore so soft a smile
    But to betray!
She, that had been his friend before,
Now from the fated monarch tore
    Her charms away.

The countless gifts, the stately walls,
The loyal palaces, and halls
    All filled with gold;
Plate with armorial bearings wrought,
Chambers with ample treasures fraught
    Of wealth untold;

The noble steeds, and harness bright,
And gallant lord, and stalwart knight,
    In rich array,
Where shall we seek them now?  Alas!
Like the bright dewdrops on the grass,
    They passed away.

His brother, too, whose factious zeal
Usurped the sceptre of Castile,
    Unskilled to reign;
What a gay, brilliant court had he,
When all the flower of chivalry
    Was in his train!

But he was mortal; and the breath,
That flamed from the hot forge of Death,
    Blasted his years;
Judgment of God! that flame by thee,
When raging fierce and fearfully,
    Was quenched in tears!

Spain’s haughty Constable, the true
And gallant Master, whom we knew
    Most loved of all;
Breathe not a whisper of his pride,
He on the gloomy scaffold died,
    Ignoble fall!

The countless treasures of his care,
His villages and villas fair,
    His mighty power,
What were they all but grief and shame,
Tears and a broken heart, when came
    The parting hour?
:::
`;
const part2 = String.raw`:::verse{style="verse" keepStanzas=6}
His other brothers, proud and high,
Masters, who, in prosperity,
    Might rival kings;
Who made the bravest and the best
The bondsmen of their high behest,
    Their underlings;

What was their prosperous estate,
When high exalted and elate
    With power and pride?
What, but a transient gleam of light,
A flame, which, glaring at its height,
    Grew dim and died?

So many a duke of royal name,
Marquis and count of spotless fame,
    And baron brave,
That might the sword of empire wield,
All these, O Death, hast thou concealed
    In the dark grave!

Their deeds of mercy and of arms,
In peaceful days, or war’s alarms,
    When thou dost show.
O Death, thy stern and angry face,
One stroke of thy all-powerful mace
    Can overthrow.

Unnumbered hosts, that threaten nigh,
Pennon and standard flaunting high,
    And flag displayed;
High battlements intrenched around,
Bastion, and moated wall, and mound,
    And palisade,

And covered trench, secure and deep,
All these cannot one victim keep,
    O Death, from thee,
When thou dost battle in thy wrath,
And thy strong shafts pursue their path
    Unerringly.

O World! so few the years we live,
Would that the life which thou dost give
    Were life indeed!
Alas! thy sorrows fall so fast,
Our happiest hour is when at last
    The soul is freed.

Our days are covered o’er with grief,
And sorrows neither few nor brief
    Veil all in gloom;
Left desolate of real good,
Within this cheerless solitude
    No pleasures bloom.

Thy pilgrimage begins in tears,
And ends in bitter doubts and fears,
    Or dark despair;
Midway so many toils appear,
That he who lingers longest here
    Knows most of care.

Thy goods are bought with many a groan,
By the hot sweat of toil alone,
    And weary hearts;
Fleet-footed is the approach of woe,
But with a lingering step and slow
    Its form departs.

And he, the good man’s shield and shade,
To whom all hearts their homage paid,
    As Virtue’s son,
Roderic Manrique, he whose name
Is written on the scroll of Fame,
    Spain’s champion;

His signal deeds and prowess high
Demand no pompous eulogy.
    Ye saw his deeds!
Why should their praise in verse be sung?
The name, that dwells on every tongue,
    No minstrel needs.

To friends a friend; how kind to all
The vassals of this ancient hall
    And feudal fief!
To foes how stern a foe was he!
And to the valiant and the free
    How brave a chief!

What prudence with the old and wise:
What grace in youthful gayeties;
    In all how sage!
Benignant to the serf and slave,
He showed the base and falsely brave
    A lion’s rage.

His was Octavian’s prosperous star,
The rush of Caesar’s conquering car
    At battle’s call;
His, Scipio’s virtue; his, the skill
And the indomitable will
    Of Hannibal.

His was a Trajan’s goodness, his
A Titus’ noble charities
    And righteous laws;
The arm of Hector, and the might
Of Tully, to maintain the right
    In truth’s just cause;

The clemency of Antonine,
Aurelius’ countenance divine,
    Firm, gentle, still;
The eloquence of Adrian,
And Theodosius’ love to man,
    And generous will;

In tented field and bloody fray,
An Alexander’s vigorous sway
    And stern command;
The faith of Constantine; ay, more,
The fervent love Camillus bore
    His native land.

He left no well-filled treasury,
He heaped no pile of riches high,
    Nor massive plate;
He fought the Moors, and, in their fall,
City and tower and castled wall
    Were his estate.

Upon the hard-fought battle-ground,
Brave steeds and gallant riders found
    A common grave;
And there the warrior’s hand did gain
The rents, and the long vassal train,
    That conquest gave.

And if, of old, his halls displayed
The honored and exalted grade
    His worth had gained,
So, in the dark, disastrous hour,
Brothers and bondsmen of his power
    His hand sustained.

After high deeds, not left untold,
In the stern warfare, which of old
    ’T was his to share,
Such noble leagues he made, that more
And fairer regions, than before,
    His guerdon were.

These are the records, half effaced,
Which, with the hand of youth, he traced
    On history’s page;
But with fresh victories he drew
Each fading character anew
    In his old age.

By his unrivalled skill, by great
And veteran service to the state,
    By worth adored,
He stood, in his high dignity,
The proudest knight of chivalry,
    Knight of the Sword.

He found his cities and domains
Beneath a tyrant’s galling chains
    And cruel power;
But by fierce battle and blockade,
Soon his own banner was displayed
    From every tower.

By the tried valor of his hand,
His monarch and his native land
    Were nobly served;
Let Portugal repeat the story,
And proud Castile, who shared the glory
    His arms deserved.

And when so oft, for weal or woe,
His life upon the fatal throw
    Had been cast down;
When he had served, with patriot zeal,
Beneath the banner of Castile,
    His sovereign’s crown;

And done such deeds of valor strong,
That neither history nor song
    Can count them all;
Then, on Ocaña’s castled rock,
Death at his portal came to knock,
    With sudden call,

Saying, “Good Cavalier, prepare
To leave this world of toil and care
    With joyful mien;
Let thy strong heart of steel this day
Put on its armor for the fray,
    The closing scene.

“Since thou hast been, in battle-strife,
So prodigal of health and life,
    For earthly fame,
Let virtue nerve thy heart again;
Loud on the last stern battle-plain
    They call thy name.

“Think not the struggle that draws near
Too terrible for man, nor fear
    To meet the foe;
Nor let thy noble spirit grieve,
Its life of glorious fame to leave
    On earth below.

“A life of honor and of worth
Has no eternity on earth,
    ’T is but a name;
And yet its glory far exceeds
That base and sensual life, which leads
    To want and shame.

“The eternal life, beyond the sky,
Wealth cannot purchase, nor the high
    And proud estate;
The soul in dalliance laid, the spirit
Corrupt with sin, shall not inherit
    A joy so great.

“But the good monk, in cloistered cell,
Shall gain it by his book and bell,
    His prayers and tears;
And the brave knight, whose arm endures
Fierce battle, and against the Moors
    His standard rears.

“And thou, brave knight, whose hand has poured
The life-blood of the Pagan horde
    O’er all the land,
In heaven shalt thou receive, at length,
The guerdon of thine earthly strength
    And dauntless hand.

“Cheered onward by this promise sure,
Strong in the faith entire and pure
    Thou dost profess,
Depart, thy hope is certainty,
The third, the better life on high
    Shalt thou possess.”

“O Death, no more, no more delay;
My spirit longs to flee away,
    And be at rest;
The will of Heaven my will shall be,
I bow to the divine decree,
    To God’s behest.

“My soul is ready to depart,
No thought rebels, the obedient heart
    Breathes forth no sigh;
The wish on earth to linger still
Were vain, when ’t is God’s sovereign will
    That we shall die.

“O thou, that for our sins didst take
A human form, and humbly make
    Thy home on earth;
Thou, that to thy divinity
A human nature didst ally
    By mortal birth,

“And in that form didst suffer here
Torment, and agony, and fear,
    So patiently;
By thy redeeming grace alone,
And not for merits of my own,
    O, pardon me!”

As thus the dying warrior prayed,
Without one gathering mist or shade
    Upon his mind;
Encircled by his family,
Watched by affection’s gentle eye
    So soft and kind;

His soul to Him, who gave it, rose;
God lead it to its long repose,
    Its glorious rest!
And, though the warrior’s sun has set,
Its light shall linger round us yet,
    Bright, radiant, blest.
:::

# Colophon {style="colophon"}

:::paragraphs{style="colophon"}
Taller de la Mar · Ocaña

Set in Alegreya (SIL OFL) · Translation by Henry Wadsworth Longfellow, public domain
:::
`;
const coverText = String.raw`:::frame{slot="back"}
:::paragraphs{style="cover-quote"}
Our lives are rivers, gliding free\
To that unfathomed, boundless sea,\
The silent grave!
:::

:::paragraphs{style="cover-blurb"}
In November 1476 Rodrigo Manrique, Master of the Order of Santiago, died in his house at Ocaña after forty years of war on the frontier of Granada and in the civil wars of Castile. His son Jorge, a soldier and a poet, wrote forty stanzas on his death. They begin with the shortness of life, go through the kings and favourites of his own century, and end at the old man’s bedside.
:::

:::paragraphs{style="cover-blurb"}
Longfellow translated the poem at twenty-six, after his first journey through Spain, and published it in Boston in 1833.
:::

:::paragraphs{style="cover-note"}
Translated by Henry Wadsworth Longfellow
:::
:::
`;
const resources = [{ id: 'river', typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: 'river.jpg', format: 'jpeg', width: 1100, height: 1740 },
  altText: t({ en: 'A ruined castle on a crag against a sunset sky, the sea shining far off, '
    + 'and below a broad river with poplars, a stone bridge and a boat moored in the reeds.',
  es: 'Un castillo en ruinas sobre un peñasco al ocaso, el mar que brilla a lo lejos y, abajo, '
    + 'un río ancho con chopos, un puente de piedra y una barca entre los juncos.' }) }];
await loadImage('river.jpg', asset('river-1100.jpg'));

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { Alegreya: ['400', '400i'], 'Alegreya SC': ['500'], 'Alegreya Sans SC': ['700'] };

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const book = await buildDocumentWithFonts({ markdown: `${markdown}\n\n${part2}`, resources },
  config, kitFonts(FONTS));

// #region sheet: the cover sheet, built from the pages just laid out
const built = buildCover({ config, version: 'paperback', pages: book.pages, markdown: coverText,
  metadata: book.metadata, resources });
if (!('config' in built)) throw new Error(built.issues.map((i) => i.kind).join(', '));
// The barcode's digits name OCR-B, which no font server has: the label face sets them.
for (const [id, bytes] of Object.entries(built.files)) {
  await loadSvg(id, new TextDecoder().decode(bytes)
    .replace(/font-family="[^"]*"/g, 'font-family="Alegreya Sans SC"'));
}
const sheet = await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS));
// #endregion

showPages(book, { title: t({ en: 'Coplas · a paperback with foil, varnish and emboss',
  es: 'Coplas · una rústica con oro, barniz y gofrado' }) });

// #region views: the sheet as it prints, then what each plate covers
// 'flat' paints the inks: the foil in its colour, the varnish and the emboss not at all.
// 'map' marks the special plates in false colour over a faded sheet, 'sheen' rakes a light
// across it. The emboss plate is drawn from the page's technical plates, the outlines the
// PDF fills on its Emboss separation.
const leaf = sheet.pages[0];
const scale = 1100 / leaf.width;
const outline = (ctx, paths) => {
  ctx.beginPath();
  for (const c of paths.flat()) {
    if (c.op === 'M') ctx.moveTo(c.x, c.y);
    else if (c.op === 'L') ctx.lineTo(c.x, c.y);
    else if (c.op === 'C') ctx.bezierCurveTo(c.x1, c.y1, c.x2, c.y2, c.x, c.y);
    else if (c.op === 'Q') ctx.quadraticCurveTo(c.x1, c.y1, c.x, c.y);
    else ctx.closePath();
  }
  ctx.fill('nonzero');
};
const VIEWS = [
  ['flat', t({ en: 'As it prints', es: 'Como se imprime' })],
  ['map', t({ en: 'The varnish and foil plates', es: 'Las planchas de barniz y oro' })],
  ['sheen', t({ en: 'Under a raking light', es: 'Con luz rasante' })],
  ['emboss', t({ en: 'The Emboss plate', es: 'La plancha de gofrado' })],
];
const views = document.createElement('section');
views.id = 'finish-views';
views.style.cssText = 'display: grid; grid-template-columns: repeat(2, minmax(0, 560px)); '
  + 'gap: 18px; justify-content: center; padding: 24px max(16px, calc(50% - 520px)); color: #ddd; '
  + 'font: 14px sans-serif';
for (const [mode, name] of VIEWS) {
  const [figure, canvas, caption] = ['figure', 'canvas', 'figcaption']
    .map((tag) => document.createElement(tag));
  figure.style.margin = '0';
  canvas.style.cssText = 'display: block; width: 100%';
  canvas.setAttribute('role', 'img');
  canvas.setAttribute('aria-label', `${t({ en: 'The cover sheet', es: 'El pliego' })}: ${name}`);
  renderPageToCanvas(leaf, sheet, canvas, { scale, finishes: mode === 'emboss' ? 'flat' : mode });
  if (mode === 'emboss') {
    // The die-maker's film: the plate in black on white, the sheet faded under it.
    const ctx = canvas.getContext('2d');
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.fillStyle = 'rgba(255, 255, 255, 0.86)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.setTransform(scale, 0, 0, scale, 0, 0);
    ctx.fillStyle = '#111';
    outline(ctx, (leaf.plates ?? []).flatMap((p) => p.paths));
  }
  caption.textContent = name;
  figure.append(canvas, caption);
  views.append(figure);
}
// What the preflight reads from the sheet: its spot plates and the reliefs it checks.
const spots = preflightDocument(sheet).find((i) => i.kind === 'spotInks');
const list = document.createElement('p');
list.style.cssText = 'grid-column: 1 / -1; margin: 0; text-align: center';
list.textContent = `${t({ en: 'Plates beside CMYK', es: 'Planchas además de CMYK' })}: `
  + [...(spots?.inks ?? []), ...new Set((leaf.plates ?? [])
    .map((p) => `${p.process[0].toUpperCase()}${p.process.slice(1)}`))].join(' · ');
views.append(list);
document.getElementById('pages').before(views);
// #endregion

// One file for the printer: the pages, then the sheet at its own size, with its plates.
offerPdf(() => renderToPdf([book, sheet], { 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 ───────────────────────────────────────────────────────────────────────
```

## アレンジ

### 紋章をデボスにする

デボスは形を厚紙に押し込みます。版はDebossとして別になります。

```diff
-    { id: 'emblem', process: 'emboss', shape: { outline: emblem,
+    { id: 'emblem', process: 'deboss', shape: { outline: emblem,
```

### 絵全体にニスをかける

絵の要素に1つの加工をかければ、2つの矩形はいりません。ニスはカルトゥーシュと書名にもかかります。

```diff
-    ...[[-3, 76], [127, 76]].map(([y, height], i) => ({ id: `gloss-${i + 1}`, process: 'varnish',
-      ink: col('varnish'), shape: { box: { zone: 'front', x: 0, y, width: 128, height } } })),
+    { id: 'gloss', process: 'varnish', ink: col('varnish'), shape: { element: 'art' } },
```

## よくあるつまずき

- エンボスやデボスが仕上がり線や折り目から3 mm以内にあると、プリフライトが知らせます（`reliefTrim`、`reliefFold`）。そこで厚紙が割れるからです。背の折り目から離してください。
- エンボスは画面には描かれません。PDFのEmboss分版で確かめるか、このレシピのように`page.plates`を描きます。
- テキストの枠に加工をかけると、表示でも印刷ファイルでも行が隠れます。書名をカルトゥーシュの空いた中央に置いたように、文字の一部は箔の外に残します。

## クレジット

- レシピ: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- テキスト: Coplas de Manrique, translated by Henry Wadsworth Longfellow (1833), from The Complete Poetical Works of Henry Wadsworth Longfellow (Household Edition, 1902), Project Gutenberg eBook #1365: Jorge Manrique ([出典](https://www.gutenberg.org/ebooks/1365)), パブリックドメイン
- テキスト: Coplas por la muerte de su padre, from the first critical edition by R. Foulché-Delbosc (1902), Project Gutenberg eBook #49333, spelling and punctuation modernised: Jorge Manrique ([出典](https://www.gutenberg.org/ebooks/49333)), パブリックドメイン
- 画像: The cover painting: a river at sunset running to the sea below a ruined castle, in oils: Generated With Diffusion Models, オリジナル
- 書体: Alegreya (OFL-1.1), Alegreya SC (OFL-1.1), Alegreya Sans SC (OFL-1.1)
- コード: MIT · サンプルの内容: CC-BY-4.0

## 関連レシピ

- [No. 188 · 濃紺の表紙に金の箔押し](https://postext.dev/ja/cookbook/gold-foil-poetry-cover.md): 金箔を加工付きの特色にします。PDFでは専用の版になり、Folioでは光り、紺の厚紙とクリームの紙はインキを刷りません。 · 難易度 3 (上級) · 詩歌
- [No. 196 · 袖付き並製本の表紙、背幅はページから](https://postext.dev/ja/cookbook/paperback-cover-with-flaps.md): 120 × 190 mm、袖60 mmの並製本。先に本文を組み、buildCoverがそのページから表紙用紙を作ります。背幅は紙の厚みどおりになります。 · 難易度 3 (上級) · 小説・戯曲・文芸
- [No. 197 · 上製本の表紙、カバーと見返し](https://postext.dev/ja/cookbook/hardcover-jacket-and-endpapers.md): 並製本のページをクロス装の上製本に仕立て直します。ISBNの違う版を一つ足し、buildCoverで表紙、カバー、前後の見返しを作ります。 · 難易度 3 (上級) · 小説・戯曲・文芸
