简单来说
一本收录爱伦·坡两篇小说的小书,以及它的封面印张。封面上每段文字都放在另一段的下方、上方或旁边,所以书名变长会把下面的文字推下去,封底的简介在一句引文下面接着排。
成品一览
爱伦·坡的两篇小说《红死病的假面舞会》和《椭圆形画像》(英文版用原文,西班牙文版用卡洛斯·奥利韦拉1884年的译本),排成125 × 195毫米的平装本,外加它的封面印张。封面上没有一段文字写了坐标,每段都是挂在别处的文本框。封面上,书名挂在区域顶部,副书名挂在书名下面,作者名立在底部。两个版本的书名都要排两行,所以书名框长高,副书名也跟着往下移。封底上,简介填满一个50毫米高的框,放不下的行接着排进第二个框,位于一句小说引文的下面。页面上方,示例把印张画了两遍:一遍是印出来的样子,一遍给每个框画上轮廓并标出串接关系。
这道食谱解答
- 怎样让封面上的各段文字彼此相对定位,书名变长时把下面的文字推下去,简介接着排进第二个文本框?
简短回答
// A box anchored to a zone stands on that point of the zone's safe area; a box anchored to
// another box hangs below it, above it or beside it. With an anchor, `rect` gives only the
// size. The title may grow to 40 mm before its type shrinks, and the blurb sends the lines
// it cannot hold to the box under the quotation.
const size = (width, height) => ({ x: 0, y: 0, width, height });
const textBoxes = [
// Front: the title from the top of the panel, the subtitle hung under it, the author
// standing on the foot. Only the title's box grows; the subtitle follows it down.
{ name: 'title', rect: size(100, 14), anchor: { to: 'front', edge: 'top', y: 8 },
maxHeight: 40 },
{ name: 'subtitle', rect: size(100, 9), anchor: { to: 'title', edge: 'below', y: 2 } },
{ name: 'author', rect: size(100, 8), anchor: { to: 'front', edge: 'bottom', y: -6 } },
// Back: the blurb, a quotation under it, and the rest of the blurb under the quotation.
// What the blurb's 50 mm cannot hold goes on in `blurb-end`, cut between lines.
{ name: 'blurb', rect: size(94, 50), anchor: { to: 'back', edge: 'top', y: 6 },
next: 'blurb-end' },
{ name: 'quote', rect: size(94, 24), anchor: { to: 'blurb', edge: 'below', y: 5 },
verticalAlign: 'middle' },
{ name: 'blurb-end', rect: size(94, 46), anchor: { to: 'quote', edge: 'below', y: 5 } },
];
const cover = {
background: col('night'),
elements: [{ id: 'art', kind: 'image', zone: 'front', x: 0, y: -3, width: 128, height: 201,
resourceId: 'masque', fit: 'cover' }],
textBoxes,
};
用料
- 功能
- 封面文本框封面印张串接的文字框印刷版本、ISBN与书脊封面、扉页和版权页标题样式设计过的章首页页面设计中的文字、线条和框文档元数据段落样式书眉与页码作为资源的图和表语义调色板导出PDF在Canvas上绘制页面
- 类型
- EB Garamond, Cinzel(SIL OFL 1.1)
- 素材
masque-1024.jpg- The cover painting: a masked ball in a file of coloured rooms under a Gothic vault, with an ebony clock and a figure in a grave-shroud, in oils (Generated With Diffusion Models, 原创)
做法
#1 · 每个框挂在某个区域或另一个框上
代码就是上面的简短回答。anchor指定印张上的一个区域或另一个文本框,再指定一个点。在区域上,这个点是其安全区的九个点之一,文本框把自己对应的点放到那里:edge: 'top'让书名在封面上居中,顶边对齐安全区的顶边;edge: 'bottom'让作者框的底边落在区域底边上。在文本框上,这个点还可以是below、above、right-of或left-of。x和y以毫米为单位从这个点移动文本框。有了锚点,rect只提供尺寸,所以书脊变厚或开本改变时,各个框仍留在原位。
#2 · 书名长高,副书名随之下移
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 mid = { textAlign: 'center' };
const caps = (tracking) => ({ fontWeight: 600, letterSpacing: pt(tracking) });
const coverStyles = [
style('cover-title', 'Cinzel', 30, 33, col('bone'), { ...mid, fontWeight: 500 }),
style('cover-subtitle', 'EB Garamond', 14, 18, col('gold'), { ...mid, italic: true }),
style('cover-author', 'Cinzel', 10, 13, col('bone'), { ...mid, ...caps(2.2) }),
style('cover-spine', 'Cinzel', 7, 8, col('bone'), { ...mid, ...caps(1.1) }),
style('cover-blurb', 'EB Garamond', 10.5, 14.5, col('bone'), { textAlign: 'justify',
hyphenation: true, firstLineIndent: mm(4) }),
style('cover-blurb-first', 'EB Garamond', 10.5, 14.5, col('bone'), { textAlign: 'justify',
hyphenation: true }),
style('cover-quote', 'EB Garamond', 15, 19, col('gold'), { ...mid, italic: true }),
style('cover-note', 'Cinzel', 7.5, 11, col('gold'), { ...caps(1.4), marginTop: pt(8) }),
];
书名用Cinzel,30磅字、33磅行距。书名框高14毫米,正好一行。“The Masque of the Red Death”和“La máscara de la muerte”都要两行,所以框随文字长高,最多到maxHeight的40毫米;超过这个高度才会缩小字号。副书名用below锚定在书名下方2毫米处,往下移了第二行的高度。作者名锚定在区域底部,位置不变。
#3 · 简介接着排进另一个框
简介框带有next: 'blurb-end'。放不下的内容在行与行之间切开,接着排进那个框;那个框在封面的Markdown里没有自己的frame。引文挂在简介下面,blurb-end挂在引文下面,所以第一个框加高时,三者之间的间距不变。只有第二个框也不够时,整条串接的文字才会一起缩小,默认最小到90%(fit.minScale)。那行金色小型大写字母是简介frame里的最后一段,所以它落在第二个框里,收住全文:
:::frame{slot="front"}
:::
:::frame{slot="blurb"}
:::paragraphs{style="cover-blurb-first"}
While a plague empties his country, Prince Prospero shuts himself up …
:::
:::paragraphs{style="cover-note"}
From the Raven Edition of Poe's works
:::
:::空的front frame让buildCover不再根据书的元数据在封面上排书名、副书名和作者:这些由文本框来排。
#4 · 书脊按页数算出的平装本
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-200-8', spineText: { minSpine: 4.5 } }],
};
const folio = { paper: { type: 'bookWove', grammage: 120, bulk: 2.2, shade: '#f8f3e8' } };
PUR胶装,16页一帖,用120 g/m²、松厚度2.2的书刊纸。书有21页,装订后32页,书脊约4.7毫米,低于默认印字所需的6毫米;所以这个版本把spineText.minSpine设为4.5,书脊上印书名和作者。ISBN是示例号码,不属于任何书。
#5 · 书芯
const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [125, 195, 21, 23, 18, 16, 14.6]; // mm, pt
const at = (to, edge, x, y, box) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
...(box && { size: box }) });
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('Cinzel', size, color, caps(size / 6));
const titling = (size, extra) => face('Cinzel', 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 wide = { width: mm(84) };
const headingStyles = [
{ ...none, id: 'half-title', advancedDesign: design(60, [
text('t', '{title}', titling(12), at('page', 'top', 0, 62, wide))]) },
// The title runs to two lines at 22 pt in both editions; the subtitle sits under them.
{ ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
text('t', '{title}', titling(22, { lineHeight: pt(27) }), at('page', 'top', 0, 44, wide)),
text('s', '{subtitle}', face('EB Garamond', 13, col('ink'), { italic: true }),
at('page', 'top', 0, 67)),
rule('r', 77),
text('a', '{author}', label(8.5, col('accent')), at('page', 'top', 0, 82)),
text('c', '{attr.credit}', face('EB Garamond', 10, col('muted'), { italic: true }),
at('page', 'top', 0, 118, { width: mm(76) })),
text('i', '{attr.imprint}', label(7.5), at('page', 'bottom', 0, -26)),
]) },
{ ...none, ...page('even'), id: 'rights',
advancedDesign: design(90, [rule('r', 84, 'container')]) },
// Each tale opens on a recto, sunk 50 mm, its title on one line of Cinzel over a short rule.
{ ...page('odd'), id: 'tale', toc: false, header: { elements: [] }, advancedDesign: design(50, [
text('t', '{titleText}', titling(13.5, { letterSpacing: pt(0.6) }),
at('container', 'top', 0, 24, { width: mm(W - INNER - OUTER) })),
rule('r', 40, 'container')]) },
{ ...none, ...page('odd'), id: 'colophon', advancedDesign: design(70, [
rule('r', 62, 'container')]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.6), parity, pages: 'body' },
at('page', 'top', 0, 11));
半书名页、书名页和版权页,然后每篇小说从奇数页开始,下沉50毫米,上面是Cinzel排的篇名和一条短红线。书眉在偶数页印作者,在奇数页印篇名,版本说明放在最后一个奇数页上收尾。
#6 · 印张由排好的内页生成
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="Cinzel"'));
}
const sheet = await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS));
buildCover接收页面、元数据和封面的Markdown,返回只有一页的文档,这一页就是印张。文本框成为这一页的frame,像组版页面的frame一样排版。条码数字要用OCR-B,没有哪个字体服务器提供,所以示例改用Cinzel。
#7 · 每个框最后落在哪里
// Each text box comes back as a frame of the sheet's composed page, with the rect it was
// given after anchoring and growing, and `continuesTo` when its text goes on elsewhere.
const leaf = sheet.pages[0];
const scale = 1100 / leaf.width;
const names = new Set(textBoxes.map((b) => b.name));
const frames = (leaf.composed?.frames ?? []).filter((f) => names.has(f.name));
const views = document.createElement('section');
views.id = 'box-views';
views.style.cssText = 'display: grid; gap: 18px; '
+ 'grid-template-columns: repeat(auto-fit, minmax(300px, 600px)); justify-content: center; '
+ 'padding: 24px 16px; color: #ddd; font: 14px sans-serif';
for (const [mode, name] of [['flat', t({ en: 'As it prints', es: 'Como se imprime' })],
['boxes', t({ en: 'The text boxes', es: 'Las cajas de texto' })]]) {
const [figure, canvas, caption] = ['figure', 'canvas', 'figcaption']
.map((tag) => document.createElement(tag));
figure.style.cssText = 'margin: 0; min-width: 0';
canvas.setAttribute('role', 'img');
canvas.setAttribute('aria-label', `${t({ en: 'The cover sheet', es: 'El pliego' })}: ${name}`);
renderPageToCanvas(leaf, sheet, canvas, { scale });
if (mode === 'boxes') {
// Each box outlined and named; a chain drawn from the foot of a box to its next.
const ctx = canvas.getContext('2d');
ctx.setTransform(scale, 0, 0, scale, 0, 0);
ctx.lineWidth = 2 / scale;
ctx.font = `${13 / scale}px sans-serif`;
for (const f of frames) {
const { x, y, width, height } = f.rect;
ctx.strokeStyle = ctx.fillStyle = '#f2c14e';
ctx.setLineDash([8 / scale, 5 / scale]);
ctx.strokeRect(x, y, width, height);
ctx.setLineDash([]);
// The name on a dark tab over the box's top-left corner, clear of the text.
const tab = ctx.measureText(f.name).width + 10 / scale;
ctx.fillStyle = '#141117';
ctx.fillRect(x, y - 18 / scale, tab, 18 / scale);
ctx.fillStyle = '#f2c14e';
ctx.fillText(f.name, x + 5 / scale, y - 5 / scale);
const next = frames.find((g) => g.id === f.continuesTo);
if (next) {
ctx.strokeStyle = '#ff7a59';
// Out of the box's foot, down its right side, into the top of the next.
const side = Math.max(x + width, next.rect.x + next.rect.width) + 14 / scale;
ctx.beginPath();
ctx.moveTo(x + width - 20 / scale, y + height);
ctx.lineTo(side, y + height);
ctx.lineTo(side, next.rect.y);
ctx.lineTo(next.rect.x + next.rect.width - 20 / scale, next.rect.y);
ctx.stroke();
}
}
}
// After the render, which sizes the canvas in CSS pixels: the column sets its width.
canvas.style.cssText = 'display: block; width: 100%; height: auto';
caption.textContent = name;
figure.append(canvas, caption);
views.append(figure);
}
document.getElementById('pages').before(views);
印张这一页的frame在page.composed.frames里,每个frame带着锚定和长高之后得到的矩形;文字接着排到别的frame时,还带有continuesTo。第二个视图在印张上画出六个框的轮廓,并从简介框的底边画到blurb-end的顶边,标出串接。
完整食谱
// ═══ Postext Cookbook · Nº 200 · Cover text boxes anchored, chained and grown ══════════════
// https://postext.dev/en/cookbook/cover-text-boxes-anchored
// Code: MIT · Text: E. A. Poe, tr. C. Olivera (public domain) · Art: diffusion models
// Fonts: EB Garamond, Cinzel (SIL OFL 1.1) · Needs postext ≥ 1.93.0
//
// Two of Poe's tales as a small paperback, and its cover sheet set from six text boxes.
// None of them has coordinates: each hangs from a panel of the sheet or from another box,
// so a title that runs to two lines takes the subtitle down with it, and the blurb on the
// back runs on under a quotation into a second box.
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 = 'cover-text-boxes-anchored';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The pages' four colours, then the cover's: a night ground, bone type, a dull gold.
const palette = { ink: '#231f1c', accent: '#8e2219', muted: '#6a625a', paper: '#faf6ee',
night: '#141117', bone: '#ece3cf', gold: '#c9a66b' };
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: six text boxes placed against the panels and against each other
// A box anchored to a zone stands on that point of the zone's safe area; a box anchored to
// another box hangs below it, above it or beside it. With an anchor, `rect` gives only the
// size. The title may grow to 40 mm before its type shrinks, and the blurb sends the lines
// it cannot hold to the box under the quotation.
const size = (width, height) => ({ x: 0, y: 0, width, height });
const textBoxes = [
// Front: the title from the top of the panel, the subtitle hung under it, the author
// standing on the foot. Only the title's box grows; the subtitle follows it down.
{ name: 'title', rect: size(100, 14), anchor: { to: 'front', edge: 'top', y: 8 },
maxHeight: 40 },
{ name: 'subtitle', rect: size(100, 9), anchor: { to: 'title', edge: 'below', y: 2 } },
{ name: 'author', rect: size(100, 8), anchor: { to: 'front', edge: 'bottom', y: -6 } },
// Back: the blurb, a quotation under it, and the rest of the blurb under the quotation.
// What the blurb's 50 mm cannot hold goes on in `blurb-end`, cut between lines.
{ name: 'blurb', rect: size(94, 50), anchor: { to: 'back', edge: 'top', y: 6 },
next: 'blurb-end' },
{ name: 'quote', rect: size(94, 24), anchor: { to: 'blurb', edge: 'below', y: 5 },
verticalAlign: 'middle' },
{ name: 'blurb-end', rect: size(94, 46), anchor: { to: 'quote', edge: 'below', y: 5 } },
];
组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)
变化
#把作者名挂在副书名下面
这样作者名也会随书名下移,而不是留在区域底部。
- { name: 'author', rect: size(100, 8), anchor: { to: 'front', edge: 'bottom', y: -6 } },
+ { name: 'author', rect: size(100, 8), anchor: { to: 'subtitle', edge: 'below', y: 6 } },#把长书名缩到一行
去掉maxHeight,书名框保持14毫米,排版会缩小书名直到放得下:这里缩到一行,约为原字号的三分之二。
{ name: 'title', rect: size(100, 14), anchor: { to: 'front', edge: 'top', y: 8 },
- maxHeight: 40 },
+ fit: { minScale: 0.6 } },常见问题
- 被另一个框的
next指向的框,接收那个框传过来的文字。不要在封面的Markdown里给它单独的frame;应该收尾的内容放在第一个框的frame末尾,就像这里的那行说明。 - 锚点指向不存在的名字、指向自己或形成循环时会报出来,文本框则留在它的
rect上。每个锚定的框都要给一个尺寸真实的rect。 maxHeight对旋转的框(rotate)不起作用,旋转的框保持rect的尺寸。
致谢
- 文本
- The Masque of the Red Death and The Oval Portrait, from The Works of Edgar Allan Poe (Raven Edition, 1903), Project Gutenberg eBooks #2148 and #2147 · Edgar Allan Poe · 公有领域
- La máscara de la muerte and El retrato oval, translated by Carlos Olivera, from Novelas y cuentos (Garnier Hermanos, Paris, 1884), as transcribed on Wikisource, spelling and punctuation modernised · Carlos Olivera · 公有领域
- 图片
- The cover painting: a masked ball in a file of coloured rooms under a Gothic vault, with an ebony clock and a figure in a grave-shroud, in oils · Generated With Diffusion Models · 原创
- 字体
- EB Garamond (SIL OFL 1.1) · Cinzel (SIL OFL 1.1)


