Pular para o conteúdo principal
Receita número 9

Receitas · Capítulo 7 · Figuras e imagens

Figuras que flutuam até onde você as cita

Capítulo em duas colunas com sete figuras numeradas: seis flutuam do primeiro :ref até o primeiro espaço que a posição permite; uma fica onde ::resource a põe.

Nesta página
Saída
Canvas
Nível
Avançado
Postext
Testada com o Postext 1.65.0
Requer ≥ 1.25.0
Licença
Atualizada em 11 de out. de 2026
Código MIT · Texto CC BY 4.0

p. 28–29 · 2–3 de 4

  • Amostra em inglês: ainda sem edição em português
  • Refile 200 × 250 mm
  • 2 colunas, medianiz de 6 mm
  • Faustina 9,4/13,4
  • IBM Plex Sans Condensed
  • Montserrat
  • 4 páginas
  • Nível
  • Postext 1.65.0
  • Diagramado em 197 ms
  • 224 linhas de código

Em poucas palavras

Um capítulo de livro didático sobre montanhas, em duas colunas, com sete imagens numeradas. Mostra como cada imagem vai para o primeiro espaço livre depois que o texto a menciona.

O que você vai compor

O capítulo 2 de Mountain Landforms, um livro didático de geomorfologia numa página de 200 × 250 mm. Uma fita azul com o número do capítulo pende do alto da abertura, ao lado da placa azul-gelo do título; seguem duas colunas justificadas de Faustina. As sete figuras, pinturas geradas com modelos de difusão e rotuladas em código, são numeradas na ordem da primeira menção. Seis flutuam até o primeiro espaço livre que a posição permite, contando a partir do parágrafo que as cita primeiro. A Figura 2.1, auto, cai no pé da abertura; a 2.3 abre a coluna da direita da página 28 e a 2.2 ocupa o pé dessa página; a 2.4 e a 2.5 abrem as duas colunas da página 29. A Figura 2.6 fica onde o texto a insere. A Figura 2.7, uma flutuante top citada na página 30, esperaria pela página 31, mas uma flutuante não pode sair do capítulo, de modo que ela vai para o pé da página 30.

Esta receita responde a

  • Como acrescento uma figura com legenda numerada e a cito no texto (“ver fig. 3.2”)?
  • Como decido onde vai uma figura: no alto da página, sobre as duas colunas, exatamente aqui ou na margem?
  • Como faço os rótulos “Figura” e “Tabela” saírem no idioma do meu documento?
  • Como adiciono imagens e tabelas a partir do código (recursos) em vez de usar ![]() do Markdown?

A resposta curta

script.js · linhas 252–285no código completo
// 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' }),
];

Ingredientes

Tipografia
Faustina, Montserrat, IBM Plex Sans Condensed (SIL OFL 1.1)
Materiais
  • abrasion-1080.jpg
  • cirque-1080.jpg
  • moraines-1080.jpg
  • plucking-1080.jpg
  • profile-1400.jpg
  • roche-1080.jpg
  • valleys-1536.jpg
  • Figure 2.1: a V-shaped river valley and a U-shaped glacial valley (Generated With Diffusion Models, original)
  • Figure 2.2: long profile of a valley glacier (Generated With Diffusion Models, original)
  • Figure 2.3: a glacial cirque in section (Generated With Diffusion Models, original)
  • Figure 2.4: abrasion at the base of the ice (Generated With Diffusion Models, original)
  • Figure 2.5: plucking on a rock step (Generated With Diffusion Models, original)
  • Figure 2.6: a roche moutonnée (Generated With Diffusion Models, original)
  • Figure 2.7: lateral, medial and terminal moraines in plan (Generated With Diffusion Models, original)

Preparo

#1 · Uma paleta para as páginas e as figuras

script.js · linhas 19–36no código completo
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' } },
];

Toda cor da configuração aponta para uma destas entradas, e as pinturas foram geradas nos mesmos tons de ardósia, azul-geleira e musgo, por isso as figuras ficam nas cores da página. Uma pintura mantém as próprias cores: um novo valor para glacier muda a fita, a placa e os rótulos, não o gelo das figuras. A cor de destaque é escura o bastante para letra pequena: 5,2:1 sobre o branco nos rótulos das legendas e nas citações, 4,5:1 sobre a placa de gelo no antetítulo. Cada figura é um SVG que incorpora a pintura como um JPEG em data URL e põe os rótulos por cima como texto, com um halo branco fino, para que fiquem nítidos e acompanhem o idioma da edição. Os rótulos indicam a IBM Plex Sans Condensed no próprio SVG, e o loadSvg do kit incorpora os dois pesos que eles usam com o inlineSvgFonts do motor, porque um SVG exibido como imagem não alcança sozinho as fontes da página.

#2 · Dê nome às figuras no idioma do leitor

script.js · linhas 47–56no código completo
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 dá nome aos tipos padrão no idioma do documento: as legendas dizem Figure 2.3 aqui e Figura 2.3 na edição em espanhol, em que o mesmo 'es' escolhe os padrões de hifenização do espanhol. Cada citação então toma a forma que a frase pede: case="lower" para (fig. 2.1) e, com style="full", para (figure 2.2); style="number" depois de um plural (figures 2.4 and 2.5); e text="…" para uma expressão como the chapter’s first figure, que não imprime número. Essa expressão remete a uma figura já posicionada; como primeira menção, ela ainda numeraria e posicionaria a figura.

#3 · Uma fita e uma placa de gelo para a abertura

script.js · linhas 60–110no código completo
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' })] };

A abertura são duas caixas e quatro textos: uma fita que pende do alto com o número do capítulo na ponta, uma placa de gelo que sangra pela borda externa, o antetítulo tirado do atributo topic do título, e o título e a linha fina encadeados abaixo dele. minHeight reserva a placa e pelo menos 5 mm abaixo dela, arredondados para cima em linhas inteiras da grade (uns 7 mm aqui), de modo que a Figura 2.1 ainda cabe na faixa do pé da mesma página. Os cabeços ficam nos cantos externos sobre um fio fino na cor rule, e pages: 'body' os tira da abertura, que recebe um fólio no pé.

#4 · Pare num id desconhecido ou numa figura não citada

script.js · linhas 289–310no código completo
// 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('; ')}`);
}

Um :ref ou um ::resource para um id que nenhum recurso tem imprime "?" e não posiciona nada; a diagramação registra cada um em doc.contentWarnings como unknownResourceId, com o id e o lugar dele no texto de origem. Uma figura que ninguém menciona nunca é posicionada e não gera aviso, por isso a verificação lê o Markdown com parseMarkdown, o analisador do próprio motor, e compara as menções com as figuras. Um id desconhecido, uma figura não citada ou uma figura here sem linha ::resource viram um único erro antes de as páginas serem mostradas.

#5 · Comece a contagem onde o livro está

script.js · linhas 417–429no código completo
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' }) });

Este é o capítulo 2 de um livro mais longo, de modo que a continuação registra um capítulo antes dele: as figuras numeradas {h1}.{n} começam em 2.1, e os fólios em 27. Na página 28, a Figura 2.3 fica acima da Figura 2.2, que tem o número menor porque o texto a cita primeiro. O ![]() do Markdown é descartado, por isso cada figura é um recurso cujo SVG é registrado sob o svg.fileId antes da composição. Cada posição decorre de onde a figura é citada: auto para a 2.1, porque a placa ocupa o alto da abertura; bottom para o perfil, que ainda pode ocupar o pé da página que o cita; top para as figuras de coluna, que abrem os próximos altos de coluna livres; e top também para a 2.7, que acaba no pé da página 30 porque uma flutuante fica dentro do capítulo.

A receita completa

Sandbox
// ═══ 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

O script.js montado funciona como está: cole-o como script de módulo em qualquer página ou abra a receita no CodePen. Pasta da receita no GitHub ↗ (abre em uma nova aba)

Variações

#Numere as figuras sem o capítulo

Tire o capítulo dos números e as figuras saem de 1 a 7; para uma contagem única no livro inteiro, diagrame os capítulos com buildBundle ou passe a cada capítulo o continuationAfter() do anterior.

-  inlineSvgFonts, parseMarkdown,
+  inlineSvgFonts, parseMarkdown, defaultResourceTypes,
@@
   locale: t({ en: 'en-us', es: 'es' }),
+  resourceTypes: defaultResourceTypes(LANG).map((type) => ({ ...type,
+    numberingTemplate: '{n}', resetOn: 'never' })),

#Ponha as legendas em cima, numa barra

A legenda sobe para cima da figura, numa barra no azul-gelo da paleta, e a linha de crédito fica embaixo da figura; reajuste o texto, já que as duas edições passam então para uma quinta página.

   captionStyle: { // a cor do texto segue bodyText; a nota tem 0,85 × o corpo da legenda
+    position: 'above', backgroundEnabled: true, background: col('ice'),
     fontFamily: LABEL, fontSize: pt(8.3), gap: mm(2.2),

#Ponha uma figura na margem

Uma página em coluna e meia dá às figuras e às legendas um canal externo em que o texto nunca entra: veja o livro didático com coluna na margem.

#Faça as tabelas flutuarem do mesmo jeito

Tabelas também são recursos, citadas e posicionadas pelas mesmas regras, e uma tabela longa se divide entre páginas: veja a ficha técnica.

Erros comuns

Erro comum

Um flutuante 'top' vai para a página seguinte à sua citação, a menos que possa encabeçar a página que o cita

Por padrão um flutuante nunca fica acima da própria referência, então um flutuante 'top' na largura da página citado na página N abre a página N+1. Com placement.citingPage: true no recurso ou no defaultPlacement do seu tipo (ou layout.floatsAtCitingPage para o livro todo, desde o postext 1.25) ele encabeça a página N, e o texto acima da referência desce para baixo dele, quando cabe dentro de layout.maxTopFraction e a linha que o cita continua nessa página. Nunca encabeça a primeira página de um capítulo nem uma página depois de uma quebra forçada: ali continua abrindo a página seguinte, e 'auto' ou 'bottom' podem ocupar o pé da página que o cita. Posicionamento de figuras →

Erro comum

::resource{id="…"} só aceita aspas duplas

Uma inserção em bloco só é reconhecida como ::resource{id="…"} com aspas duplas; qualquer outra forma fica no texto como uma linha visível. Figuras exatamente aqui →

Erro comum

Sem <marker> nem filtros na arte SVG (vira bitmap)

Uma figura SVG só continua vetorial no PDF sem <marker>, filtros e máscaras; caso contrário, é rasterizada, e filtros muito aninhados podem deixá-la em branco no Chrome. Desenhe as pontas de seta como caminhos (paths). Figuras e tabelas como recursos →

Verificação do Sandbox · unknownResourceId

Recurso desconhecido

Por quê. Um :ref ou ::resource cita um id que nenhum recurso tem; a referência imprime “?” e nada é colocado.

Correção. Corrija o id (só com aspas duplas) ou acrescente o recurso. Docs →

Créditos

Texto
Texto original, CC BY 4.0
Imagens
  • Figure 2.1: a V-shaped river valley and a U-shaped glacial valley · Generated With Diffusion Models · original
  • Figure 2.2: long profile of a valley glacier · Generated With Diffusion Models · original
  • Figure 2.3: a glacial cirque in section · Generated With Diffusion Models · original
  • Figure 2.4: abrasion at the base of the ice · Generated With Diffusion Models · original
  • Figure 2.5: plucking on a rock step · Generated With Diffusion Models · original
  • Figure 2.6: a roche moutonnée · Generated With Diffusion Models · original
  • Figure 2.7: lateral, medial and terminal moraines in plan · Generated With Diffusion Models · original
Fontes
Faustina (SIL OFL 1.1) · Montserrat (SIL OFL 1.1) · IBM Plex Sans Condensed (SIL OFL 1.1)
Sandbox