# 精装书的书壳、护封和环衬

> 把一本平装书的书页再装成布面精装：另一个版本，有自己的ISBN，再由buildCover做出书壳、护封和前后两张环衬。

- HTML版本: https://postext.dev/zh/cookbook/hardcover-jacket-and-endpapers
- 食谱 No. 197 · 输出与集成 · 难度 3 (高级) · 输出: Canvas, PDF
- 体裁: 小说、戏剧与文学散文
- 需要 postext ≥ 1.93.0, postext-pdf ≥ 1.93.0 · 已用 1.93.0, postext-pdf 1.93.0 测试，日期 2026-11-23
- 页面: [3](https://postext.dev/cookbook/hardcover-jacket-and-endpapers/en/p03.webp?v=37c1fac7), [4](https://postext.dev/cookbook/hardcover-jacket-and-endpapers/en/p04.webp?v=37c1fac7), [5](https://postext.dev/cookbook/hardcover-jacket-and-endpapers/en/p05.webp?v=37c1fac7), [7](https://postext.dev/cookbook/hardcover-jacket-and-endpapers/en/p07.webp?v=37c1fac7), [9](https://postext.dev/cookbook/hardcover-jacket-and-endpapers/en/p09.webp?v=37c1fac7), [21](https://postext.dev/cookbook/hardcover-jacket-and-endpapers/en/p21.webp?v=37c1fac7), [23](https://postext.dev/cookbook/hardcover-jacket-and-endpapers/en/p23.webp?v=37c1fac7), [1](https://postext.dev/cookbook/hardcover-jacket-and-endpapers/en/p38.webp?v=37c1fac7), [1](https://postext.dev/cookbook/hardcover-jacket-and-endpapers/en/p39.webp?v=37c1fac7), [1](https://postext.dev/cookbook/hardcover-jacket-and-endpapers/en/p40.webp?v=37c1fac7), [2](https://postext.dev/cookbook/hardcover-jacket-and-endpapers/en/p41.webp?v=37c1fac7)
- PDF: https://postext.dev/cookbook/hardcover-jacket-and-endpapers/en/hardcover-jacket-and-endpapers.pdf?v=37c1fac7
- 在沙盒中打开: https://postext.dev/zh/sandbox#recipe=hardcover-jacket-and-endpapers&lang=en (.postext: https://postext.dev/cookbook/hardcover-jacket-and-endpapers/en/hardcover-jacket-and-endpapers.postext)
- 最后更新: 2026-11-23
- 其他语言: [en](https://postext.dev/en/cookbook/hardcover-jacket-and-endpapers.md), [es](https://postext.dev/es/cookbook/hardcover-jacket-and-endpapers.md), [ca](https://postext.dev/ca/cookbook/hardcover-jacket-and-endpapers.md), [de](https://postext.dev/de/cookbook/hardcover-jacket-and-endpapers.md), [fr](https://postext.dev/fr/cookbook/hardcover-jacket-and-endpapers.md), [it](https://postext.dev/it/cookbook/hardcover-jacket-and-endpapers.md), [pt](https://postext.dev/pt/cookbook/hardcover-jacket-and-endpapers.md), [ja](https://postext.dev/ja/cookbook/hardcover-jacket-and-endpapers.md), [ar](https://postext.dev/ar/cookbook/hardcover-jacket-and-endpapers.md)

## 简单来说

还是贝克尔的两篇传说，这回做成精装书：包住纸板的布面、套在外面的纸护封，以及粘在封面里侧的彩绘纸张。书页不变；每个版本有自己的展开图和ISBN。

## 成品一览

还是那本带勒口平装书里贝克尔的两篇传说，这次再装订一遍，做成120 × 190毫米的精装书。37页书页原样不动。这本书现在有两个版本，各有自己的装订方式和ISBN，精装版要交给装订厂四张展开图。书壳裱深绿色的布，封面和书脊上烫金印出书名和作者。护封上是那幅画、简介文字、条码和前后两个勒口。封面里侧是两张彩绘环衬：前面是杜罗河畔的索里亚，后面是第二篇传说里的那眼泉水。

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

- 怎样用平装书同样的书页，做出精装书的书壳、护封和环衬？

## 简短回答

```js
// script.js, 行 29–55
// The paperback is Nº 196's, on the printer's own profile. The hardcover takes the built-in
// flat-spine case; `flaps` on a case means a dust jacket, and `caseMaterial: 'cloth'` a case
// covered in cloth and stamped, under the jacket. Spines, boards and turn-ins come from the
// laid-out pages on the paper of `folio.paper`.
const production = {
  bindings: [{ id: 'pur-flaps', name: 'PUR perfect binding, 60 mm flaps', style: 'perfect',
    signature: 16, measures: { flapWidth: 60, bleed: 3, spineAllowance: 0.5 } }],
  versions: [
    { id: 'paperback', name: t({ en: 'Paperback', es: 'Rústica' }), binding: 'pur-flaps',
      flaps: true, isbn: '978-84-0000-196-4', isbnAddOn: '90000' },
    { id: 'hardcover', name: t({ en: 'Hardcover', es: 'Cartoné' }), binding: 'case-flat',
      flaps: true, caseMaterial: 'cloth', isbn: '978-84-0000-197-1', isbnAddOn: '90000' },
  ],
};
// 100 g/m² bulky cream wove at a bulk of 2.4: each leaf is 100 × 2.4 = 240 µm thick.
const folio = { paper: { type: 'bookWove', grammage: 100, bulk: 2.4, shade: '#f7f1e3' } };
// The book's cover design (the paperback's, the jacket's): a night ground and the painting
// on the front panel, into the bleed, whatever the panel's width. `sheets` gives the
// hardcover's other sheets a design of their own: the case its cloth, each endpaper its
// painting across both leaves.
const cover = { background: col('night'), verticalAlign: { back: 'middle' },
  image: { resourceId: 'moncayo', area: 'front', focus: { x: 0.5, y: 0.4 } },
  sheets: {
    case: { background: col('cloth') },
    endpaperFront: { image: { resourceId: 'soria' } },
    endpaperBack: { image: { resourceId: 'fuente' } },
  } };
```

## 用料

**讲解**

- [封面印张](https://postext.dev/zh/docs/print-covers.md#版面及其区域): buildCover排出一个印刷版本的封面印张：封底、书脊和封面，带勒口，或精装的封壳、护封和环衬，含出血和折线标记。cover设置负责它的设计，书中的一份Markdown文档填写各个区域。
- [印刷版本、ISBN与书脊](https://postext.dev/zh/docs/print-covers.md#书的版本): production.versions为书的每种装订指定装订配置和ISBN，ISBN印成EAN-13条码；书脊宽度由页数和纸张算出。production.collection再加上整部作品的ISBN及其书目。

**还用到**

- [封面、扉页和版权页](https://postext.dev/zh/docs/configuration-styles.md#标题样式)
- [标题样式](https://postext.dev/zh/docs/configuration-styles.md#标题样式)
- [设计过的章首页](https://postext.dev/zh/docs/configuration-headings.md#通栏与高级设计)
- [页面设计中的文字、线条和框](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚)
- [文档元数据](https://postext.dev/zh/docs/document-format.md#前置元数据)
- [段落样式](https://postext.dev/zh/docs/configuration-styles.md#段落样式)
- [目录](https://postext.dev/zh/docs/configuration-notes-references.md#目录)
- [书眉与页码](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚)
- [作为资源的图和表](https://postext.dev/zh/docs/document-format-resources.md#资源)
- [语义调色板](https://postext.dev/zh/docs/configuration-fonts-colors-viewers.md#调色板)
- [导出PDF](https://postext.dev/zh/docs/configuration-pdf-output.md#生成pdf)
- [在Canvas上绘制页面](https://postext.dev/zh/docs/configuration-programmatic-usage.md#把页面渲染为位图)
- [纸张、装订、台面与光照（Folio）](https://postext.dev/zh/docs/configuration-fonts-colors-viewers.md#书页视图配置)
- [标题属性](https://postext.dev/zh/docs/document-format.md#标题属性)
- [纸张颜色](https://postext.dev/zh/docs/configuration-page-layout.md#页面)
- [按页面角色显示书眉](https://postext.dev/zh/docs/configuration-headers-footers.md#文本元素)
- [嵌入PDF的字体](https://postext.dev/zh/docs/configuration-pdf-output.md#为什么需要字体提供函数)
- [分节书眉](https://postext.dev/zh/docs/configuration-styles.md#标题样式)
- [不编号的章](https://postext.dev/zh/docs/configuration-styles.md#标题样式)

**配置一览**

- [`bodyText`](https://postext.dev/zh/docs/configuration-text.md#正文), [`colorPalette`](https://postext.dev/zh/docs/configuration-fonts-colors-viewers.md#调色板), [`cover`](https://postext.dev/zh/docs/print-covers.md#封面的设计), [`folio`](https://postext.dev/zh/docs/configuration-html-folio-epub.md#外观), [`footer`](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚), [`header`](https://postext.dev/zh/docs/configuration-headers-footers.md#页眉与页脚), [`headingStyles`](https://postext.dev/zh/docs/configuration-styles.md#标题样式), [`headings`](https://postext.dev/zh/docs/configuration-headings.md#标题), [`layout`](https://postext.dev/zh/docs/configuration-page-layout.md#版式), [`locale`](https://postext.dev/zh/docs/configuration-language.md#断词), [`page`](https://postext.dev/zh/docs/configuration-page-layout.md#页面), [`paragraphStyles`](https://postext.dev/zh/docs/configuration-styles.md#段落样式), [`production`](https://postext.dev/zh/docs/print-covers.md#书的版本), [`toc`](https://postext.dev/zh/docs/configuration-notes-references.md#目录)

**API**

- [`buildCover`](https://postext.dev/zh/docs/print-covers.md#在代码中), [`buildDocumentWithFonts`](https://postext.dev/zh/docs/configuration-programmatic-usage.md#排版前加载字体), [`decompressWoff2`](https://postext.dev/zh/docs/configuration-pdf-output.md#浏览器字体提供函数fontsource--woff2), [`inlineSvgFonts`](https://postext.dev/zh/docs/configuration-resources.md#svg文字中的字体), [`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)

**字体**

- Crimson Pro (OFL-1.1), Cormorant Garamond (OFL-1.1), Josefin Sans (OFL-1.1)

## 做法

### 1 · 一个书芯，两个版本

代码就是上面的[简短回答](https://postext.dev/zh/cookbook/hardcover-jacket-and-endpapers.md#简短回答)。两个版本读取同一个`folio.paper`和同一批排好的书页：37页，向上取整为三个16页的书帖，24张，每张厚240微米。平装版加上胶的余量，书脊6.3毫米。精装版再加上两块2毫米的纸板，书脊10.3毫米。每个版本有自己的ISBN，两个都是出版社号段里的示例号码，不属于任何一本书。书脊做成平背，因为不到6毫米厚的书芯太薄，没法起圆；换成`case-round`会再加3毫米，做成圆背。书壳用布面（`cloth`），因为画、文字和条码都已经在护封上，底下烫一个书名就够了。

### 2 · 书壳：包边、书槽和飘口

```js
// script.js, 行 545–562
// One call per sheet, with the same config and the same cover text: each sheet takes its
// design from `cover.sheets` (the jacket, the book's) and the frames meant for it. The
// barcode goes on the jacket alone, the sheet a till scans.
const built = {};
for (const sheet of ['cover', 'jacket', 'endpaperFront', 'endpaperBack']) {
  const made = buildCover({ config, sheet, pages: book.pages, version: 'hardcover',
    markdown: coverText, metadata: book.metadata, resources });
  if (!('config' in made)) throw new Error(made.issues.map((i) => i.kind).join(', '));
  // The barcode's digits name OCR-B, which no font server has: set in the label face.
  for (const [id, bytes] of Object.entries(made.files)) {
    await loadSvg(id, new TextDecoder().decode(bytes)
      .replace(/font-family="[^"]*"/g, 'font-family="Josefin Sans"'));
  }
  built[sheet] = made;
}
const sheetDoc = (b) => buildDocumentWithFonts(b.content, b.config, kitFonts(FONTS));
const caseDoc = await sheetDoc(built.cover);
const jacketDoc = await sheetDoc(built.jacket);
```

平装书的封面按成品尺寸裁切，勒口在前口折进去。精装书的书壳是一层包住两块纸板的面料。每块纸板在书脊一侧比书页窄7毫米，在天头、地脚和前口比书页多出3毫米（飘口），所以是116 × 196毫米。每块纸板和书脊之间留一道7毫米的书槽，书壳在这里弯折。四周还有15毫米的包边翻折到纸板边上，所以布面的底色一直铺到286.3 × 226毫米的整张展开图。

每张展开图都用同一个`config`和同一份封面文字来做。书壳的设计来自`cover.sheets.case`，只有一层布面底色；文字来自标了`sheet="case"`的文本框：封面纸板和书脊上的书名、副书名和作者，用的`case-`样式就是护封的样式改成金色；封底纸板上放一个空文本框，布面上就不会出现内容简介。条码只印在护封上，收银台扫的就是它。

### 3 · 护封沿用封面的设计和文字

```js
// script.js, 行 59–81
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: 600, textTransform: 'uppercase',
  letterSpacing: pt(tracking) });
const coverStyles = [
  style('cover-title', 'Cormorant Garamond', 40, 40, col('bone'), { fontWeight: 600,
    textAlign: 'center', marginTop: mm(12) }),
  style('cover-subtitle', 'Cormorant Garamond', 15, 19, col('bone'), { italic: true,
    textAlign: 'center' }),
  style('cover-author', 'Josefin Sans', 8.5, 11, col('gold'), { ...caps(1.8),
    textAlign: 'center', marginTop: pt(16) }),
  style('cover-spine', 'Josefin Sans', 7.5, 9, col('bone'), { ...caps(1.2), textAlign: 'center' }),
  style('cover-blurb', 'Crimson Pro', 10.5, 14.5, col('bone'), { marginBottom: pt(7) }),
  style('cover-note', 'Crimson Pro', 10.5, 14.5, col('gold'), { italic: true }),
  style('flap-head', 'Josefin Sans', 7.5, 10, col('gold'), caps(1.4)),
  style('flap-text', 'Crimson Pro', 9.6, 13.2, col('bone'), { marginTop: pt(5) }),
];
// The case's frames (`sheet="case"` in the cover text) set the jacket's lines in gold, the
// colour the cloth is stamped in.
const stamped = coverStyles.filter((s) => /title|subtitle|author|spine/.test(s.id))
  .map((s) => ({ ...s, id: s.id.replace('cover-', 'case-'), color: col('gold'),
    italicColor: col('gold') }));
```

护封在`cover.sheets`里没有自己的一项，所以用书本身的`cover`和不带`sheet`的文本框，段落样式和封面Markdown都与平装版相同；书壳的文本框在这里不用，护封的封面和书脊就从元数据里取文字。它的面板更宽：每块盖住一块纸板、书槽，再多3毫米折到纸板边上，一共126毫米。勒口宽到80毫米，是书页宽度的三分之二，也是护封的默认值。画铺满封面面板，一直到折线，条码在封底面板上，书店在那里扫码。

### 4 · 两张环衬放在一个文档里

```js
// script.js, 行 566–572
// Both endpapers are the size of two pages: one document holds them, a page each, the
// back's template renamed so the two templates do not share an id.
const [ef, eb] = [built.endpaperFront, built.endpaperBack];
const back = { ...eb.config.pageTemplates.at(-1), id: 'endpaper-back' };
const endpapers = await buildDocumentWithFonts({ ...ef.content, markdown: `${ef.content.markdown}`
  + `\n\n${eb.content.markdown.replace('postext-cover', back.id)}` },
{ ...ef.config, pageTemplates: [...ef.config.pageTemplates, back] }, kitFonts(FONTS));
```

一张环衬有两页宽：一半粘在纸板上，另一半是可以翻动的扉页。前环衬粘在纸板上的那一半在左边，后环衬在右边。每张展开图246 × 196毫米，天头、地脚和外侧各有3毫米出血，折线处没有出血，那里有一条5毫米的胶条把它粘在书芯上。两幅画都让中间保持安静，因为折线从那里穿过。两张展开图尺寸相同，所以放进同一个文档，每页一张。每幅画都是对应环衬在`cover.sheets`里的设计，横跨两页。

## 完整食谱

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

- 食谱文件夹: https://github.com/drnachio/postext/tree/main/cookbook/hardcover-jacket-and-endpapers

### script.js

```js
// ═══ Postext Cookbook · Nº 197 · A hardcover's case, dust jacket and endpapers ═══
// https://postext.dev/en/cookbook/hardcover-jacket-and-endpapers
// Code: MIT · Text: Bécquer, tr. C. F. & K. L. Bates (public domain) · Art: diffusion models
// Fonts: Crimson Pro, Cormorant Garamond, Josefin Sans (SIL OFL 1.1) · Needs postext ≥ 1.93.0
//
// The pages of Nº 196 bound two ways: the paperback with flaps, and a cloth hardcover in a
// dust jacket with painted endpapers. Each version has its binding and its ISBN; buildCover
// makes each sheet of the hardcover from the same laid-out pages.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, inlineSvgFonts,
} 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 = 'hardcover-jacket-and-endpapers';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The last four colours are the covers': the jacket's night, gold and bone, the case's cloth.
const palette = { ink: '#25221e', accent: '#86472a', muted: '#6b645a', paper: '#fbf7ee',
  night: '#16242a', gold: '#c99b4e', bone: '#eee5d1', cloth: '#22362f' };
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' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];

// #region answer: two versions over the same pages, each with its binding and its ISBN
// The paperback is Nº 196's, on the printer's own profile. The hardcover takes the built-in
// flat-spine case; `flaps` on a case means a dust jacket, and `caseMaterial: 'cloth'` a case
// covered in cloth and stamped, under the jacket. Spines, boards and turn-ins come from the
// laid-out pages on the paper of `folio.paper`.
const production = {
  bindings: [{ id: 'pur-flaps', name: 'PUR perfect binding, 60 mm flaps', style: 'perfect',
    signature: 16, measures: { flapWidth: 60, bleed: 3, spineAllowance: 0.5 } }],
  versions: [
    { id: 'paperback', name: t({ en: 'Paperback', es: 'Rústica' }), binding: 'pur-flaps',
      flaps: true, isbn: '978-84-0000-196-4', isbnAddOn: '90000' },
    { id: 'hardcover', name: t({ en: 'Hardcover', es: 'Cartoné' }), binding: 'case-flat',
      flaps: true, caseMaterial: 'cloth', isbn: '978-84-0000-197-1', isbnAddOn: '90000' },
  ],
};
// 100 g/m² bulky cream wove at a bulk of 2.4: each leaf is 100 × 2.4 = 240 µm thick.
const folio = { paper: { type: 'bookWove', grammage: 100, bulk: 2.4, shade: '#f7f1e3' } };
// The book's cover design (the paperback's, the jacket's): a night ground and the painting
// on the front panel, into the bleed, whatever the panel's width. `sheets` gives the
// hardcover's other sheets a design of their own: the case its cloth, each endpaper its
// painting across both leaves.
const cover = { background: col('night'), verticalAlign: { back: 'middle' },
  image: { resourceId: 'moncayo', area: 'front', focus: { x: 0.5, y: 0.4 } },
  sheets: {
    case: { background: col('cloth') },
    endpaperFront: { image: { resourceId: 'soria' } },
    endpaperBack: { image: { resourceId: 'fuente' } },
  } };
// #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: 600, textTransform: 'uppercase',
  letterSpacing: pt(tracking) });
const coverStyles = [
  style('cover-title', 'Cormorant Garamond', 40, 40, col('bone'), { fontWeight: 600,
    textAlign: 'center', marginTop: mm(12) }),
  style('cover-subtitle', 'Cormorant Garamond', 15, 19, col('bone'), { italic: true,
    textAlign: 'center' }),
  style('cover-author', 'Josefin Sans', 8.5, 11, col('gold'), { ...caps(1.8),
    textAlign: 'center', marginTop: pt(16) }),
  style('cover-spine', 'Josefin Sans', 7.5, 9, col('bone'), { ...caps(1.2), textAlign: 'center' }),
  style('cover-blurb', 'Crimson Pro', 10.5, 14.5, col('bone'), { marginBottom: pt(7) }),
  style('cover-note', 'Crimson Pro', 10.5, 14.5, col('gold'), { italic: true }),
  style('flap-head', 'Josefin Sans', 7.5, 10, col('gold'), caps(1.4)),
  style('flap-text', 'Crimson Pro', 9.6, 13.2, col('bone'), { marginTop: pt(5) }),
];
// The case's frames (`sheet="case"` in the cover text) set the jacket's lines in gold, the
// colour the cloth is stamped in.
const stamped = coverStyles.filter((s) => /title|subtitle|author|spine/.test(s.id))
  .map((s) => ({ ...s, id: s.id.replace('cover-', 'case-'), color: col('gold'),
    italicColor: col('gold') }));
// #endregion

// #region pages: the book block, a small literary paperback
const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [120, 190, 20, 22, 18, 15.5, 15.2]; // 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, extra) => ({ fontFamily, fontSize: pt(size), color,
  ...extra });
const label = (size, color = col('muted')) => face('Josefin Sans', size, color, caps(size / 5));
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(10) }) });
const folioAt = (y, pages) => ({ elements: [text('f', '{pageNumber}',
  { ...face('Crimson Pro', 9, col('ink')), pages }, at('page', 'bottom', 0, y))] });
const serif = (size, extra) => face('Cormorant Garamond', size, col('ink'), extra);
const headingStyles = [
  { ...none, id: 'half-title', advancedDesign: design(60, [
    text('t', '{title}', serif(17, { fontWeight: 500 }), at('page', 'top', 0, 62))]) },
  { ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
    text('t', '{title}', serif(27, { fontWeight: 600 }), at('page', 'top', 0, 46)),
    text('s', '{subtitle}', serif(13, { italic: true }), at('page', 'top', 0, 58)),
    rule('r', 67),
    text('a', '{author}', label(8, col('accent')), at('page', 'top', 0, 72)),
    text('tr', '{attr.translators}', face('Crimson Pro', 9.5, col('muted'), { italic: true }),
      at('page', 'top', 0, 118, { width: mm(70) })),
    text('i', '{attr.imprint}', label(7), at('page', 'bottom', 0, -26)),
  ]) },
  // The rights at the foot of the verso, under a short rule.
  { ...none, ...page('even'), id: 'rights',
    advancedDesign: design(92, [rule('r', 86, 'container')]) },
  { ...none, ...page('odd'), id: 'contents', advancedDesign: design(34, [
    text('t', '{titleText}', label(8, col('accent')), at('container', 'top', 0, 14)),
    rule('r', 21, 'container')]) },
  // Each legend has a title leaf of its own (the contents point to it), then opens on the
  // next recto, sunk 40 mm.
  { ...none, ...page('odd'), id: 'tale-title', toc: true, advancedDesign: design(90, [
    text('k', '{attr.kicker}', serif(15, { fontWeight: 600, color: col('accent') }),
      at('page', 'top', 0, 58)),
    text('t', '{titleText}', serif(23, { fontWeight: 500 }), at('page', 'top', 0, 67)),
    text('p', '{attr.place}', face('Crimson Pro', 10.5, col('muted'), { italic: true }),
      at('page', 'top', 0, 79)),
    rule('r', 88)]) },
  { ...page('odd'), id: 'tale', toc: false, advancedDesign: design(40, [
    text('t', '{titleText}', serif(15, { fontWeight: 500, italic: true }),
      at('container', 'top', 0, 16)),
    rule('r', 25, 'container')]) },
  { ...none, ...page('any'), id: 'colophon', advancedDesign: design(70, [
    rule('r', 60, '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: 'Crimson Pro', 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, hyphenation: { enabled: true },
    optimalLineBreaking: true, avoidWidows: true, avoidOrphans: true },
  headings: { fontFamily: 'Cormorant Garamond', color: col('ink'), textAlign: 'center', levels: [
    { level: 2, fontSize: pt(12.5), lineHeight: pt(LEAD), fontWeight: 600, color: col('accent'),
      marginTop: pt(LEAD), marginBottom: pt(LEAD / 2) }] },
  headingStyles,
  paragraphStyles: [
    style('rights', 'Crimson Pro', 8, 11, col('muted'), { marginBottom: pt(5) }),
    style('colophon', 'Crimson Pro', 9.5, 13, col('muted'), { italic: true, textAlign: 'center' }),
    ...coverStyles, ...stamped,
  ],
  toc: { levels: [{ level: 1, fontFamily: 'Crimson Pro', fontSize: pt(11), color: col('ink'),
    marginBottom: pt(LEAD / 2) }], pageNumber: { fontFamily: 'Crimson Pro', fontSize: pt(11),
    color: col('ink'), width: mm(8) }, leader: { char: ' ', gap: mm(2) } },
  header: { elements: [head('v', '{author}', 'even'), head('r', '{chapterTitle}', 'odd')] },
  footer: folioAt(-12, 'body'),
  production, cover, folio,
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The book runs on through three files (each within the Cookbook's 2,500 words), cut
// between paragraphs. The cover's text is a fifth: a frame per panel.
const markdown = String.raw`---
title: "The Spirits’ Mountain"
subtitle: "and The Emerald Eyes"
author: "Gustavo Adolfo Bécquer"
---

# The Spirits’ Mountain {style="half-title"}

# The Spirits’ Mountain {style="title-page" translators="Translated from the Spanish by Cornelia Frances Bates and Katharine Lee Bates" imprint="Moncayo Press · Soria"}

# Rights {style="rights"}

:::paragraphs{style="rights"}
The two legends appeared in the Madrid newspaper *El Contemporáneo* in 1861 and were gathered in Bécquer’s *Obras* in 1871. The translation by Cornelia Frances Bates and Katharine Lee Bates was published in *Romantic Legends of Spain* (New York, 1909) and is in the public domain; the text follows Project Gutenberg eBook 50044.

Paperback with flaps · ISBN 978-84-0000-196-4. Hardcover in cloth, with dust jacket · ISBN 978-84-0000-197-1. Sample numbers, assigned to no book.

Jacket and endpaper paintings generated with diffusion models.

Set in Crimson Pro, Cormorant Garamond and Josefin Sans (SIL OFL) on 100 g/m² cream bulky book wove, bulk 2.4.
:::

# Contents {style="contents"}

:::toc

# The Spirits’ Mountain {style="tale-title" kicker="I" place="A Legend of Soria"}

# The Spirits’ Mountain {style="tale"}

On All Souls’ Night I was awakened, I knew not at what hour, by the tolling of bells; their monotonous, unceasing sound brought to mind this tradition which I heard a short time ago in Soria.

I tried to sleep again. Impossible! The imagination, once roused, is a horse that runs wild and cannot be reined in. To pass the time, I decided to write the story out, and so in fact I did.

I had heard it in the very place where it originated and, as I wrote, I sometimes glanced behind me with sudden fear, when, smitten by the cold night air, the glass of my balcony crackled.

Make of it what you will—here it goes loose, like the mounted horseman in a Spanish pack of cards.

## I

“Leash the dogs! Blow the horns to call the hunters together, and let us return to the city. Night is at hand—the Night of All Souls, and we are on the Spirits’ Mountain.”

“So soon!”

“Were it any day but this, I would not give up till I had made an end of that pack of wolves which the snows of the Moncayo have driven from their dens; but to-day it is impossible. Very soon the Angelus will sound in the monastery of the Knights Templars, and the souls of the dead will commence to toll their bell in the chapel on the mountain.”

“In that ruined chapel! Bah! Would you frighten me?”

“No, fair cousin; but you are not aware of all that happens hereabout, for it is not yet a year since you came hither from a distant part of Spain. Rein in your mare; I will keep mine at the same pace and tell you this story on the way.”

The pages gathered together in merry, boisterous groups; the Counts of Bórges and Alcudiel mounted their noble steeds, and the whole company followed after the son and daughter of those great houses, Alonso and Beatriz, who rode at some little distance in advance of the company.

As they went, Alonso related in these words the promised tradition:

“This mountain, which is now called the Spirits’ Mountain, belonged to the Knights Templars, whose monastery you see yonder on the river bank. The Templars were both monks and warriors. After Soria had been wrested from the Moors, the King summoned the Templars here from foreign lands to defend the city on the side next to the bridge, thus giving deep offense to his Castilian nobles, who, as they had won Soria alone, would alone have been able to defend it.

“Between the knights of the new and powerful Order and the nobles of the city there fermented for some years an animosity which finally developed into a deadly hatred. The Templars claimed for their own this mountain, where they reserved an abundance of game to satisfy their needs and contribute to their pleasures; the nobles determined to organize a great hunt within the bounds notwithstanding the rigorous prohibitions of the *clergy with spurs*, as their enemies called them.

“The news of the projected invasion spread fast, and nothing availed to check the rage for the hunt on the one side, and the determination to break it up on the other. The proposed expedition came off. The wild beasts did not remember it; but it was never to be forgotten by the many mothers mourning for their sons. That was not a hunting-trip, but a frightful battle; the mountain was strewn with corpses, and the wolves, whose extermination was the end in view, had a bloody feast. Finally the authority of the King was brought to bear; the mountain, the accursed cause of so many bereavements, was declared abandoned, and the chapel of the Templars, situated on this same wild steep, friends and enemies buried together in its cloister, began to fall into ruins.

“They say that ever since, on All Souls’ Night, the chapel bell is heard tolling all alone, and the spirits of the dead, wrapt in the tatters of their shrouds, run as in a fantastic chase through the bushes and brambles. The deer trumpet in terror, wolves howl, snakes hiss horribly, and on the following morning there have been seen clearly marked in the snow the prints of the fleshless feet of the skeletons. This is why we call it in Soria the Spirits’ Mountain, and this is why I wished to leave it before nightfall.”

Alonso’s story was finished just as the two young people arrived at the end of the bridge which admits to the city from that side. There they waited for the rest of the company to join them, and then the whole cavalcade was lost to sight in the dim and narrow streets of Soria.

## II

The servants had just cleared the tables; the high Gothic fireplace of the palace of the Counts of Alcudiel was shedding a vivid glow over the groups of lords and ladies who were chatting in friendly fashion, gathered about the blaze; and the wind shook the leaded glass of the ogive windows.

Two persons only seemed to hold aloof from the general conversation—Beatriz and Alonso. Beatriz, absorbed in a vague revery, followed with her eyes the capricious dance of the flames. Alonso watched the reflection of the fire sparkling in the blue eyes of Beatriz.

Both maintained for some time an unbroken silence.

The duennas were telling gruesome stories, appropriate to the Night of All Souls—stories in which ghosts and spectres played the principal rôles, and the church bells of Soria were tolling in the distance with a monotonous and mournful sound.

“Fair cousin,” finally exclaimed Alonso, breaking the long silence between them. “Soon we are to separate, perhaps forever. I know you do not like the arid plains of Castile, its rough, soldier customs, its simple, patriarchal ways. At various times I have heard you sigh, perhaps for some lover in your far-away demesne.”

Beatriz made a gesture of cold indifference; the whole character of the woman was revealed in that disdainful contraction of her delicate lips.

“Or perhaps for the grandeur and gaiety of the French capital, where you have lived hitherto,” the young man hastened to add. “In one way or another, I foresee that I shall lose you before long. When we part, I would like to have you carry hence a remembrance of me. Do you recollect the time when we went to church to give thanks to God for having granted you that restoration to health which was your object in coming to this region? The jewel that fastened the plume of my cap attracted your attention. How well it would look clasping a veil over your dark hair! It has already been the adornment of a bride. My father gave it to my mother, and she wore it to the altar. Would you like it?”

“I do not know how it may be in your part of the country,” replied the beauty, “but in mine to accept a gift is to incur an obligation. Only on a holy day may one receive a present

from a kinsman—though he may go to Rome without returning empty-handed.”

The frigid tone in which Beatriz spoke these words troubled the youth for a moment, but, clearing his brow, he replied sadly:

“I know it, cousin, but to-day is the festival of All Saints, and yours among them—a holiday on which gifts are fitting. Will you accept mine?”

Beatriz slightly bit her lip and put out her hand for the jewel, without a word.

The two again fell silent and again heard the quavering voices of the old women telling of witches and hobgoblins, the whistling wind which shook the ogive windows, and the mournful, monotonous tolling of the bells.

After the lapse of some little time, the interrupted dialogue was thus renewed:

“And before All Saints’ Day ends, which is holy to my saint as well as to yours, so that you can, without compromising yourself, give me a keepsake, will you not do so?” pleaded Alonso, fixing his eyes on his cousin’s, which flashed like lightning, gleaming with a diabolical thought.

“Why not?” she exclaimed, raising her hand to her right shoulder as though seeking for something amid the folds of her wide velvet sleeve embroidered with gold. Then, with an innocent air of disappointment, she added:

“Do you recollect the blue scarf I wore to-day to the hunt—the scarf which you said, because of something about the meaning of its color, was the emblem of your soul?”

“Yes.”

“Well! it is lost! it is lost, and I was thinking of letting you have it for a souvenir.”

“Lost! where?” asked Alonso, rising from his seat with an indescribable expression of mingled fear and hope.

“I do not know—perhaps on the mountain.”

“On the Spirits’ Mountain!” he murmured, paling and sinking back into his seat. “On the Spirits’ Mountain!”

Then he went on in a voice choked and broken:

“You know, for you have heard it a thousand times, that I am called in the city, in all Castile, the king of the hunters. Not having yet had a chance to try, like my ancestors, my strength in battle, I have brought to bear on this pastime, the image of war, all the energy of my youth, all the hereditary ardor of my race. The rugs your feet tread on are the spoils of the chase, the hides of the wild beasts I have killed with my own hand. I know their haunts and their habits; I have fought them by day and by night, on foot and on horseback, alone and with hunting-parties, and there is not a man will say that he has ever seen me shrink from danger. On any other night I would fly for that scarf—fly as joyously as to a festival; but to-night, this one night—why disguise it?—I am afraid. Do you hear? The bells are tolling, the Angelus has sounded in San Juan del Duero, the ghosts of the mountain are now beginning to lift their yellowing skulls from amid the brambles that cover their graves—the ghosts! the mere sight of them is enough to curdle with horror the blood of the bravest, turn his hair white, or sweep him away in the stormy whirl of their fantastic chase as a leaf, unwitting whither, is carried by the wind.”

While the young man was speaking, an almost imperceptible smile curled the lips of Beatriz, who, when he had ceased, exclaimed in an indifferent tone, while she was stirring the fire on the hearth, where the wood blazed and snapped, throwing off sparks of a thousand colors:

“Oh, by no means! What folly! To go to the mountain at this hour for such a trifle! On so dark a night, too, with ghosts abroad, and the road beset by wolves!”

As she spoke this closing phrase, she emphasized it with so peculiar an intonation that Alonso could not fail to understand all her bitter irony. As moved by a spring, he leapt to his feet, passed his hand over his brow as if to dispel the fear which was in his brain, not in his breast, and with firm voice he said, addressing his beautiful cousin, who was still leaning over the hearth, amusing herself by stirring the fire:

“Farewell, Beatriz, farewell. If I return, it will be soon.”

“Alonso, Alonso!” she called, turning quickly, but now that she wished—or made show of wishing—to detain him, the youth had gone.

In a few moments she heard the beat of a horse’s hoofs departing at a gallop. The beauty, with a radiant expression of satisfied pride flushing her cheeks, listened attentively to the sound which grew fainter and fainter until it died away.

The old dames, meanwhile, were continuing their tales of ghostly apparitions; the wind was shrilling against the balcony glass, and far away the bells of the city tolled on.

## III

An hour had passed, two, three; midnight would soon be striking, and Beatriz withdrew to her chamber. Alonso had not returned; he had not returned, though less than an hour would have sufficed for his errand.

“He must have been afraid!” exclaimed the girl, closing her prayer-book and turning toward her bed after a vain attempt to murmur some of the prayers that the church offers for the dead on the Day of All Souls.

After putting out her light and drawing the double silken curtains, she fell asleep; but her sleep was restless, light, uneasy.

The Postigo clock struck midnight. Beatriz heard through her dreams the slow, dull, melancholy strokes, and half opened her eyes. She thought she had heard, at the same time, her name spoken, but far, far away, and in a faint, suffering voice. The wind groaned outside her window.

“It must have been the wind,” she said, and pressing her hand above her heart, she strove to calm herself. But her heart beat ever more wildly. The larchwood doors of the chamber grated on their hinges with a sharp creak, prolonged and strident.
`;
const part2 = String.raw`First these doors, then the more distant ones—all the doors which led to her room opened, one after another, some with a heavy, groaning sound, some with a long wail that set the nerves on edge. Then silence, a silence full of strange noises, the silence of midnight, with a monotonous murmur of far-off water, the distant barking of dogs, confused voices, unintelligible words, echoes of footsteps going and coming, the rustle of trailing garments, half-suppressed sighs, labored breathing almost felt upon the face, involuntary shudders that announce the presence of something not seen, though its approach is felt in the darkness.

Beatriz, stiffening with fear, yet trembling, thrust her head out from the bed-curtains and listened a moment. She heard a thousand diverse noises; she passed her hand across her brow and listened again; nothing, silence.

She saw, with that dilation of the pupils common in nervous crises, dim shapes moving hither and thither all about the room, but when she fixed her gaze on any one point, there was nothing but darkness and impenetrable shadows.

“Bah!” she exclaimed, again resting her beautiful head upon her blue satin pillow, “am I as timid as these poor kinsfolk of mine, whose hearts thump with terror under their armor when they hear a ghost-story?”

And closing her eyes she tried to sleep—but her effort to compose herself was in vain. Soon she started up again, paler, more uneasy, more terrified. This time it was no illusion; the brocade hangings of the door had rustled as they were pushed to either side, and slow footsteps were heard upon the carpet; the sound of those footsteps was muffled, almost imperceptible, but continuous, and she heard, keeping measure with them, a creaking as of dry wood or bones. And the footfalls came nearer, nearer; the prayer-stool by the side of her bed moved. Beatriz uttered a sharp cry, and burying herself under the bedclothes, hid her head and held her breath.

The wind beat against the balcony glass; the water of the far-off fountain was falling, falling, with a monotonous, unceasing sound; the barking of the dogs was borne upon the gusts, and the church bells in the city of Soria, some near, some remote, tolled sadly for the souls of the dead.

So passed an hour, two, the night, a century, for that night seemed to Beatrix eternal. At last the day began to break; putting fear from her, she half opened her eyes to the first silver rays. How beautiful, after a night of wakefulness and terrors, is the clear white light of dawn! She parted the silken curtains of her bed and was ready to laugh at her past alarms, when suddenly a cold sweat covered her body, her eyes seemed starting from their sockets, and a deadly pallor overspread her cheeks; for on her prayer-stool she had seen, torn and blood-stained, the blue scarf she lost on the mountain, the blue scarf Alonso went to seek.

When her attendants rushed in, aghast, to tell her of the death of the heir of Alcudiel, whose body, partly devoured by wolves, had been found that morning among the brambles on the Spirits’ Mountain, they discovered her motionless, convulsed, clinging with both hands to one of the ebony bedposts, her eyes staring, her mouth open, the lips white, her limbs rigid—dead, dead of fright!

## IV

They say that, some time after this event, a hunter who, having lost his way, had been obliged to pass the Night of the Dead on the Spirits’ Mountain, and who in the morning, before he died, was able to relate what he had seen, told a tale of horror. Among other awful sights, he avowed he beheld the skeletons of the ancient Knights Templars and of the nobles of Soria, buried in the cloister of the chapel, rise at the hour of the Angelus with a horrible rattle and, mounted on their bony steeds, chase, as a wild beast, a beautiful woman, pallid, with streaming hair, who, uttering cries of terror and anguish, had been wandering, with bare and bloody feet, about the tomb of Alonso.

# The Emerald Eyes {style="tale-title" kicker="II" place="A Legend of the Moncayo"}

# The Emerald Eyes {style="tale"}

For a long time I have desired to write something with this title. Now that the opportunity has come, I have inscribed it in capital letters at the top of the page and have let my pen run at will.

I believe that I have seen eyes like those I have painted in this legend. It may have been in my dreams, but I have seen them. Too true it is that I shall not be able to describe them as they were, luminous, transparent as drops of rain slipping over the leaves of the trees after a summer shower. At all events, I count upon the imagination of my readers to understand me in what we might call a sketch for a picture which I will paint some day.

## I

“The stag is wounded—he is wounded; no doubt of it. There are traces of his blood on the mountain shrubs, and in trying to leap one of those mastic trees his legs failed him. Our young lord begins where others end. In my forty years as huntsman I have not seen a better shot. But by Saint Saturio, patron of Soria, cut him off at these hollies, urge on the dogs, blow the horns till your lungs are empty, and bury your spurs in the flanks of the horses. Do you not see that he is going toward the fountain of the Poplars, and if he lives to reach it we must give him up for lost?”

The glens of the Moncayo flung from echo to echo the braying of the horns and barking of the unleashed pack of hounds; the shouts of the pages resounded with new vigor, while the confused throng of men, dogs and horses rushed toward the point which Iñigo, the head huntsman of the Marquises of Almenar, indicated as the one most favorable for intercepting the quarry.

But all was of no avail. When the fleetest of the greyhounds reached the hollies, panting, its jaws covered with foam, already the deer, swift as an arrow, had cleared them at a single bound, disappearing among the thickets of a narrow path which led to the fountain.

“Draw rein! draw rein, every man!” then cried Iñigo. “It was the will of God that he should escape.”

And the troop halted, the horns fell silent and the hounds, at the call of the hunters, abandoned, snarling, the trail.

At that moment, the lord of the festival, Fernando de Argensola, the heir of Almenar, came up with the company.

“What are you doing?” he exclaimed, addressing his huntsman, astonishment depicted on his features, anger burning in his eyes. “What are you doing, idiot? Do you see that the creature is wounded, that it is the first to fall by my hand, and yet you abandon the pursuit and let it give you the slip to die in the depths of the forest? Do you think perchance that I have come to kill deer for the banquets of wolves?”

“*Señor*,” murmured Iñigo between his teeth, “it is impossible to pass this point.”

“Impossible! And why?”

“Because this path,” continued the huntsman, “leads to the fountain of the Poplars, the fountain of the Poplars in whose waters dwells an evil spirit. He who dares trouble its flow pays dear for his rashness. Already the deer will have reached its borders; how will you take it without drawing on your head some fearful calamity? We hunters are kings of the Moncayo, but kings that pay a tribute. A quarry which takes refuge at this mysterious fountain is a quarry lost.”

“Lost! Sooner will I lose the seigniory of my fathers, sooner will I lose my soul into the hands of Satan than permit this stag to escape me, the only one my spear has wounded, the first fruits of my hunting. Do you see him? Do you see him? He can still at intervals be made out from here. His legs falter, his speed slackens; let me go, let me go! Drop this bridle or I roll you in the dust! Who knows if I will not run him down before he reaches the fountain? And if he should reach it, to the devil with it, its untroubled waters and its inhabitants! On, Lightning! on, my steed! If you overtake him, I will have the diamonds of my coronet set in a headstall all of gold for you.”

Horse and rider departed like a hurricane.

Iñigo followed them with his eyes till they disappeared in the brush. Then he looked about him: all like himself remained motionless, in consternation.

The huntsman exclaimed at last:

“*Señores*, you are my witnesses. I exposed myself to death under his horse’s hoofs to hold him back. I have fulfilled my duty. Against the devil heroism does not avail. To this point comes the huntsman with his crossbow; beyond this, it is for the chaplain with his holy water to attempt to pass.”

## II

“You are pale; you go about sad and gloomy. What afflicts you? From the day, which I shall ever hold in hate, on which you went to the fountain of the Poplars in chase of the wounded deer, I should say an evil sorceress had bewitched you with her enchantments.

“You do not go to the mountains now preceded by the clamorous pack of hounds, nor does the blare of your horns awake the echoes. Alone with these brooding fancies which beset you, every morning you take your crossbow only to plunge into the thickets and remain there until the sun goes down. And when night darkens and you return to the castle, white and weary, in vain I seek in the game-bag the spoils of the chase. What detains you so long far from those who love you most?”

While Iñigo was speaking, Fernando, absorbed in his thoughts, mechanically cut splinters from the ebony bench with his hunting knife.

After a long silence, which was interrupted only by the click of the blade as it slipped over the polished wood, the young man, addressing his servant as if he had not heard a single word, exclaimed:

“Iñigo, you who are an old man, you who know all the haunts of the Moncayo, who have lived on its slopes pursuing wild beasts and in your wandering hunting trips have more than once stood on its summit, tell me, have you ever by chance met a woman who dwells among its rocks?”

“A woman!” exclaimed the huntsman with astonishment, looking closely at him.

“Yes,” said the youth. “It is a strange thing that has happened to me, very strange. I thought I could keep this secret always; but it is no longer possible. It overflows my heart and begins to reveal itself in my face. Therefore I am going to tell it to you. You will help me solve the mystery which enfolds this being who seems to exist only for me, since no one knows her or has seen her, or can give me any account of her.”

The huntsman, without opening his lips, drew forward his stool to place it near the ebony bench of his lord from whom he did not once remove his affrighted eyes. The youth, after arranging his thoughts, continued thus:

“From the day on which, notwithstanding your gloomy predictions, I went to the fountain of the Poplars, and crossing its waters recovered the stag which your superstition would have let escape, my soul has been filled with a desire for solitude.

“You do not know that place. See, the fountain springs from a hidden source in the cavity of a rock, and falls in trickling drops through the green, floating leaves of the plants that grow on the border of its cradle. These drops, which on falling glisten like points of gold and sound like the notes of a musical instrument, unite on the turf and murmuring, murmuring with a sound like that of bees humming about the flowers, glide on through the gravel, and form a rill and contend with the obstacles in their way, and gather volume and leap and flee and run, sometimes with a laugh, sometimes with sighs, until they fall into a lake. Into the lake they fall with an indescribable sound. Laments, words, names, songs, I know not what I have heard in that sound when I have sat, alone and fevered, upon the huge rock at whose feet the waters of that mysterious fountain leap to bury themselves in a deep pool whose still surface is scarcely rippled by the evening wind.

“Everything there is grand. Solitude with its thousand vague murmurs dwells in those places and transports the mind with a profound melancholy. In the silvered leaves of the poplars, in the hollows of the rocks, in the waves of the water it seems that the invisible spirits of nature talk with us, that they recognize a brother in the immortal soul of man.

“When at break of dawn you would see me take my crossbow and go toward the mountain, it was never to lose myself among the thickets in pursuit of game. No, I went to sit on the rim of the fountain, to seek in its waves—I know not what—an absurdity! The day I leaped over it on my Lightning, I believed I saw glittering in its depths a marvel—truly a marvel—the eyes of a woman!

“Perhaps it may have been a fugitive ray of sunshine that wound, serpent like, through the foam; perhaps one of those flowers which float among the weeds of its bosom, flowers whose calyxes seem to be emeralds—I do not know. I thought I saw a gaze which fixed itself on mine, a look which kindled in my breast a desire absurd, impossible of realization, that of meeting a person with eyes like those.

“In my search, I went to that place day after day.
`;
const part3 = String.raw`“At last, one afternoon—I thought myself the plaything of a dream—but no, it is the truth; I have spoken with her many times as I am now speaking with you—one afternoon I found, sitting where I had sat, clothed in a robe which reached to the waters and floated on their surface, a woman beautiful beyond all exaggeration. Her hair was like gold; her eyelashes shone like threads of light, and between the lashes flashed the restless eyes that I had seen—yes; for the eyes of that woman were the eyes which I bore stamped upon my mind, eyes of an impossible color, the color——”

“Green!” exclaimed Iñigo, in accents of profound terror, starting with a bound from his seat.

Fernando, in turn, looked at him as if astonished that Iñigo should supply what he was about to say, and asked him with mingled anxiety and joy:

“Do you know her?”

“Oh, no!” said the huntsman. “God save me from knowing her! But my parents, on forbidding me to go toward those places, told me a thousand times that the spirit, goblin, demon or woman, who dwells in those waters, has eyes of that color. I conjure you by that which you love most on earth not to return to the fountain of the Poplars. One day or another her vengeance will overtake you, and you will expiate in death the crime of having stained her waters.”

“By what I love most!” murmured the young man with a sad smile.

“Yes,” continued the elder. “By your parents, by your kindred, by the tears of her whom heaven destines for your wife, by those of a servant who watched beside your cradle.”

“Do you know what I love most in this world? Do you know for what I would give the love of my father, the kisses of her who gave me life, and all the affection which all the women on earth can hold in store? For one look, for only one look of those eyes! How can I leave off seeking them?”

Fernando said these words in such a tone that the tear which trembled on the eyelids of Iñigo fell silently down his cheek, while he exclaimed with a mournful accent: “The will of Heaven be done!”

## III

“Who art thou? What is thy fatherland? Where dost thou dwell? Day after day I come seeking thee, and see neither the palfrey that brings thee hither, nor the servants who bear thy litter. Rend once for all the veil of mystery in which thou dost enfold thyself as in the heart of night. I love thee and, highborn or lowly, I will be thine, thine forever.”

The sun had crossed the crest of the mountain. The shadows were descending its slope with giant strides. The breeze sighed amid the poplars of the fountain. The mist, rising little by little from the surface of the lake, began to envelop the rocks of its margin.

Upon one of these rocks, on one which seemed ready to topple over into the depths of the waters on whose surface was pictured its wavering image, the heir of Almenar, on his knees at the feet of his mysterious beloved, sought in vain to draw from her the secret of her existence.

She was beautiful, beautiful and pallid as an alabaster statue. One of her tresses fell over her shoulders, entangling itself in the folds of her veil like a ray of sunlight passing through clouds; and her eyes, within the circle of her amber-colored lashes, gleamed like emeralds set in fretted gold.

When the youth ceased speaking, her lips moved as for utterance, but only exhaled a sigh, a sigh soft and sorrowful like that of the gentle wave which a dying breeze drives among the rushes.

“Thou answerest not,” exclaimed Fernando, seeing his hope mocked. “Wouldst thou have me credit what they have told me of thee? Oh, no! Speak to me. I long to know if thou lovest me; I long to know if I may love thee, if thou art a woman——”

—“Or a demon. And if I were?”

The youth hesitated a moment; a cold sweat ran through his limbs; the pupils of his eyes dilated, fixing themselves with more intensity upon those of that woman and, fascinated by their phosphoric brilliance, as though demented he exclaimed in a burst of passion:

“If thou wert, I should love thee. I should love thee as I love thee now, as it is my destiny to love thee even beyond this life, if there be any life beyond.”

“Fernando,” said the beautiful being then, in a voice like music: “I love thee even more than thou lovest me; in that I, who am pure spirit, stoop to a mortal. I am not a woman like those that live on earth. I am a woman worthy of thee who art superior to the rest of humankind. I dwell in the depths of these waters, incorporeal like them, fugitive and transparent; I speak with their murmurs and move with their undulations. I do not punish him who dares disturb the fountain where I live; rather I reward him with my love, as a mortal superior to the superstitions of the common herd, as a lover capable of responding to my strange and mysterious embrace.”

While she was speaking, the youth, absorbed in the contemplation of her fantastic beauty, drawn on as by an unknown force, approached nearer and nearer the edge of the rock. The woman of the emerald eyes continued thus:

“Dost thou behold, behold the limpid depths of this lake, behold these plants with large, green leaves which wave in its bosom? They will give us a couch of emeralds and corals and I—I will give thee a bliss unnamable, that bliss which thou hast dreamed of in thine hours of delirium, and which no other can bestow.—Come! the mists of the lake float over our brows like a pavilion of lawn, the waves call us with their incomprehensible voices, the wind sings among the poplars hymns of love; come—come!”

Night began to cast her shadows, the moon shimmered on the surface of the pool, the mist was driven before the rising breeze, the green eyes glittered in the dusk like the will-o’-the-wisps that run over the surface of impure waters. “Come, come!” these words were murmuring in the ears of Fernando like an incantation—“Come!” and the mysterious woman called him to the brink of the abyss where she was poised, and seemed to offer him a kiss—a kiss——

Fernando took one step toward her—another—and felt arms slender and flexible twining about his neck and a cold sensation on his burning lips, a kiss of snow—wavered, lost his footing and fell, striking the water with a dull and mournful sound.

The waves leaped in sparks of light, and closed over his body, and their silvery circles went widening, widening until they died away on the banks.

# Colophon {style="colophon"}

:::paragraphs{style="colophon"}
This book was set in November 2026, on the eve of All Souls’ Night.
:::
`;
const coverText = String.raw`:::frame{slot="back"}
:::paragraphs{style="cover-blurb"}
On All Souls’ Night the bell of a ruined Templar chapel rings by itself above Soria, and a young noble rides out to fetch a blue sash his cousin says she lost on the mountain. A hunter follows a woman with green eyes to a spring on the slopes of the Moncayo.
:::

:::paragraphs{style="cover-blurb"}
Bécquer wrote these two legends in his twenties, for the Madrid newspaper *El Contemporáneo*, from stories he heard in the towns where they happen.
:::

:::paragraphs{style="cover-note"}
Translated by Cornelia Frances Bates and Katharine Lee Bates
:::
:::

:::frame{slot="flapFront"}
:::paragraphs{style="flap-head"}
Gustavo Adolfo Bécquer
:::

:::paragraphs{style="flap-text"}
was born in Seville in 1836 and went to Madrid at eighteen to make a living as a writer. He wrote for newspapers, translated plays and worked as a government censor of novels. In 1864 he spent months in the monastery of Veruela, at the foot of the Moncayo, and sent from there the letters *Desde mi celda*. He died in Madrid in 1870, at thirty-four. His *Rimas* and *Leyendas* were collected by his friends and published the following year.
:::
:::

:::frame{slot="flapBack"}
:::paragraphs{style="flap-head"}
The translators
:::

:::paragraphs{style="flap-text"}
Cornelia Frances Bates (1826–1908) began to study Spanish at seventy-one and read Bécquer in two small green volumes with a red dictionary beside them. Her daughter Katharine Lee Bates (1859–1929), professor of English at Wellesley College, finished the translation they had planned together and published it in New York in 1909 as *Romantic Legends of Spain*.
:::
:::

:::frame{slot="front" sheet="case"}
:::paragraphs{style="case-title"}
The Spirits’ Mountain
:::

:::paragraphs{style="case-subtitle"}
and The Emerald Eyes
:::

:::paragraphs{style="case-author"}
Gustavo Adolfo Bécquer
:::
:::

:::frame{slot="spine" sheet="case"}
:::paragraphs{style="case-spine"}
The Spirits’ Mountain · Gustavo Adolfo Bécquer
:::
:::

:::frame{slot="back" sheet="case"}
:::
`;
const picture = (id, w, h, alt) => ({ id, typeId: 'figure', kind: 'bitmap', createdAt: 0,
  updatedAt: 0, bitmap: { fileId: `${id}.jpg`, format: 'jpeg', width: w, height: h },
  altText: t(alt) });
const resources = [
  picture('moncayo', 1100, 1771, { en: 'A ruined chapel with a lit window '
    + 'on a rocky hill at night, a snowy ridge behind it and a rider in a red cloak below.',
  es: 'Una capilla en ruinas con una ventana encendida en un cerro de noche, una sierra '
    + 'nevada detrás y un jinete de capa roja en el camino.' }),
  picture('soria', 1300, 1036, { en: 'Soria on its slope above the Duero at '
    + 'dusk, the stone bridge on the left, a hill with a ruined chapel on the right.',
  es: 'Soria en su ladera sobre el Duero al anochecer, el puente de piedra a la izquierda y un '
    + 'cerro con una capilla en ruinas a la derecha.' }),
  picture('fuente', 1300, 1036, { en: 'A still green pool among rocks and '
    + 'poplars under the moon, a waterfall on the left and a snowy summit behind.',
  es: 'Una poza verde y quieta entre rocas y álamos bajo la luna, una cascada a la izquierda y '
    + 'una cumbre nevada al fondo.' }),
];
await loadImage('moncayo.jpg', asset('moncayo-1100.jpg'));
await loadImage('soria.jpg', asset('soria-1300.jpg'));
await loadImage('fuente.jpg', asset('fuente-1300.jpg'));

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { 'Crimson Pro': ['400', '400i', '600'], 'Cormorant Garamond': ['500', '600', '600i'],
  'Josefin Sans': ['600'] };

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const book = await buildDocumentWithFonts({ markdown: [markdown, part2, part3]
  .join('\n\n'), resources }, config, kitFonts(FONTS));

// #region sheets: the hardcover's four sheets, built from the pages just laid out
// One call per sheet, with the same config and the same cover text: each sheet takes its
// design from `cover.sheets` (the jacket, the book's) and the frames meant for it. The
// barcode goes on the jacket alone, the sheet a till scans.
const built = {};
for (const sheet of ['cover', 'jacket', 'endpaperFront', 'endpaperBack']) {
  const made = buildCover({ config, sheet, pages: book.pages, version: 'hardcover',
    markdown: coverText, metadata: book.metadata, resources });
  if (!('config' in made)) throw new Error(made.issues.map((i) => i.kind).join(', '));
  // The barcode's digits name OCR-B, which no font server has: set in the label face.
  for (const [id, bytes] of Object.entries(made.files)) {
    await loadSvg(id, new TextDecoder().decode(bytes)
      .replace(/font-family="[^"]*"/g, 'font-family="Josefin Sans"'));
  }
  built[sheet] = made;
}
const sheetDoc = (b) => buildDocumentWithFonts(b.content, b.config, kitFonts(FONTS));
const caseDoc = await sheetDoc(built.cover);
const jacketDoc = await sheetDoc(built.jacket);
// #endregion

// #region endpapers: the two endpapers in one document
// Both endpapers are the size of two pages: one document holds them, a page each, the
// back's template renamed so the two templates do not share an id.
const [ef, eb] = [built.endpaperFront, built.endpaperBack];
const back = { ...eb.config.pageTemplates.at(-1), id: 'endpaper-back' };
const endpapers = await buildDocumentWithFonts({ ...ef.content, markdown: `${ef.content.markdown}`
  + `\n\n${eb.content.markdown.replace('postext-cover', back.id)}` },
{ ...ef.config, pageTemplates: [...ef.config.pageTemplates, back] }, kitFonts(FONTS));
// #endregion

showPages(book, { title: t({ en: 'The Spirits’ Mountain · hardcover in a dust jacket',
  es: 'El monte de las ánimas · cartoné con sobrecubierta' }) });
// The sheets above the pages, each with the measures buildCover worked out.
const show = (doc, page, b, name) => {
  const canvas = document.createElement('canvas');
  canvas.style.cssText = 'display: block; width: min(1200px, 94vw); margin: 32px auto 8px';
  const { width, height } = b.sheet;
  const caption = `${name} · ${width.toFixed(1)} × ${height.toFixed(1)} mm`;
  document.getElementById('pages').before(canvas, caption);
  renderPageToCanvas(doc.pages[page], doc, canvas, { scale: 2400 / doc.pages[page].width });
};
show(caseDoc, 0, built.cover, t({ en: `Cloth case · ${book.pages.length} pp., spine `
  + `${built.cover.sheet.spine.toFixed(1)} mm`, es: `Tapa de tela · ${book.pages.length} pp., `
  + `lomo de ${built.cover.sheet.spine.toFixed(1)} mm` }));
show(jacketDoc, 0, built.jacket, t({ en: 'Dust jacket', es: 'Sobrecubierta' }));
show(endpapers, 0, ef, t({ en: 'Front endpaper', es: 'Guarda delantera' }));
show(endpapers, 1, eb, t({ en: 'Back endpaper', es: 'Guarda trasera' }));

// One file for the binder: the pages, then each sheet at its own size.
offerPdf(() => renderToPdf([book, caseDoc, jacketDoc, endpapers], {
  fontProvider: fontsourceProvider, resourceBytes: imageBytes }), `${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 ───────────────────────────────────────────────────────────────────────
```

## 变化

### 印刷书壳，不用布面

把`case`从`cover.sheets`里删掉，书壳就用书本身的设计：夜色底子，画在封面纸板上。书壳自己的文本框照样把书名印成金色。

```diff
   sheets: {
-    case: { background: col('cloth') },
     endpaperFront: { image: { resourceId: 'soria' } },
```

### 做成圆背

书再厚一些，`case-round`会给书壳的书脊加3毫米，护封的书脊也跟着变宽。

```diff
-    { id: 'hardcover', name: t({ en: 'Hardcover', es: 'Cartoné' }), binding: 'case-flat',
+    { id: 'hardcover', name: t({ en: 'Hardcover', es: 'Cartoné' }), binding: 'case-round',
```

## 常见问题

- 在截取的页面列表里，展开图排在书页后面：书壳是第38页，护封第39页，环衬第40和41页。书多一页，这些编号都会跟着变。
- 在精装书上，`sheet="cover"`既指书壳，也指平装书的封面；`sheet="case"`只指书壳。某张展开图自己的文本框只在这张图上替换同一区域的通用文本框，空的文本框就让这块区域留白。

## 致谢

- 食谱: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- 文字: The Spirits’ Mountain and The Emerald Eyes, translated by Cornelia Frances Bates and Katharine Lee Bates, from Romantic Legends of Spain (1909), Project Gutenberg eBook #50044: Gustavo Adolfo Bécquer ([来源](https://www.gutenberg.org/ebooks/50044)), 公有领域
- 文字: El monte de las ánimas and Los ojos verdes, from the Obras (Madrid, Fernando Fe, 1885) as transcribed on Wikisource, accents modernised: Gustavo Adolfo Bécquer ([来源](https://es.wikisource.org/wiki/El_monte_de_las_%C3%A1nimas)), 公有领域
- 图片: The dust jacket: a ruined chapel under the Moncayo on All Souls’ Night, in oils: Generated With Diffusion Models, 原创
- 图片: The front endpaper: Soria above the Duero at dusk, with the Mountain of the Spirits: Generated With Diffusion Models, 原创
- 图片: The back endpaper: a spring among poplars on the slopes of the Moncayo by moonlight: Generated With Diffusion Models, 原创
- 字体: Crimson Pro (OFL-1.1), Cormorant Garamond (OFL-1.1), Josefin Sans (OFL-1.1)
- 代码: MIT · 示例内容: CC-BY-4.0

## 相关食谱

- [No. 200 · 锚定并串接的封面文本框](https://postext.dev/zh/cookbook/cover-text-boxes-anchored.md): 两篇爱伦·坡小说的平装本，封面由六个彼此挂靠的文本框排成：书名变长时框随之长高，封底简介接着排进第二个框。 · 难度 3 (高级) · 小说、戏剧与文学散文
- [No. 194 · 开窗封面，框住下面的书名页](https://postext.dev/zh/cookbook/die-cut-window-cover.md): 用dieCuts在封面上模切一个椭圆窗，按书名页上的画来量，让切口正落在金色画框上，模切线放在单独的色版上。 · 难度 2 (中级) · 小说、戏剧与文学散文
- [No. 115 · 一本书，两个EPUB 3文件：固定版式与流式版式](https://postext.dev/zh/cookbook/epub-fixed-and-reflowable.md): postext-epub的renderToEpub把buildBundle排好的各章写成一个固定版式EPUB和一个流式EPUB；readEpub列出每个文件里有什么。 · 难度 3 (高级) · 小说、戏剧与文学散文
