Em poucas palavras
As duas primeiras páginas de uma reportagem de viagem numa revista pequena, com uma faixa colorida e uma imagem. Mostra como um texto simples com alguns títulos vira uma página diagramada com as cores.
O que você vai compor
As páginas de abertura de uma reportagem de viagem em Caderno de campo, uma revista pequena. A página 1 é uma abertura em página ímpar: uma fotografia de salinas e de uma duna ao anoitecer nos 58% de cima da página, o título em Young Serif de 54 pt e, embaixo, duas colunas justificadas que começam o texto com uma abertura em negrito. A página 2, no verso, continua sob um cabeço em maiúsculas espacejadas e termina com um sinal de fim e um colofão. O design inteiro cabe numa função de configuração e numa paleta de seis cores. O título vem do título de nível 1, e a linha fina, a autora e a data vêm do front matter da string Markdown, por isso o mesmo pen compõe qualquer matéria cujo título caiba em duas linhas; só a fotografia é exclusiva desta.
Esta receita responde a
- Como evito que títulos, negritos e marcadores de lista saiam em azul?
- Como configuro uma página de livro: formato refilado, margens interna e externa espelhadas, duas colunas e medianiz?
- Como faço para transformar uma string Markdown em páginas compostas e desenhar uma delas em um canvas?
A resposta curta
const config = () => ({
locale: t({ en: 'en-us', es: 'es', pt: 'pt', fr: 'fr', de: 'de', it: 'it' }), // the hyphenation
colorPalette: colorPalette(),
page: { // mirror: left is the inner margin and right the outer one; versos swap them
width: mm(PAGE.width), height: mm(PAGE.height),
margins: { top: mm(MARGIN.top), bottom: mm(MARGIN.bottom), left: mm(MARGIN.inner),
right: mm(MARGIN.outer), mirror: true },
},
// 'double' is the default, stated so that the whole page setup reads in one place
layout: { layoutType: 'double', gutterWidth: mm(6) },
bodyText: { // justified, hyphenated and broken by paragraph: all on by default
fontFamily: 'Newsreader', // one family name: there is no fallback chain
fontSize: pt(9.5), lineHeight: pt(LEAD), color: col('ink'),
boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
firstLineIndent: mm(4), indentAfterHeading: false,
// Optional, for 70 mm columns: word spaces from 0.8 to 1.8 × the normal one, and runts
// tightened by at most 4 thousandths of an em, so the grey of the text stays even.
minWordSpacing: 0.8, maxWordSpacing: 1.8, maxRuntTracking: 4,
},
headings: {
fontFamily: 'Young Serif', fontWeight: 400, color: col('band'), // it has one weight
levels: [
// span: 'page' opens the H1 on a new page, across both columns. Parity 'odd' puts the
// next article pasted in on a recto, with a blank verso only when one is needed.
{ level: 1, span: 'page', breakBefore: { enabled: true, parity: 'odd' },
advancedDesign: opener() },
// A line of margin and a line and a half of head: 2.5 lines, which snapToGrid (on by
// default) rounds up to 3, so the text below lands back on the grid.
{ level: 2, fontSize: pt(13), lineHeight: pt(1.5 * LEAD), marginTop: pt(LEAD),
marginBottom: pt(0) },
],
},
unorderedLists: { color: col('ink'), fontWeight: 400, bulletChar: '–',
marginTop: pt(0), marginBottom: pt(0) },
calloutStyles: [colophon()],
header: header(),
footer: footer(),
// The magazine's name is its masthead, the same on every story (#849).
checks: { contentInConfig: { allow: [MAGAZINE] } },
});
Ingredientes
- Funcionalidades
- Metadados do documentoPaleta de cores semânticaCabeços e fóliosPáginas em um canvasAberturas desenhadasFaixa de capítulo em largura totalImagens nos designs de páginaAncoragem de elementos de designCabeços por tipo de páginaFontes antes da diagramaçãoFormato da páginaMargens espelhadasUma ou duas colunasTipografia do textoNegrito, itálico e suas coresAmostras de corHifenização e idioma do documentoListas com marcadores e de verificaçãoBoxesQuebras de linha nos títulos
- Também usa
- Figuras e tabelas como recursos
- Tipografia
- Newsreader, Young Serif, Inter Tight (SIL OFL 1.1)
- Materiais
salt-road-1440.jpg- As salinas e a duna ao anoitecer da abertura, uma fotografia (Generated With Diffusion Models, original)
Preparo
#1 · Todas as fontes, antes da primeira composição
const FONTS = {
Newsreader: ['400', '400i', '700'], // text
'Young Serif': ['400'], // display: it ships one weight, so the headings ask for 400
'Inter Tight': ['400', '600'], // labels: kicker, byline, running heads, colophon
};
O Postext mede o texto com as fontes que o navegador tem na hora de compor, de modo que uma composição que rodasse antes de as fontes chegarem manteria as quebras de linha de uma fonte substituta. buildDocumentWithFonts carrega, antes da primeira composição, todas as fontes que a configuração cita e as de FONTS; kitFonts(FONTS) entrega os arquivos do Fontsource, os mesmos que um PDF incorporaria. Depois ele percorre as fontes que as páginas usam, carrega as que ainda faltam e compõe de novo. Uma fonte que o Fontsource não tem fica na substituta e aparece em doc.contentWarnings como fontFallback. O negrito e o itálico de uma fonte de texto só carregam quando a família os tem.
#2 · Dê nome às cores e aponte para os nomes
const palette = {
ink: '#1b1e23', // text: a cool near-black, never #000
band: '#2b3a67', // the one accent (an indigo): the folios, the subheads, the end mark
sand: '#e9dcc0', // the kicker, the title and the byline
salt: '#f7f4ee', // the standfirst
rule: '#d6d3cc', // the hairline over the colophon
muted: '#66686e', // running heads and the colophon
};
// Each colour carries its palette id and its hex. The design objects below are functions
// that config() calls, so col() copies the hex out of `palette` on every build: one edit
// to `palette` reaches the text, the folios and the drop folio alike.
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 (headings, bold, italic, bullets, the default running head) link
// to 'main-color': point it at the accent, so nothing left unset prints blue.
{ id: 'main-color', name: 'defaults', value: { hex: palette.band, model: 'hex' } },
];
Toda cor da configuração é col('id'), um identificador da paleta com o hexadecimal ao lado. bodyText.boldColor, italicColor, referenceColor e unorderedLists.color apontam para ink, e headings.color aponta para a cor de destaque. Os padrões do motor para títulos, negrito, itálico e marcadores estão ligados a main-color, e esta paleta aponta essa entrada para a cor de destaque, de modo que qualquer um deles que você deixar de fora sai anil, e não azul. Os objetos de design são funções que config() chama a cada composição, e col() copia de palette o hexadecimal vigente toda vez, por isso uma só mudança em palette chega do mesmo jeito ao texto, aos fólios e à abertura. O sinal de fim é uma amostra de cor em linha que aponta para band, por isso uma troca de cor também chega a ele. O cabeço padrão também está ligado a main-color, de modo que sairia na cor de destaque até você substituí-lo (passo 5).
#3 · Uma fotografia cortada no seu quadro
// A JPEG in assets/, cut to PAGE.width × BAND (180 × 140 mm) and declared at its pixels, so at
// full width it fills the band exactly. A deeper band needs a picture cut to the new frame.
const landscape = { id: 'landscape', typeId: 'figure', kind: 'bitmap', createdAt: 0,
updatedAt: 0, bitmap: { fileId: 'salt-road-1440.jpg', format: 'jpeg', width: 1440,
height: 1120 },
altText: 'Salt pans at dusk, a dune with a cairn of white stones on its crest, and a line of '
+ 'footprints crossing the pans towards it.' };
As salinas, a duna e o marco de pedras são uma fotografia gerada com modelos de difusão, feita ao anoitecer para que o título claro se leia contra um céu escuro. O JPEG está cortado no quadro da faixa, PAGE.width × BAND milímetros, e o recurso declara seus pixels, 1440 × 1120, de modo que na largura inteira a imagem preenche a faixa exatamente. Uma faixa mais alta pede uma imagem cortada no novo quadro. A abertura a mostra por meio de um elemento de imagem que indica o recurso pelo identificador.
#4 · O frontmatter escreve a abertura
const BAND = 140; // mm from the top edge: the band holds the top 58% of the page
const TITLE_W = 130; // mm: room for two lines of the title; a third would push the byline
// down onto the pale salt pans: keep titles short
const DECK_W = 104; // mm: the standfirst stops short of the dune and its cairn
const MAGAZINE = t({ en: 'Field notes', es: 'Cuaderno de campo', pt: 'Caderno de campo',
fr: 'Carnet de terrain', de: 'Unterwegs', it: 'Quaderno di campo' });
const label = { fontFamily: 'Inter Tight', fontSize: pt(7.5), fontWeight: 600,
letterSpacing: pt(1.4), textTransform: 'uppercase' };
const below = (id, y, width) => ({ anchor: { to: `#${id}`, edge: 'below' },
offset: { y: mm(y) }, ...(width && { size: { width: mm(width) } }) });
const opener = () => ({
enabled: true,
minHeight: mm(BAND - MARGIN.top + 5), // from the top margin to the band's foot, plus 5 mm
slot: {
elements: [
// The photograph is PAGE.width × BAND (see art): at full width it fills the band.
{ kind: 'image', id: 'art', resourceId: 'landscape',
placement: { anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill' } } },
{ kind: 'text', id: 'kicker', content: MAGAZINE, ...label, color: col('sand'),
placement: { anchor: { to: 'page', edge: 'top-left' }, // recto: inner on the left
offset: { x: mm(MARGIN.inner), y: mm(20) } } },
// {titleText} is the H1; {subtitle}, {author} and {publishDate} are frontmatter. A bare
// lineHeight multiplies the text's size: 1 sets the title solid. Both texts wrap.
{ kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Young Serif',
fontSize: pt(54), lineHeight: 1, color: col('sand'), align: 'left',
placement: below('kicker', 3, TITLE_W) },
{ kind: 'text', id: 'deck', content: '{subtitle}', fontFamily: 'Newsreader',
fontSize: pt(12), lineHeight: 1.3, italic: true, color: col('salt'), align: 'left',
placement: below('title', 5, DECK_W) },
{ kind: 'text', id: 'byline', ...label, color: col('sand'),
content: t({ en: 'By {author} · {publishDate}',
es: 'Por {author} · {publishDate}', pt: 'Por {author} · {publishDate}',
fr: 'Par {author} · {publishDate}', de: 'Von {author} · {publishDate}', it: 'Di {author} · {publishDate}' }),
placement: below('deck', 4.5) },
],
},
});
O título de nível 1 ocupa as duas colunas, e sua abertura é um espaço de design com elementos: a fotografia até a sangria e quatro textos encadeados um abaixo do outro. Um título mais longo empurra a linha fina e a assinatura para baixo em vez de se sobrepor a elas, mas a partir da terceira linha a assinatura cai sobre as salinas claras. {titleText} é o texto do título; {subtitle}, {author} e {publishDate} são campos do front matter. A \\ no título quebra a linha onde você a puser (quebras de linha em títulos). minHeight conta a partir da margem superior, por isso a altura reservada termina 5 mm abaixo da faixa.
#5 · Cabeços no lugar do azul padrão
const HEAD = 12; // mm: the running heads from the top edge, the drop folio from the foot
const GAP = 3; // mm between a folio and its label, however many digits the folio has
const head = (id, content, parity, placement, color = col('muted')) => ({
kind: 'text', id, content, parity, pages: 'body', ...label, color, placement,
});
const outer = (edge, x) => ({ anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(HEAD) } });
const beside = (id, edge, x) => ({ anchor: { to: `#${id}`, edge }, offset: { x: mm(x) } });
const header = () => ({
elements: [ // folios on the outer margin's edge; each label hangs off its folio
head('verso-folio', '{pageNumber}', 'even', outer('top-left', MARGIN.outer), col('band')),
head('verso-title', '{title}', 'even', beside('verso-folio', 'right-of', GAP)),
head('recto-folio', '{pageNumber}', 'odd', outer('top-right', -MARGIN.outer), col('band')),
head('recto-title', MAGAZINE, 'odd', beside('recto-folio', 'left-of', -GAP)),
],
});
const footer = () => ({
elements: [{ kind: 'text', id: 'drop-folio', content: '{pageNumber}', pages: 'opener',
...label, color: col('band'),
placement: { anchor: { to: 'page', edge: 'bottom' }, offset: { y: mm(-HEAD) } } }],
});
Deixe header de fora e volta o padrão do motor: Open Sans sobre um fio de largura inteira, em todas as páginas. Aqui cada fólio é ancorado à página física e filtrado pela paridade, de modo que fica sempre na margem externa. O texto que o acompanha é ancorado ao fólio, a GAP milímetros, com right-of ou left-of, e um fólio de três ou quatro algarismos empurra o texto em vez de esbarrar nele. pages: 'body' deixa os quatro elementos fora da abertura. O rodapé tem um único fólio, o da abertura, e como footer está definido, as páginas de texto perdem o fólio centralizado padrão.
#6 · Componha com uma configuração nova e pinte
await loadImage(landscape.bitmap.fileId, asset(landscape.bitmap.fileId));
const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
// showPages paints each page with renderPageToCanvas(page, doc, canvas, { scale }).
showPages(doc, {
title: t({ en: 'From a Markdown string to a designed page',
es: 'De una cadena Markdown a una página diseñada',
pt: 'De uma string Markdown a uma página diagramada',
fr: 'D’une chaîne Markdown à une page mise en forme',
de: 'Von einem Markdown-String zur gestalteten Seite',
it: 'Da una stringa Markdown a una pagina progettata' }),
});
config() é uma função para que cada composição leia a paleta como ela está: chama de novo as funções de design do passo 2. Um único objeto de configuração alterado no lugar também serviria: desde o postext 1.25 o motor vê a mudança na composição seguinte. buildDocumentWithFonts recebe o conteúdo, essa configuração e as opções de fontes do kit, e devolve o documento. showPages dispõe as páginas como ficam num livro encadernado, com a página 1 sozinha à direita, e pinta cada uma com renderPageToCanvas.
A receita completa
// ═══ Postext Cookbook · Nº 012 · From a Markdown string to a designed page ══════════
// https://postext.dev/en/cookbook/first-page-from-markdown
// Code: MIT · Text: original (CC BY 4.0) · Photo: diffusion models
// Fonts: Newsreader, Young Serif, Inter Tight (SIL OFL 1.1) · Needs postext ≥ 1.34.0
//
// This pen sets a Markdown string with a frontmatter block on two magazine pages and paints
// them on canvases. The whole design is in config(); swap config() for {} in the build
// below to see the engine's defaults.
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
const LANG = 'pt'; // @lang: the sample document's language ('en' | 'es' | 'pt' | 'fr' | 'de' | 'it')
const RECIPE = 'first-page-from-markdown';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// Every setting that shapes the pages is in this part, from PAGE down to config().
const PAGE = { width: 180, height: 240 }; // mm: a 3:4 magazine page
const MARGIN = { top: 22, bottom: 22, inner: 20, outer: 14 }; // mm; inner is the spine side
const LEAD = 13.5; // pt: the body leading, the grid every vertical space steps on
// #region palette: six named colours; every colour in the config links to one of them
const palette = {
ink: '#1b1e23', // text: a cool near-black, never #000
band: '#2b3a67', // the one accent (an indigo): the folios, the subheads, the end mark
sand: '#e9dcc0', // the kicker, the title and the byline
salt: '#f7f4ee', // the standfirst
rule: '#d6d3cc', // the hairline over the colophon
muted: '#66686e', // running heads and the colophon
};
// Each colour carries its palette id and its hex. The design objects below are functions
// that config() calls, so col() copies the hex out of `palette` on every build: one edit
// to `palette` reaches the text, the folios and the drop folio alike.
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 (headings, bold, italic, bullets, the default running head) link
// to 'main-color': point it at the accent, so nothing left unset prints blue.
{ id: 'main-color', name: 'defaults', value: { hex: palette.band, model: 'hex' } },
];
// #endregion
// #region art: a photograph of the salt pans and the dunes at Sorra, cut for a page × band frame
// A JPEG in assets/, cut to PAGE.width × BAND (180 × 140 mm) and declared at its pixels, so at
// full width it fills the band exactly. A deeper band needs a picture cut to the new frame.
const landscape = { id: 'landscape', typeId: 'figure', kind: 'bitmap', createdAt: 0,
updatedAt: 0, bitmap: { fileId: 'salt-road-1440.jpg', format: 'jpeg', width: 1440,
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
#Veja o que a configuração substitui
Componha com uma configuração vazia e o mesmo Markdown sai numa página de 17 × 24 cm em EB Garamond de 8 pt, com títulos azuis em Open Sans e um cabeço azul sobre um fio; o motor carrega também essas duas famílias, porque a configuração padrão as cita.
-const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
+const doc = await buildDocumentWithFonts({ markdown, resources }, {}, kitFonts(FONTS));#Troque a cor da página inteira
Mude a cor de destaque e a execução seguinte pinta na nova cor os fólios, os intertítulos e o sinal de fim, porque col() copia o novo hexadecimal ao lado do identificador cada vez que config() roda. A fotografia mantém as próprias cores.
- band: '#2b3a67', // the one accent (an indigo): the folios, the subheads, the end mark
+ band: '#3f5b3a', // the one accent (a pine green): the folios, the subheads, the end mark#Pinte uma página no seu próprio canvas
renderPageToCanvas dimensiona o canvas com o tamanho da página em pixels na resolução do documento (300 dpi por padrão) vezes scale, por isso scale: 0.5 pinta a cerca de 150 dpi, e o CSS decide o tamanho com que aparece na tela.
-showPages(doc, {
- title: t({ en: 'From a Markdown string to a designed page',
- es: 'De una cadena Markdown a una página diseñada',
- pt: 'De uma string Markdown a uma página diagramada',
- fr: 'D’une chaîne Markdown à une page mise en forme',
- de: 'Von einem Markdown-String zur gestalteten Seite',
- it: 'Da una stringa Markdown a una pagina progettata' }),
-});
+const canvas = document.body.appendChild(document.createElement('canvas'));
+renderPageToCanvas(doc.pages[0], doc, canvas, { scale: 0.5 });Erros comuns
- A Young Serif tem um peso só. Os títulos saem em negrito por padrão, de modo que aqui
headings.fontWeight: 400é obrigatório: sem ele, os títulos pedem uma Young Serif negrito que o Fontsource não tem, o navegador engrossa a regular edoc.contentWarningsregistra a fonte comofontFallback.
Créditos
- Receita
- Ignacio Ferro
- Texto
- Texto original, CC BY 4.0
- Imagens
- As salinas e a duna ao anoitecer da abertura, uma fotografia · Generated With Diffusion Models · original
- Fontes
- Newsreader (SIL OFL 1.1) · Young Serif (SIL OFL 1.1) · Inter Tight (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)


