Em poucas palavras
Um guia de reciclagem de quatro páginas feito por uma prefeitura. Mostra como criar um PDF que os leitores de tela conseguem seguir, com descrições das imagens e tabelas que eles leem em voz alta.
O que você vai compor
Reciclar en el barrio é o guia de reciclagem de uma prefeitura espanhola inventada: quatro páginas A4 para ler na tela ou imprimir em casa. A capa, azul-marinho, mostra as cinco lixeiras de rua sobre um meio-fio amarelo. A página 2 reúne o sumário e três boxes ao lado de uma carta da vereadora; as páginas 3 e 4 trazem as duas seções, em duas colunas em bandeira de Atkinson Hyperlegible Next. O código exporta um PDF marcado que passa nas verificações PDF/UA-1 do veraPDF, com títulos, listas, boxes e tabelas na ordem de leitura, texto alternativo na figura e células de cabeçalho nas duas tabelas. O arquivo declara título e idioma (es), e os marcadores e as linhas do sumário levam às páginas. As tags não se imprimem, por isso o código as desenha sobre a página 3 da visualização, a que aparece aqui, com cada bloco marcado numa caixa numerada e identificada pela tag. O PDF baixado não tem essa sobreposição.
Esta receita responde a
- Como gero um PDF acessível (com tags, PDF/UA) com texto alternativo e idioma do documento?
- Como faço os rótulos “Figura” e “Tabela” saírem no idioma do meu documento?
- Como acrescento um sumário que se atualiza sozinho (pontilhados, números de página, autores, linhas de parte)?
- Como faço para exportar um PDF de verdade no navegador, com as fontes incorporadas?
A resposta curta
// renderToPdf writes a tagged PDF by default: the tag tree follows the headings, paragraphs,
// lists and boxes of the Markdown. Pictures and tables carry their own accessible text here.
const table = (id, tsv, columnWidths, caption, altText) => ({ id, typeId: 'table', kind: 'table',
caption, altText, createdAt: 0, updatedAt: 0, // altText → the Table's /Summary
placement: { position: 'here' }, // set under the sentence that cites it
table: { model: { headerRowCount: 1, columnWidths, // row 0: TH cells, scope Column
rows: parseTSV(tsv).rows.map((row) => row.map(({ content }, c) => ({ content: cell(content),
...(c === 0 && { isHeader: true }) }))) } } }); // column 0: TH cells, scope Row
const resources = () => [
{ id: 'contenedores', typeId: 'figure', kind: 'svg', placement: { position: 'here' },
svg: { fileId: 'contenedores.svg', width: FIGURE[0] * PX, height: FIGURE[1] * PX },
caption: 'Una isla del barrio: de izquierda a derecha, amarillo, azul, verde, marrón y gris.',
altText: 'Cinco contenedores en fila: amarillo con una botella de plástico, azul con una caja '
+ 'de cartón, verde con una botella de vidrio, marrón con un corazón de manzana y gris con '
+ 'una bolsa de basura cerrada.', createdAt: 0, updatedAt: 0 }, // → the Figure's /Alt
table('dudas', dudas, [3, 2], 'Los residuos que más dudas dan.',
'Once residuos y el contenedor de cada uno.'),
table('horarios', horarios, [2.2, 4, 1.4], 'Días y horas de recogida.',
'Qué días y desde qué hora se vacía cada contenedor.'),
{ id: 'calle', typeId: 'figure', kind: 'svg', createdAt: 0, updatedAt: 0, // the cover's row:
svg: { fileId: 'calle.svg', width: STREET[0] * PX, height: STREET[1] * PX } }, // an artifact
];
const exportPdf = (doc) => renderToPdf(doc, { fontProvider: fontsourceProvider,
resourceBytes: imageBytes }); // accessible and outlines default to true
Ingredientes
- Funcionalidades
- PDF acessível com tagsSumárioExportação para PDFMarcadores do PDFFigura e Tabela no seu idiomaTabelas a partir de dadosFiguras exatamente aquiAmostras de corCitações que posicionam as figurasMetadados do documentoEstilos de títuloCapítulos sem númeroAberturas desenhadasFaixa de capítulo em largura totalCapas, folhas de rosto e colofõesImagens nos designs de páginaBoxesFontes antes da diagramaçãoPáginas em um canvas
- Também usa
- Atributos de títuloTítulos numeradosSair da grade de propósitoQuebras de página e de colunaEstilos de parágrafoFontes incorporadas ao PDFFiguras e tabelas como recursosGeometria por seçãoCabeços por seçãoQuebras de linha nos títulos
- Tipografia
- Atkinson Hyperlegible Next, Atkinson Hyperlegible Mono, Public Sans (SIL OFL 1.1)
- Materiais
- Nenhum: todas as imagens são desenhadas em código
Preparo
#1 · O idioma e o título do documento
locale: LANG, // → /Lang es, and "Figura", "Tabla" in the captions and the citations
// /Title and /Author come from the frontmatter's title and author
O postext-pdf grava o idioma das tags a partir de locale, aqui /Lang es, para que um leitor de tela leia o guia com pronúncia espanhola; sem isso, o arquivo declara en-US. O title e o author do front matter de content.es.md viram o título e o autor do PDF, e o arquivo pede aos visualizadores que mostrem esse título na barra da janela em vez do nome do arquivo. O mesmo locale dá às legendas e às citações seus nomes em espanhol: “Figura 1.1”, “tabla 1.1”. A resposta curta dá à figura e às tabelas seu texto acessível: o altText vira a descrição alternativa da figura (/Alt) e o /Summary de cada tabela, e a primeira linha e a primeira coluna das duas tabelas são marcadas como células de cabeçalho.
#2 · Uma só estrutura de títulos, e uma faixa de capa só com o título
const [BAND, COVER] = [54, 176]; // mm from the trim top to the foot of each band
const band = (height) => ({ kind: 'box', id: 'band', style: { backgroundColor: col('navy') },
placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: mm(height) } } });
const display = (size, hue) => face('Public Sans', 800, size, { lineHeight: 1, color: col(hue) });
const section = { enabled: true, slot: { elements: [band(BAND),
text('number', '{number}', display(64, 'signal'), at('container', 'top-left', 0, 4)),
text('title', '{titleText}', display(28, 'paper'),
{ ...at('#number', 'right-of', 6, 3.5), size: { width: mm(130) } })] } };
// A heading design's text is tagged as the heading, so the cover's band holds only the title.
const cover = { enabled: true, minHeight: mm(COVER - TOP + 24), slot: { elements: [band(COVER),
{ kind: 'box', id: 'kerb', style: { backgroundColor: col('signal') },
placement: { ...at('bleed', 'top-left', 0, COVER), size: { width: 'fill', height: mm(3) } } },
{ kind: 'image', id: 'bins', resourceId: 'calle', // the wheels stand on the kerb
placement: { ...at('#kerb', 'align-bottom', SIDE), size: { width: mm(STREET[0]) } } },
text('title', '{titleText}', display(66, 'paper'),
{ ...at('container', 'top-left', 0, 26), size: { width: mm(STREET[0]) } })] } };
const plain = (id, more) => ({ id, numbered: false, span: 'column', ...more,
advancedDesign: { enabled: false }, fontSize: pt(26), lineHeight: pt(2 * LEAD) });
const headingStyles = [
{ id: 'portada', numbered: false, toc: false, span: 'page', advancedDesign: cover,
layout: { layoutType: 'single' }, footer: { elements: [] } },
plain('indice', { toc: false }), // the contents leave their own heading out
plain('presentacion', { breakBefore: { enabled: false } }), // gotcha: style-inherits-break
];
const headings = { fontFamily: 'Public Sans', fontWeight: 800, color: col('ink'),
levels: [ // parity 'any': a section opens the next page, whichever side it falls on
{ level: 1, numberingTemplate: '{1}', breakBefore: { enabled: true, parity: 'any' },
span: 'page', advancedDesign: section, marginBottom: pt(LEAD) }, // 9.7 mm under the band
{ level: 2, fontWeight: 700, fontSize: pt(13.5), lineHeight: pt(LEAD), marginTop: pt(0),
marginBottom: pt(0) }, // the line above an H2 is the paragraph's, or the resource's, gap
] };
A árvore de tags tira seus elementos H1 e H2 dos títulos do Markdown, e os marcadores do PDF saem da mesma lista; assim, a capa, o sumário, a carta e as duas seções são de nível 1, e os intertítulos, de nível 2. O postext-pdf marca cada elemento de texto do design de um título como parte desse título. Por isso a faixa da capa leva apenas o título, e a linha fina e o nome da prefeitura vão abaixo dela, como parágrafos. As faixas azul-marinho, o meio-fio e a fileira de lixeiras são elementos de design, e o PDF marca caixas e imagens de design como artefatos, de modo que elas não precisam de texto alternativo e o leitor de tela as pula.
#3 · Um sumário com links
const [NUMBER, GAP] = [6, 2.5]; // mm: the number column and the gap before a title
const toc = { levels: [{ level: 1, ...face('Public Sans', 700, 12), numberWidth: mm(NUMBER),
numberGap: mm(GAP), marginTop: pt(LEAD / 2) }, { level: 2, indent: mm(NUMBER + GAP) }],
unnumbered: { indent: mm(NUMBER + GAP) }, leader: { gap: mm(1.5) }, // Presentación: no number
// The page numbers, and the leaders with them, in the text face
pageNumber: { fontFamily: 'Atkinson Hyperlegible Next', fontWeight: 700, width: mm(8) } };
:::toc lista os H1 e os H2 com os números de página que eles imprimem, e no PDF cada uma das onze linhas leva ao alto da página. As citações :ref “figura 1.1” e “tabla 1.1”, na página 3, e “tabla 2.1”, na página 4, levam à figura e às tabelas. Os números de página vão na fonte do texto, Atkinson Hyperlegible Next Bold, e as linhas pontilhadas tomam a fonte dos números, não a Public Sans das entradas.
#4 · A ordem de leitura, desenhada na página
// An opener band's title, then each column from top to bottom; a float is read after the text
// that cites it, wherever it is painted. A paragraph continued in the next column stays one
// element, so its second part keeps its number.
const tagOf = (b) => ({ heading: `H${b.headingLevel ?? 1}`, callout: 'Div', listItem: 'LI',
resource: b.resourceBlock?.kind === 'table' ? 'Table' : 'Figure' })[b.type] ?? 'P';
function readingOrder(page) {
const ids = new Map(); // element → its number
const add = (block, box) => {
const key = block.id.replace(/-cont-\d+$/, ''); // fragments share their block's id
if (!ids.has(key)) ids.set(key, ids.size + 1);
return { n: ids.get(key), tag: tagOf(block), box, cont: key !== block.id };
};
const blocks = page.columns.flatMap((c) => c.blocks);
const title = blocks.find((b) => b.hidden && b.type === 'heading'); // drawn by the band
const flow = blocks.filter((b) => !b.hidden);
for (const float of page.floats ?? []) { // after the last block up to its place in the source
flow.splice(flow.findLastIndex((b) => b.contentIndex <= float.contentIndex) + 1, 0, float);
}
return [...(page.openerBand && title ? [add(title, union(page.openerBand.blocks
.filter((b) => b.kind === 'text')))] : []), ...flow.map((b) => add(b, b.bbox))];
}
Um leitor de tela segue as tags. renderToPdf etiqueta primeiro o título da faixa e depois cada coluna de cima para baixo, e lê um flutuante logo depois do parágrafo que o cita, onde quer que a página o pinte. Esta função repete essa ordem para numerar as caixas da página 3, e a árvore de estrutura do PDF lista os mesmos catorze elementos na mesma ordem. A figura e as duas tabelas ficam no fluxo, com placement: { position: 'here' } e uma linha ::resource, para que quem lê com os olhos também as encontre sob a frase que as cita. O parágrafo sobre o vidro que continua na segunda coluna mantém um só número, 9, porque o PDF marca as duas partes como um único parágrafo.
#5 · Cores escolhidas pelo contraste
const palette = {
ink: '#14243a', // text: 15.6:1 on white
navy: '#173556', // bands: white type on it 12.5:1
signal: '#f2b705', // yellow: only on navy (6.9:1) or as a fill, never as text on white
tint: '#e8eef5', // header cells and boxes: ink on it 13.4:1
rule: '#aebccb', // table rules
muted: '#4a5a6e', // footer and colophon: 7.0:1 on white
paper: '#ffffff',
};
// every colour is linked to its palette entry by id
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// 'main-color' is the id the engine's default styles link to: any default left in them is navy
const colorPalette = [...Object.entries(palette), ['main-color', palette.navy]]
.map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const BIN = { amarillo: '#f2b705', azul: '#1f6fc5', verde: '#2e8b4a', marron: '#8a5a2f',
gris: '#6b7480' }; // the street bins' colours, for the pictograms and the swatches
const NAME = { amarillo: 'Amarillo', azul: 'Azul', verde: 'Verde', marron: 'Marrón', gris: 'Gris',
punto: 'Punto limpio' }; // a table cell never shows a colour alone: its name goes beside it
const cell = (text) => (text in NAME // an unknown colour ('none') draws an empty square
? `:swatch{color="${BIN[text] ?? 'none'}"} ${NAME[text]}` : text);
O PDF/UA-1 não verifica cor, mas a WCAG 2.2 pede 4,5:1 entre o texto e o fundo. A tinta mede 15,6:1 sobre branco, a letra branca 12,5:1 sobre as faixas azul-marinho e o cinza do rodapé 7,0:1. O amarelo dá 1,8:1 sobre branco, por isso só aparece sobre o azul-marinho (6,9:1) e como preenchimento. Os pictogramas seguem o 3:1 que a WCAG pede para gráficos: branco quando atinge essa proporção contra a lixeira, tinta sobre a amarela. cell() escreve o nome de cada lixeira ao lado da amostra de cor e dá ao ecoponto um quadrado vazio, de modo que nenhuma instrução depende de distinguir cores.
A receita completa
// ═══ Postext Cookbook · Nº 039 · Accessible tagged PDF (PDF/UA) ═════════════════════
// https://postext.dev/en/cookbook/accessible-tagged-pdf
// Code: MIT · Text: original (CC BY 4.0) · Pictograms: generated in code (CC BY 4.0)
// Fonts: Atkinson Hyperlegible Next and Mono, Public Sans (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, parseTSV,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
const LANG = 'es'; // @lang: the language of the sample document (this recipe is Spanish only)
const RECIPE = 'accessible-tagged-pdf';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: text colours chosen for their contrast, and never a colour without its name
const palette = {
ink: '#14243a', // text: 15.6:1 on white
navy: '#173556', // bands: white type on it 12.5:1
signal: '#f2b705', // yellow: only on navy (6.9:1) or as a fill, never as text on white
tint: '#e8eef5', // header cells and boxes: ink on it 13.4:1
rule: '#aebccb', // table rules
muted: '#4a5a6e', // footer and colophon: 7.0:1 on white
paper: '#ffffff',
};
// every colour is linked to its palette entry by id
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// 'main-color' is the id the engine's default styles link to: any default left in them is navy
const colorPalette = [...Object.entries(palette), ['main-color', palette.navy]]
.map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const BIN = { amarillo: '#f2b705', azul: '#1f6fc5', verde: '#2e8b4a', marron: '#8a5a2f',
gris: '#6b7480' }; // the street bins' colours, for the pictograms and the swatches
const NAME = { amarillo: 'Amarillo', azul: 'Azul', verde: 'Verde', marron: 'Marrón', gris: 'Gris',
punto: 'Punto limpio' }; // a table cell never shows a colour alone: its name goes beside it
const cell = (text) => (text in NAME // an unknown colour ('none') draws an empty square
? `:swatch{color="${BIN[text] ?? 'none'}"} ${NAME[text]}` : text);
// #endregion
const TRIM = [210, 297]; // A4, the size residents print at home
const [TOP, FOOT, SIDE, LEAD] = [20, 22, 18, 15.5]; // margins in mm, not mirrored; leading in pt
const [PX, FIGURE, STREET] = [12, [83, 30], [174, 44]]; // drawings: px per mm, sizes in mm
const face = (fontFamily, fontWeight, size, more) => ({ fontFamily, fontWeight, fontSize: pt(size),
...more });
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });
const text = (id, content, style, placement) => ({ kind: 'text', id, content, align: 'left',
...style, placement }); // a heading's design wraps its text; the footer clips its own
// #region answer: the alt text and header cells the tags take from the resources
// renderToPdf writes a tagged PDF by default: the tag tree follows the headings, paragraphs,
// lists and boxes of the Markdown. Pictures and tables carry their own accessible text here.
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 a figura flutuar
Tire o posicionamento e a figura 1.1 flutua para o pé da primeira coluna da página 3. O PDF continua lendo-a depois do parágrafo que a cita, de modo que a sobreposição mantém o número 3 e a ordem das tags não muda.
- { id: 'contenedores', typeId: 'figure', kind: 'svg', placement: { position: 'here' },
+ { id: 'contenedores', typeId: 'figure', kind: 'svg',Erros comuns
Erro comum
Um estilo de título herda a quebra de página do seu nível
Uma entrada de headingStyles recebe do seu nível de título todos os campos que não define, inclusive breakBefore. Um sumário ou um colofão com estilo sobre um H1 depois de um :::pagebreak herda a paridade 'odd' e cai depois de uma página em branco. Dê a esse estilo breakBefore: { enabled: false }. Estilos de título →
Erro comum
Os arquivos do Fontsource cobrem letras, não símbolos
O kit incorpora o arquivo latin do Fontsource de cada fonte e, quando o texto usa esses caracteres, o arquivo latin-ext para č, ł, † e o arquivo greek para α, χ (em uma família que o tenha: Lora e Gelasio não têm), na tela e no PDF. Símbolos como →, ≈, ✓ e ★ não estão em nenhum desses arquivos e somem no PDF: desenhe-os, componha-os como matemática ou escolha uma fonte cujos arquivos os tenham. Fontes incorporadas ao PDF →
O código não consegue validar o próprio PDF, porque o veraPDF roda fora do navegador. Baixe o arquivo e rode verapdf -f ua1 accessible-tagged-pdf.pdf; a cópia capturada para esta página passa. O validador não sabe dizer se um texto alternativo descreve a imagem, por isso ouça o guia também com um leitor de tela.
O colofão imprime o endereço da web completo porque o guia foi escrito para o postext 1.4.1, em que um link de Markdown imprimia as palavras sem acrescentar nenhum link ao PDF. A partir do postext 1.10, um link [text](url) funciona no PDF e é marcado como um elemento Link cujo texto são as palavras com o link.
Créditos
- Receita
- Ignacio Ferro
- Texto
- Texto original, CC BY 4.0
- Fontes
- Atkinson Hyperlegible Next (SIL OFL 1.1) · Atkinson Hyperlegible Mono (SIL OFL 1.1) · Public Sans (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)


