Коротко
Глава учебника о горах в две колонки с семью нумерованными рисунками. Она показывает, как каждый рисунок занимает первое свободное место после первого упоминания в тексте.
Что получится
Глава 2 книги Mountain Landforms, учебника геоморфологии с полосой 200 × 250 мм. На начальной полосе с верхнего края свисает синяя лента с номером главы, рядом льдисто-голубая плита с заголовком; дальше две колонки Faustina по формату. Семь рисунков, иллюстрации диффузионных моделей с подписями, поставленными кодом, нумеруются в порядке первого упоминания. Шесть уходят в первый свободный слот, который допускает их размещение, считая от абзаца с первой ссылкой. Рисунок 2.1, auto, встаёт внизу начальной полосы; 2.3 открывает правую колонку страницы 28, а 2.2 занимает её низ; 2.4 и 2.5 открывают две колонки страницы 29. Рисунок 2.6 стоит там, где его вставляет текст. Рисунок 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, а 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 мм под ней с округлением до целых линий сетки (здесь около 7 мм), поэтому рисунок 2.1 ещё помещается в нижний ярус той же полосы. Колонтитулы сидят во внешних углах над волосной линейкой цвета rule, а pages: 'body' убирает их с начальной полосы, где вместо них опущенная колонцифра.
#4 · Остановиться на неизвестном идентификаторе или рисунке без ссылки
// 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('; ')}`);
}
:ref или ::resource с идентификатором, которого нет ни у одного ресурса, печатает «?» и ничего не ставит; сборка записывает каждый такой случай в doc.contentWarnings как unknownResourceId, с идентификатором и местом в источнике. Рисунок, который никто не упомянул, не ставится и предупреждения не вызывает, поэтому проверка читает Markdown через parseMarkdown, собственный разбор движка, и сравнивает упоминания с рисунками. Неизвестный идентификатор, рисунок без ссылки или рисунок here без строки ::resource дают одну ошибку ещё до показа страниц.
#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 рисунок 2.3 стоит выше рисунка 2.2, у которого номер меньше, потому что текст ссылается на него раньше. ![]() из Markdown вырезается, поэтому каждый рисунок — ресурс, чей SVG зарегистрирован под своим svg.fileId до сборки. Каждое размещение следует из места ссылки: auto для 2.1, потому что верх начальной полосы занят плитой; bottom для профиля, который ещё успевает занять низ той полосы, где на него ссылаются; top для рисунков в колонку, которые открывают ближайшие свободные колонки; и top для 2.7, который оказывается внизу страницы 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 = 'en'; // @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: { // the text colour follows bodyText; the note is 0.85 × the caption size
+ position: 'above', backgroundEnabled: true, background: col('ice'),
fontFamily: LABEL, fontSize: pt(8.3), gap: mm(2.2),#Поставить рисунок на поле
Полоса в полторы колонки отдаёт рисункам и подписям внешнюю колонку, куда текст не заходит: см. учебник с колонкой на поле.
#Так же выносить таблицы
Таблицы — тоже ресурсы, на них ссылаются и их ставят по тем же правилам, а длинная делится между страницами: см. технический паспорт.
Частые ошибки
Подводный камень
Объект 'top' уходит на страницу после ссылки, если ему не разрешено открыть страницу со ссылкой
По умолчанию плавающий объект не поднимается выше собственной ссылки, поэтому объект 'top' на всю ширину, вызванный на странице N, открывает страницу N+1. Задайте placement.citingPage: true у ресурса или в defaultPlacement его типа (либо layout.floatsAtCitingPage для всей книги, начиная с postext 1.25), и он откроет страницу N, а текст над ссылкой сдвинется под него, если объект укладывается в layout.maxTopFraction и строка со ссылкой остаётся на этой странице. Первую страницу главы и страницу после принудительного разрыва он не открывает: там он по-прежнему уходит на следующую, а 'auto' и 'bottom' могут занять низ страницы со ссылкой. Размещение рисунков →
Подводный камень
::resource{id="…"} — только с двойными кавычками
Вставка блоком распознаётся только в виде ::resource{id="…"} с двойными кавычками; любая другая форма остаётся в тексте видимой строкой. Рисунки точно здесь →
Подводный камень
Без <marker> и фильтров в SVG (иначе растр)
SVG-рисунок остаётся в PDF векторным только без <marker>, фильтров и масок; иначе он заменяется растром, а глубоко вложенные фильтры могут сделать его в Chrome пустым. Рисуйте наконечники стрелок контурами. Рисунки и таблицы как ресурсы →
Проверка Sandbox · unknownResourceId
Неизвестный ресурс
Причина. :ref или ::resource называет id, которого нет ни у одного ресурса; ссылка печатает «?», и ничего не размещается.
Решение. Исправьте id (только прямые двойные кавычки) или добавьте ресурс. Документация →
Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- Оригинальный текст, 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)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)


