简单来说
一本山地教材中的一章,分两栏排,有七幅编号插图。示例演示每幅图怎样自动放到正文首次提到它之后的第一个空位。
成品一览
这是地貌学教科书《Mountain Landforms》的第2章,页面尺寸为200 × 250 mm。章首页上,一条带章号的蓝色飘带从页顶垂下,旁边是标题所在的冰蓝色色块;后面是两栏两端对齐的Faustina。七幅图是用扩散模型生成、再用代码加上标注的画,按首次提及的顺序编号。其中六幅从首次引用它的段落算起,浮动到其位置设置允许的第一个空位。Figure 2.1设为auto,落在章首页底部;2.3排在第28页右栏顶部,2.2填满同一页的底部;2.4和2.5分别排在第29页两栏的顶部。Figure 2.6放在正文嵌入它的地方。Figure 2.7是一个top浮动体,在第30页被引用,本应等到第31页,但浮动体不能离开所在的章,所以它排到了第30页底部。
这道食谱解答
- 怎样加一幅带编号题注的图,并在正文里引用它(“见图3.2”)?
- 怎样控制图的位置:页面顶部、横跨两栏、就放在这里,还是放在边栏里?
- 怎样让“图”和“表”的标签使用文档的语言?
- 怎样用代码(资源)而不是Markdown的![]()添加图片和表格?
简短回答
// In the Markdown, :ref{id="valleys" case="lower"} prints 'fig. 2.1' and places Figure 2.1.
// Captions, credits and alt texts come from content.figures.<lang>.md.
const figure = (id, height, placement) => {
if (!TEXTS[id]) throw new Error(`content.figures has no caption block for "${id}"`);
const [caption, note, altText] = TEXTS[id];
// An SVG fills the width of its slot (a column or the text block, or a fraction of
// either), so its width and height only give its shape.
const width = (placement.span === 'page' ? MEASURE : COLUMN) * (placement.width ?? 1);
return { id, typeId: 'figure', kind: 'svg', caption, note, altText,
svg: { fileId: `${id}.svg`, width, height }, placement, createdAt: 0, updatedAt: 0 };
};
// In any order: the first mention of each one in the text, a :ref or a ::resource line,
// decides its number.
const resources = [
// Cited on the opener page: 'auto' may take that page's foot band, where 'top'
// could only open the next page (gotcha: top-float-next-page).
figure('valleys', 56, { position: 'auto', span: 'page' }),
// Across both columns, but only in a foot band: the page it is cited on, if both
// columns still have room there, else the foot of the next page.
figure('profile', 60, { position: 'bottom', span: 'page' }),
// A column figure that takes only a column head: the next one still empty after its
// citation, here the right column of the same page, above the text that follows it.
figure('cirque', 48, { position: 'top' }),
// Cited in the same sentence, the two take the next two column heads, side by side.
figure('abrasion', 48, { position: 'top' }),
figure('plucking', 48, { position: 'top' }),
// No float: set exactly where ::resource{id="roche"} stands, with the same gap above it
// and below it.
figure('roche', 42, { position: 'here' }),
// A band of its own, half the text width and centred. It is cited on the chapter's last
// page, where a 'top' float would wait for the next page; a float cannot leave its
// chapter, so this one goes to the foot of the last page.
figure('moraines', 50, { position: 'top', span: 'page', width: 0.5, align: 'center' }),
];
用料
- 功能
- 决定图位置的引用图的放置编号题注图就放在这里浮动体屏障用你的语言显示“图”和“表”题注样式来源与出处行作为资源的图和表自定义资源类型设计过的章首页通栏章首色带标题属性编号标题断词与文档语言书眉与页码按页面角色显示书眉语义调色板各栏齐底
- 还用到
- 段落样式
- 类型
- Faustina, Montserrat, IBM Plex Sans Condensed(SIL OFL 1.1)
- 素材
abrasion-1080.jpgcirque-1080.jpgmoraines-1080.jpgplucking-1080.jpgprofile-1400.jpgroche-1080.jpgvalleys-1536.jpg- Figure 2.1: a V-shaped river valley and a U-shaped glacial valley (Generated With Diffusion Models, 原创)
- Figure 2.2: long profile of a valley glacier (Generated With Diffusion Models, 原创)
- Figure 2.3: a glacial cirque in section (Generated With Diffusion Models, 原创)
- Figure 2.4: abrasion at the base of the ice (Generated With Diffusion Models, 原创)
- Figure 2.5: plucking on a rock step (Generated With Diffusion Models, 原创)
- Figure 2.6: a roche moutonnée (Generated With Diffusion Models, 原创)
- Figure 2.7: lateral, medial and terminal moraines in plan (Generated With Diffusion Models, 原创)
做法
#1 · 页面和图共用一套调色板
const palette = {
ink: '#1b2227', // text: a cold near-black
glacier: '#34729a', // the accent: kicker, ribbon, caption labels, references, folios, water
ice: '#e3f1f8', // the opener slab
rock: '#5b5a57', // bedrock in the drawings
moss: '#7d8f4e', // valley floors and pines
rule: '#c6d3db', // the hairline under the running heads
muted: '#5d6a72', // running heads, credit notes, the colophon
paper: '#ffffff',
};
// A linked colour carries its hex and the palette entry it follows.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
// The engine's defaults link to 'main-color' (#295aa3): pointing it at the accent keeps
// that second blue off the page.
{ id: 'main-color', name: 'glacier (defaults)', value: { hex: palette.glacier, model: 'hex' } },
];
配置中的每种颜色都链接到这里的某一项,而画作也是用同样的石板灰、冰川蓝和苔绿生成的,所以图与页面的颜色一致。画作保留自己的颜色:给glacier换一个值,会改变飘带、色块和标注,但不会改变图中冰的颜色。强调色足够深,可以用于小字:在白底上对比度为5.2:1,用于题注标签和引用;在冰蓝色块上为4.5:1,用于眉题。每幅图都是一个SVG,把画作以JPEG data URL嵌入,并在上面用文字排出标注,带一圈细细的白色描边,所以标注保持清晰,并随版本的语言变化。标注在SVG上直接写明IBM Plex Sans Condensed,kit的loadSvg再通过引擎的inlineSvgFonts把用到的两种字重嵌进去,因为作为图像显示的SVG自己取不到页面的字体。
#2 · 用读者的语言给图命名
const captions = () => ({
// The built-in types take their names from the locale: 'Figure 2.3' and 'fig. 2.3' with
// 'en-us', 'Figura 2.3' with 'es', numbered {h1}.{n} per chapter. It sets hyphenation too.
locale: t({ en: 'en-us', es: 'es' }),
captionStyle: { // the text colour follows bodyText; the note is 0.85 × the caption size
fontFamily: LABEL, fontSize: pt(8.3), gap: mm(2.2),
labelColor: col('glacier'), descriptionItalic: true, // the label is bold by default
note: { color: col('muted'), gap: mm(0.6) }, // the credit line
},
});
locale用文档的语言给内置类型命名:这里的题注是Figure 2.3,西班牙文版是Figura 2.3;同一个'es'还选定西班牙语的断词规则。每处引用再采用所在句子需要的形式:case="lower"得到*(fig. 2.1),再加上style="full"得到(figure 2.2);复数之后用style="number"(figures 2.4 and 2.5);text="…"用于the chapter’s first figure*这样的短语,不印编号。这个短语指回一幅已经放好的图;如果作为首次提及,它仍然会给图编号并确定其位置。
#3 · 章首页的飘带和冰色块
const at = (to, edge, x, y, width, height) => ({ anchor: { to, edge },
offset: { x: mm(x), y: mm(y) },
...(width && { size: { width: mm(width), height: height ? mm(height) : 'auto' } }) });
const text = (id, content, family, size, color, placement, extra) => ({ kind: 'text', id,
content, fontFamily: family, fontSize: pt(size), color: col(color), placement,
align: 'left', ...extra });
const caps = (size) => ({ fontWeight: 600, textTransform: 'uppercase',
letterSpacing: pt(size * 0.18) }); // capitals tracked 0.18 em
const [SLAB, RIBBON, RIBBON_END] = [64, 30, 70]; // mm: slab height; ribbon width and length
const [TEXT_X, KICKER_Y] = [RIBBON + 8, 10]; // mm: the opener texts start 8 mm right of the ribbon
const [TITLE_W, LEAD_W] = [118, 112]; // mm: the title's measure, and a shorter standfirst
const opener = {
enabled: true,
// At least 5 mm under the slab; the reserve then rounds up to whole 13.4 pt grid lines,
// so here 69 mm becomes 15 lines (70.9 mm) and the text starts about 7 mm under the slab.
minHeight: mm(SLAB + 5),
slot: { elements: [
{ kind: 'box', id: 'slab', style: { backgroundColor: col('ice') }, // runs off the fore-edge
placement: at('container', 'top-left', 0, 0, MEASURE + OUTER, SLAB) },
{ kind: 'box', id: 'ribbon', style: { backgroundColor: col('glacier') }, // hangs from the head
placement: at('page', 'top-left', INNER, 0, RIBBON, RIBBON_END) },
text('numeral', '{chapterNumber}', DISPLAY, 80, 'paper', // an 80 pt line box is 28 mm tall:
at('page', 'top-left', INNER, RIBBON_END - 31, RIBBON), // it ends 3 mm above the foot
{ fontWeight: 800, lineHeight: 1, align: 'center' }),
text('kicker', t({ en: 'Chapter {chapterNumber} · {attr.topic}',
es: 'Capítulo {chapterNumber} · {attr.topic}' }), LABEL, 8.5, 'glacier',
at('container', 'top-left', TEXT_X, KICKER_Y), caps(8.5)),
text('title', '{titleText}', DISPLAY, 27, 'ink', at('#kicker', 'below', 0, 2.6, TITLE_W),
{ fontWeight: 800, lineHeight: 1.06 }),
text('lead', '{attr.lead}', TEXT, 10.6, 'ink', at('#title', 'below', 0, 4.2, LEAD_W),
{ italic: true, lineHeight: 1.38, hyphenate: true }),
] },
};
const HAIRLINE = TOP - 5; // mm from the top edge: the rule under the running heads
const HEAD_Y = HAIRLINE - 4.4; // the running heads' line box, 4.4 mm above the hairline
const head = (id, content, parity, edge, x, extra) => text(id, content, LABEL, 7.6, 'muted',
at('page', edge, x, HEAD_Y), { ...caps(7.6), parity, pages: 'body', ...extra });
const folio = (id, parity, edge, x, extra) => text(id, '{pageNumber}', DISPLAY, 8.5, 'glacier',
at('page', edge, x, HEAD_Y), { fontWeight: 800, parity, pages: 'body', ...extra });
const header = { elements: [ // outer corners, over a hairline; never on the opener
folio('verso-folio', 'even', 'top-left', OUTER),
head('verso-title', '{title}', 'even', 'top-left', OUTER + 8),
head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 8), { align: 'right' }),
folio('recto-folio', 'odd', 'top-right', -OUTER, { align: 'right' }),
{ kind: 'rule', id: 'hairline', pages: 'body', direction: 'horizontal', color: col('rule'),
thickness: pt(0.5), placement: { ...at('container', 'top-left', 0, HAIRLINE),
size: { width: 'fill', height: 'auto' } } },
] };
const footer = { elements: [ // the drop folio: on the opener only, centred 9 mm under the text
text('drop-folio', '{pageNumber}', DISPLAY, 8.5, 'glacier', at('container', 'top', 0, 9),
{ fontWeight: 800, align: 'center', pages: 'opener' })] };
章首页由两个框和四段文字组成:一条从页顶垂下、底端带章号的飘带,一块伸出书口的冰色块,取自标题topic属性的眉题,以及依次挂在它下方的标题和导语。minHeight预留出色块及其下方至少5 mm的空间,向上取整到整数个网格行(这里约7 mm),所以Figure 2.1仍能放进同一页的底部区域。书眉位于外侧角上,下面是一条rule颜色的细线,pages: 'body'让章首页不印书眉,章首页改用排在页脚的页码。
#4 · 遇到未知的id或未被引用的图就停下
// The build lists every :ref and ::resource to an id no resource has in doc.contentWarnings
// (kind 'unknownResourceId'); each prints '?' on the page. A figure nobody names is never
// placed and raises no warning, so the pen reads the mentions with the engine's own parser;
// an embed needs double quotes (gotcha: resource-double-quotes).
function checkFigures(doc) {
const [named, embedded] = [new Set(), new Set()];
for (const block of parseMarkdown(markdown)) {
if (block.type === 'resourceBlock' && block.resourceId) {
named.add(block.resourceId);
embedded.add(block.resourceId);
}
for (const span of block.spans) if (span.ref?.resourceId) named.add(span.ref.resourceId);
}
const unknown = (doc.contentWarnings ?? []).filter((w) => w.kind === 'unknownResourceId');
const problems = [
...new Set(unknown.map((w) => `unknown id "${w.resourceId}"`)),
...resources.filter((r) => !named.has(r.id)).map((r) => `"${r.id}" is never cited`),
...resources.filter((r) => r.placement.position === 'here' && !embedded.has(r.id))
.map((r) => `"${r.id}" is placed 'here' but no ::resource line embeds it`),
];
if (problems.length) throw new Error(`Figures: ${problems.join('; ')}`);
}
指向不存在的资源id的:ref或::resource会印出“?”,也不放置任何内容;构建时每一处都会记入doc.contentWarnings,种类为unknownResourceId,带有id和它在源文本中的位置。没人提及的图永远不会被放置,也不产生警告,所以检查用引擎自己的解析器parseMarkdown读取Markdown,把提及与图逐一比对。未知的id、未被引用的图,以及没有::resource行的here图,都会在显示页面之前合成一个错误。
#5 · 从全书的当前位置开始计数
for (const { id, svg: { fileId, width, height } } of resources) { // each under its svg.fileId
const art = await dataUrl(PAINTINGS[id]);
await loadSvg(fileId, svg(width, height, `<image href="${art}" width="${n2(width)}" `
+ `height="${n2(height)}" preserveAspectRatio="none"/>${DRAWINGS[id](width, height)}`));
}
// One chapter came before: figures number 2.1, 2.2… and the folios start at 27.
const continuation = { pageNumbering: { startAt: 27 }, // odd, to match the recto of page 1
headings: { h1: 1, h2: 0, h3: 0, h4: 0, h5: 0, h6: 0 } }; // the next # is chapter 2
const doc = await buildDocumentWithFonts({ markdown, resources, continuation }, config(),
{ ...kitFonts(FONTS), text: words });
checkFigures(doc); // a wrong id stops here, and the viewer's bar says why
showPages(doc, { title: t({ en: 'Figures that float to where you cite them',
es: 'Figuras que flotan hasta donde las citas' }) });
这是一本较长的书的第2章,所以接续信息记录了它之前的一章:按{h1}.{n}编号的图从2.1开始,页码从27开始。在第28页上,Figure 2.3排在Figure 2.2上方,后者编号较小,因为正文先引用它。Markdown的![]()会被去掉,所以每幅图都是一个资源,其SVG在排版前以svg.fileId注册。每幅图的位置都取决于它在哪里被引用:2.1用auto,因为色块占满了章首页的顶部;纵剖面用bottom,它还能占用引用它那一页的底部;各栏中的图用top,排在接下来空出的栏顶;2.7也用top,它最终排在第30页底部,因为浮动体不会离开所在的章。
完整食谱
// ═══ Postext Cookbook · Nº 009 · Figures that float to where you cite them ═════════
// https://postext.dev/en/cookbook/figures-float-where-cited
// Code: MIT · Text: original (CC BY 4.0) · Figures: diffusion models, labels in code
// Fonts: Faustina, Montserrat, IBM Plex Sans Condensed (SIL OFL 1.1) · Needs postext ≥ 1.25.0
//
// Chapter 2 of a geomorphology textbook. Six of its seven figures float, each to the first
// free slot its placement allows, counting from the paragraph that first cites it. Figure 2.6
// is set where ::resource embeds it. The figures are numbered in order of first mention.
import {
buildDocumentWithFonts, prepareFonts, renderPageToCanvas, registerResourceImage,
inlineSvgFonts, parseMarkdown,
} from 'https://esm.sh/postext';
const LANG = 'es'; // @lang: the language of the sample document ('es' | 'en')
const RECIPE = 'figures-float-where-cited';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: eight named colours; the paintings were made to match them
const palette = {
ink: '#1b2227', // text: a cold near-black
glacier: '#34729a', // the accent: kicker, ribbon, caption labels, references, folios, water
ice: '#e3f1f8', // the opener slab
rock: '#5b5a57', // bedrock in the drawings
moss: '#7d8f4e', // valley floors and pines
rule: '#c6d3db', // the hairline under the running heads
muted: '#5d6a72', // running heads, credit notes, the colophon
paper: '#ffffff',
};
// A linked colour carries its hex and the palette entry it follows.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
// The engine's defaults link to 'main-color' (#295aa3): pointing it at the accent keeps
// that second blue off the page.
{ id: 'main-color', name: 'glacier (defaults)', value: { hex: palette.glacier, model: 'hex' } },
];
// #endregion
const TEXT = 'Faustina'; // one family each for text, display and labels
const DISPLAY = 'Montserrat';
const LABEL = 'IBM Plex Sans Condensed';
const LEAD = 13.4; // body leading in pt: the grid every float band snaps to
const [PAGE_W, PAGE_H, TOP, BOTTOM, INNER, OUTER, GUTTER] = [200, 250, 22, 20, 18, 14, 6]; // mm
const MEASURE = PAGE_W - INNER - OUTER; // 168 mm: the text block, and a page-wide figure
const COLUMN = (MEASURE - GUTTER) / 2; // 81 mm: a column, and a column figure
// #region captions: the type name in the document's language; bold label, italic description
const captions = () => ({
// The built-in types take their names from the locale: 'Figure 2.3' and 'fig. 2.3' with
组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)
变化
#图号不带章号
从编号中去掉章号,图就印成1到7;如果要全书统一计数,用buildBundle排各章,或者把前一章的continuationAfter()传给后一章。
- inlineSvgFonts, parseMarkdown,
+ inlineSvgFonts, parseMarkdown, defaultResourceTypes,
@@
locale: t({ en: 'en-us', es: 'es' }),
+ resourceTypes: defaultResourceTypes(LANG).map((type) => ({ ...type,
+ numberingTemplate: '{n}', resetOn: 'never' })),#把题注放在上方的色条上
题注移到图的上方,放在调色板冰蓝色的色条上,出处行仍留在图下方;需要重新调整正文,因为这样两个版本都会排到第五页。
captionStyle: { // 文字颜色跟随bodyText;注释为题注字号的0.85倍
+ position: 'above', backgroundEnabled: true, background: col('ice'),
fontFamily: LABEL, fontSize: pt(8.3), gap: mm(2.2),#把图放在边栏里
一栏半的页面给图和题注留出一条正文从不进入的外侧通道:参见带边注栏的教科书。
#用同样的方式浮动表格
表格也是资源,按同样的规则引用和定位,长表还会跨页拆分:参见技术数据表。
常见问题
易错点
'top'浮动体默认排在引用页的下一页,除非允许它置于引用页顶
默认情况下浮动体不会排在自己的引用之前,所以在第N页引用的整页宽'top'浮动体会出现在第N+1页的顶部。在资源或其类型的defaultPlacement上设置placement.citingPage: true(或者对全书设置layout.floatsAtCitingPage,自postext 1.25起),它就改为置于第N页顶部,引用处之上的文字移到它下方,前提是它不超过layout.maxTopFraction且引用行仍留在该页。它不会置于章首页或强制分页之后的页面顶部:那时仍排在下一页,而'auto'或'bottom'可以占用引用页的底部。 图的放置 →
易错点
SVG插图中不要用<marker>或滤镜(会退回位图)
SVG图只有在不含<marker>、滤镜和蒙版时,才能在PDF中保持矢量;否则会退回位图,而且层层嵌套的滤镜可能让它在Chrome中变成空白。箭头用路径来画。 作为资源的图和表 →
沙盒检查 · unknownResourceId
未知资源
原因. 某个:ref或::resource指定的id没有对应的资源;引用处印出“?”,也不会放置任何内容。
解决. 改正id(只能用双引号),或添加该资源。 文档 →
致谢
- 文本
- 原创文字, CC BY 4.0
- 图片
- Figure 2.1: a V-shaped river valley and a U-shaped glacial valley · Generated With Diffusion Models · 原创
- Figure 2.2: long profile of a valley glacier · Generated With Diffusion Models · 原创
- Figure 2.3: a glacial cirque in section · Generated With Diffusion Models · 原创
- Figure 2.4: abrasion at the base of the ice · Generated With Diffusion Models · 原创
- Figure 2.5: plucking on a rock step · Generated With Diffusion Models · 原创
- Figure 2.6: a roche moutonnée · Generated With Diffusion Models · 原创
- Figure 2.7: lateral, medial and terminal moraines in plan · Generated With Diffusion Models · 原创
- 字体
- Faustina (SIL OFL 1.1) · Montserrat (SIL OFL 1.1) · IBM Plex Sans Condensed (SIL OFL 1.1)


