Em poucas palavras
O relatório anual de uma pequena cooperativa de energia, em duas colunas. Mostra como fazer as duas colunas de texto terminarem exatamente na mesma altura.
O que você vai compor
O relatório anual de 2025 da Tidewell Community Energy, uma cooperativa inventada com duas turbinas eólicas, uma usina solar e painéis em 21 telhados. Cinco páginas de 210 × 280 mm. Na capa, a produção eólica e a solar do ano correm como duas fitas sob um “2025” de 150 pt. A carta da presidente, o relatório de operações e as contas da tesouraria vêm em seguida, em duas colunas justificadas de Brygada 1918 numa grade de 50 linhas. As colunas cheias terminam na última linha da grade, e as curtas terminam niveladas com a vizinha. Um boxe com três números-chave atravessa a página da presidente, com a carta cortada em nível acima dele, e uma nota sobre medição flutua para o alto da página 4. Na página final, as duas colunas param na mesma linha, acima da demonstração de resultados. Um atributo de paleta pinta de verde-azulado as páginas de operações e de vermelho-tijolo a página de finanças.
Esta receita responde a
- Como deixo as colunas alinhadas no pé e a última página equilibrada (justificação vertical)?
- Como coloco um boxe atravessando as duas colunas no meio da página, como um painel “em números” com três blocos?
- Como levo um boxe para o alto ou o pé da página enquanto o texto continua correndo?
- Como faço uma tabela com linhas de cabeçalho, células mescladas, larguras de coluna e alinhamento por célula?
- Como divido um livro em partes ou seções, cada uma com sua cor e sua página divisória?
A resposta curta
// The text block is LINES lines of LEAD deep (MARGIN.bottom is derived from them) and every
// heading takes whole lines, so a column the break rules leave short is short by whole lines.
// Balancing (on by default) stretches it back to its foot with its levers, in this order: a
// box that closes the column moves down to it; a picture with a safe area grows; lines above
// the headings, two each at most (maxLinesBeforeLoose); one line where a list ends; one under
// a display formula or a box, then under a float at the column head; a paragraph set one line
// longer and looser, with up to maxTracking of tracking; last, the lines a heading may still
// take, up to maxLinesPerHeading. A closing band whose columns differ by more than a line is
// cut level instead (trailing), and so is the band a page-wide box leaves when it has to move
// on to the next page (beforeSpan).
const balancing = { maxLinesPerHeading: 1 }; // one line per heading; the next lever takes more
const flowText = { // justification, hyphenation and Knuth–Plass stay at their defaults (on)
fontFamily: 'Brygada 1918', fontSize: pt(9.4), lineHeight: pt(LEAD),
firstLineIndent: mm(4), indentAfterHeading: false,
minWordSpacing: 0.7, maxWordSpacing: 1.8, // word spaces 0.7–1.8 of normal (defaults 0.6–2)
};
const onGrid = { lineHeight: pt(LEAD), marginTop: pt(LEAD), marginBottom: pt(0) }; // one line
// hook-up: headings: { balancing, levels: [..., { level: 2, ...onGrid }] }, bodyText: flowText
Ingredientes
- Funcionalidades
- Equilíbrio de colunasBoxes na largura da páginaColunas num boxe ou no textoBoxes flutuantesCores por parteViúvas, órfãs e linhas curtasQuebra de linha ótima (Knuth–Plass)Posicionamento de figurasPaleta de cores semânticaBoxesTabelas a partir de dadosEstilos de tabela com nomeEstilo de tabelaPreenchimento de célulasEstilo de legendaTipos de recurso personalizadosFiguras e tabelas como recursosCapas, folhas de rosto e colofões
- Também usa
- Citações que posicionam as figurasAtributos de títuloEstilos de títuloFiguras exatamente aquiFaixa de capítulo em largura totalAberturas desenhadasEstilos de parágrafoPáginas de abertura de parteCabeços por seçãoQuebras de linha nos títulos
- Tipografia
- Brygada 1918, Epilogue, Spline Sans Mono, Mrs Saint Delafield (SIL OFL 1.1)
- Materiais
- Nenhum: todas as imagens são desenhadas em código
Preparo
#1 · Mantenha cada linha na grade e deixe as alavancas fecharem os vãos
O código é a resposta curta logo acima. A mancha tem exatamente 50 linhas de 13,4 pt de altura, e a margem inferior (21,6 mm) é calculada a partir dessa altura. Um intertítulo ocupa uma linha da grade acima dele e uma para si, por isso uma coluna que termina curta fica curta em linhas inteiras, e linhas inteiras são o que o balanceamento de colunas acrescenta. Na página 3, o parágrafo de três linhas sobre a chuva de granizo vai inteiro para a página 4 por causa de avoidOrphans, o nome que o Postext dá à regra que impede a última linha de um parágrafo de ficar sozinha no alto de uma coluna, e a coluna direita termina duas linhas curta. maxLinesPerHeading: 1 dá uma dessas linhas ao espaço acima de The Saltings and the roofs e deixa a outra para a alavanca seguinte, que a acrescenta depois da lista de telhados. Por padrão, um título recebe até duas linhas antes de as alavancas seguintes serem tentadas (maxLinesBeforeLoose), e até quatro quando elas não têm mais nada a dar, de modo que as duas linhas iriam para cima do título.
#2 · Corte o texto em nível acima de um boxe que atravessa a página
// In the Markdown: :::callout{type="figures" span="page"} around :::columns{count=3 breaks="3,5"},
// each number a :::paragraphs{style="figure"} of **8.47 GWh**, then its line of text.
const figures = { id: 'figures', background: col('ink'), columnGap: mm(GUTTER),
padding: { top: mm(5), right: mm(5), bottom: mm(5), left: mm(5) },
marginTop: pt(LEAD), marginBottom: pt(LEAD), titleStyle: { ...boxTitle, color: col('sun') },
body: { fontFamily: 'Epilogue', fontSize: pt(9), lineHeight: pt(12), color: col('paper'),
...boxText } };
const bigNumber = { id: 'figure', fontFamily: 'Epilogue', fontSize: pt(26), lineHeight: pt(31),
color: col('paper'), boldColor: col('sun'), ...boxText };
Um boxe com span="page" divide uma página de duas colunas em faixas. Na página 2, a carta da presidente para em oito linhas em cada coluna acima do boxe e continua nas duas colunas abaixo dele. Dentro do boxe, :::columns{count=3 breaks="3,5"} abre a segunda e a terceira colunas no segundo e no terceiro número (o terceiro e o quinto blocos do grupo), em vez de cortar onde as colunas ficariam mais niveladas. O estilo de parágrafo figure compõe esses números em 26 pt, e o boldColor os imprime em amarelo.
#3 · Faça um boxe flutuar para o alto da página seguinte
// In the Markdown: :::callout{type="aside" span="page" placement="top"}. It leaves the flow
// where it stands and takes the head of the next page the flow opens; the text goes on
// filling this one. It has a stripe in the section's colour and no fill. The padding under
// the text drops the floats below the box by a grid line, so they stand clear of it.
const aside = { id: 'aside', backgroundEnabled: false, columnGap: mm(GUTTER),
stripe: { enabled: true, side: 'top', width: pt(2.5), color: col('band') },
padding: { top: mm(3.5), right: pt(0), bottom: mm(3.5), left: pt(0) },
titleStyle: { ...boxTitle, color: col('band') },
body: { fontFamily: 'Epilogue', fontSize: pt(8.6), lineHeight: pt(12.2), color: col('ink'),
...boxText } };
No Markdown, a nota sobre medição vem depois do primeiro parágrafo sobre Harrow Down, na página 3; placement="top" a tira do fluxo e a coloca no alto da página seguinte. O relatório preenche o resto da página 3, e a página 4 abre com o boxe sobre as duas colunas. Abaixo dele, a tabela por local e o gráfico de anel, ambos com position: 'top', encabeçam uma coluna cada, uma linha da grade mais abaixo do que ficariam sem os 3,5 mm de espaçamento interno inferior do boxe.
#4 · Dê a cada seção a sua cor sem página divisória
const palette = {
ink: '#14202b', // text: a blue-black
band: '#0b5d7a', // sea, overridden by palette="band=#…" on the :::part fences
wind: '#3aa6a0', sun: '#f2b134', coral: '#e2674b', // the data colours of the charts
tint: '#eef3f5', // subtotal rows
rule: '#c9d3d9', // hairlines
muted: '#566370', // captions' notes and the running feet
mist: '#9fb1bd', // small print on the ink cover
paper: '#ffffff',
};
// Every colour is linked to its palette entry, so a :::part recolours it by paletteId.
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' } }));
Com parts: { page: false }, um delimitador como :::part{number="02" title="Operations" palette="band=#1c6e67"} não abre página. Ele dá nome à seção na faixa de abertura e nos rodapés correntes, e troca band em todas as páginas até a parte seguinte. As faixas, os intertítulos, os marcadores, os rótulos das legendas e o fio da nota usam band, por isso as páginas de operações saem em verde-azulado e a de finanças em vermelho-tijolo, enquanto a carta da presidente mantém o azul-mar de base (cores por parte).
#5 · Monte as tabelas a partir dos dados e feche a última página nivelada
const DATA = {
// Output in MWh at the export meter, January to December 2025.
wind: [560, 520, 450, 330, 270, 210, 190, 150, 300, 420, 480, 540], // Harrow Down
sun: [90, 160, 300, 440, 560, 600, 580, 500, 380, 250, 120, 70], // the Saltings + 21 roofs
// The turbines' year, % of the hours of both machines: [label, share, palette colour].
hours: [['generating', 78.0, 'wind'], ['waiting for wind', 16.8, 'rule'], ['bearing repair', 2.6,
'coral'], ['servicing and grid', 1.8, 'sun'], ['stopped for bats', 0.8, 'ink']],
// Output by site in MWh: [site, source, capacity in MW, 2025, 2024].
sites: [['Harrow Down', 'wind', 1.8, 4420, 4560], ['The Saltings', 'solar', 3.2, 3190, 2640],
['21 roofs', 'solar', 0.9, 860, 790]],
// £ thousand, [label, 2025, 2024]; a label alone opens a group, '=' prints the running sum.
accounts: [['Income'], ['Electricity sold under the power purchase agreement', 760, 722],
['Electricity sold to roof hosts', 92, 85], ['Feed-in tariff', 236, 229], ['=Total income'],
['Operating costs'], ['Operation and maintenance', -231, -198],
['Rent, rates and insurance', -158, -151], ['Staff and administration', -121, -112],
['Depreciation', -286, -286], ['=Operating surplus'],
['Interest on the Harrow Down loan', -54, -66], ['Interest on members’ shares at 3.5%', -113,
-107], ['Grants to the Tidewell Fund', -84, -70], ['Corporation tax', -5, -7],
['=Surplus for the year']],
};
const fill = { background: col('tint') }; // totals sit on a tint between two hairlines
const right = (content, extra) => ({ content, align: 'right', ...extra });
const figure = (n, digits = 0) => n.toLocaleString('en-GB', { minimumFractionDigits: digits });
const head = (c, i) => (i ? right(c, { isHeader: true }) : { content: c, isHeader: true });
const siteTable = (rows) => ({ headerRowCount: 1, columnWidths: [3, 1, 1.3, 1.3], rows: [
['Site', 'MW', '2025', '2024'].map(head),
...rows.map(([site, source, mw, ...n]) => [{ content: `${site} *(${source})*` },
right(figure(mw, 1)), ...n.map((v) => right(figure(v)))]),
[{ content: '**All sites**', ...fill }, ...[2, 3, 4].map((i, k) => right(`**${figure(rows
.reduce((sum, row) => sum + row[i], 0), k ? 0 : 1)}**`, fill))]] }); // the totals, summed
// Accounting style: losses in brackets, and gains followed by a no-break space, as wide as a
// bracket in a monospaced face, so the digits line up.
const pad = '\u00a0';
const money = (n) => (n < 0 ? `(${figure(-n)})` : `${figure(n)}${pad}`);
function statement(rows) {
const sum = [0, 0];
const cells = [['£ thousand', `2025${pad}`, `2024${pad}`].map(head)];
for (const [label, ...years] of rows) {
years.forEach((n, i) => { sum[i] += n; });
const sub = label.startsWith('='); // a subtotal: the running sum, in bold
cells.push(sub ? [{ content: `**${label.slice(1)}**`, ...fill },
...sum.map((n) => right(`**${money(n)}**`, fill))]
: [{ content: years.length ? label : `*${label}*` }, // a label alone heads a group
...[0, 1].map((i) => right(years.length ? money(years[i]) : ''))]);
}
// mergeCells writes the cells a spanning group head hides (gotcha: merged-cells-hiddenby)
return cells.reduce((model, row, r) => (r && !row[1].content ? mergeCells(model,
{ start: { row: r, col: 0 }, end: { row: r, col: 2 } }) : model),
{ rows: cells, headerRowCount: 1, columnWidths: [5, 1, 1] });
}
statement() transforma DATA.accounts na demonstração de resultados, linha a linha. Um rótulo que começa com = imprime em negrito, sobre o tom claro, a soma acumulada de cada ano; os custos são negativos nos dados, por isso o Operating surplus sai dessa soma sem nenhum total digitado à mão. Um rótulo sem números, Income ou Operating costs, vira uma única célula em itálico na largura da tabela, mesclada com mergeCells, que também escreve as células de preenchimento de que uma mesclagem precisa. Na página 5, a demonstração flutua na largura do pé da página, sob o relatório da tesoureira, que fecha o documento. Sem equilíbrio, as colunas chegariam a 12 linhas na esquerda e 9 na direita; o corte final deixa as duas em 11, e a alavanca de títulos acrescenta acima de Cash and reserves a linha que ainda falta à coluna direita.
A receita completa
// ═══ Postext Cookbook · Nº 037 · Annual report with flush columns ═══════════════════════
// https://postext.dev/en/cookbook/annual-report-flush-columns
// Code: MIT · Text: original (CC BY 4.0) · Art: drawn in code · Typefaces: SIL OFL 1.1
// Fonts: Brygada 1918, Epilogue, Spline Sans Mono, Mrs Saint Delafield · Needs postext ≥ 1.28.0
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, mergeCells, inlineSvgFonts,
} from 'https://esm.sh/postext';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'annual-report-flush-columns';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: 'band' is the first section's colour; each later :::part brings its own
const palette = {
ink: '#14202b', // text: a blue-black
band: '#0b5d7a', // sea, overridden by palette="band=#…" on the :::part fences
wind: '#3aa6a0', sun: '#f2b134', coral: '#e2674b', // the data colours of the charts
tint: '#eef3f5', // subtotal rows
rule: '#c9d3d9', // hairlines
muted: '#566370', // captions' notes and the running feet
mist: '#9fb1bd', // small print on the ink cover
paper: '#ffffff',
};
// Every colour is linked to its palette entry, so a :::part recolours it by paletteId.
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' } }));
// #endregion
const TRIM = { width: 210, height: 280 };
const LEAD = 13.4; // body leading in pt: one line of the baseline grid
const LINES = 50; // grid lines in a full column
const MARGIN = { top: 22, inner: 18, outer: 16 }; // mm, mirrored
MARGIN.bottom = TRIM.height - MARGIN.top - (LINES * LEAD * 25.4) / 72; // 21.6 mm: 50 lines exactly
const GUTTER = 7; // mm between the columns, and between the columns inside the boxes
const mono = { fontFamily: 'Spline Sans Mono', fontWeight: 500, textTransform: 'uppercase' };
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const text = (id, content, look, placement) => ({ kind: 'text', id, content, placement,
align: 'left', ...look });
// #region answer: flush columns: whole grid lines everywhere, and the balancing levers
// The text block is LINES lines of LEAD deep (MARGIN.bottom is derived from them) and every
// heading takes whole lines, so a column the break rules leave short is short by whole lines.
// Balancing (on by default) stretches it back to its foot with its levers, in this order: a
// box that closes the column moves down to it; a picture with a safe area grows; lines above
// the headings, two each at most (maxLinesBeforeLoose); one line where a list ends; one under
// a display formula or a box, then under a float at the column head; a paragraph set one line
// longer and looser, with up to maxTracking of tracking; last, the lines a heading may still
// take, up to maxLinesPerHeading. A closing band whose columns differ by more than a line is
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
#Deixe os títulos ficarem com todo o vão
As duas linhas livres da página 3 vão então para cima de The Saltings and the roofs, e nenhuma depois da lista.
-const balancing = { maxLinesPerHeading: 1 }; // one line per heading; the next lever takes more
+const balancing = {}; // the default: two lines above a heading, then the other levers#Desligue o balanceamento
A coluna direita da página 3 termina então duas linhas curta. Na página 5, a coluna esquerda chega a 12 linhas e a direita a 9, e a demonstração começa uma linha mais abaixo.
-const balancing = { maxLinesPerHeading: 1 }; // one line per heading; the next lever takes more
+const balancing = { enabled: false };Erros comuns
Erro comum
avoidWidows cuida do pé da coluna, avoidOrphans do alto
O Postext dá nomes próprios às duas linhas isoladas: avoidWidows (widowMinLines, widowPenalty) impede que a primeira linha de um parágrafo fique sozinha no pé de uma coluna, e avoidOrphans (orphanMinLines, orphanPenalty) impede que a última fique sozinha no alto da seguinte. Muitos manuais de estilo usam os dois nomes ao contrário, então escolha a configuração pelo lugar onde ela age. As duas vêm ativadas, exceto numa grade de caracteres (cjk.grid): ali avoidWidows vem desativada, e avoidOrphans também na região do Japão, para que a página contenha as linhas que a grade conta (desde o postext 1.28). Elas funcionam como penalidades: a diagramação compara cada uma com as linhas vazias que obedecê-la deixaria. Viúvas, órfãs e linhas curtas →
- Quando as colunas de uma página final diferem em uma linha, elas ficam como estão, com a esquerda uma linha mais longa, como um compositor as deixaria; o corte final só age numa diferença de duas linhas ou mais. Para terminar as duas juntas, alongue ou encurte o texto em uma linha.
- A demonstração de resultados põe os custos entre parênteses. Para alinhar com eles os números positivos, o código termina cada número positivo com um espaço não separável, que numa fonte monoespaçada tem a largura do parêntese de fechamento; uma célula de tabela mantém esse espaço no fim do texto.
Créditos
- Receita
- Ignacio Ferro
- Texto
- Texto original, CC BY 4.0
- Fontes
- Brygada 1918 (SIL OFL 1.1) · Epilogue (SIL OFL 1.1) · Spline Sans Mono (SIL OFL 1.1) · Mrs Saint Delafield (SIL OFL 1.1)
- Código
- MIT, como o Postext
Editar este texto ↗ (abre em uma nova aba)Pasta da receita no GitHub ↗ (abre em uma nova aba)


