In short
A four-page recycling guide from a town council. It shows how to make a PDF that screen readers can follow, with picture descriptions and tables they can read aloud.
What you'll build
Reciclar en el barrio is a four-page A4 recycling guide from an invented Spanish council, for reading on screen or printing at home. The navy cover shows the five street bins on a yellow kerb. Page 2 holds the contents and three boxes beside a letter from the councillor, and pages 3 and 4 the two sections, in two ragged columns of Atkinson Hyperlegible Next. The pen exports a tagged PDF that passes veraPDF's PDF/UA-1 checks, with headings, lists, boxes and tables in reading order, alt text on the figure and header cells in both tables. The file declares its title and language (es), and its bookmarks and contents rows link to the pages. Tags do not print, so the pen draws them over page 3 of its preview, shown here, each tagged block in a numbered box labelled with its tag. The downloaded PDF has no overlay.
This recipe answers
- How do I produce an accessible (tagged, PDF/UA) PDF with alt text and a document language?
- How do I get "Figure" and "Table" labels in my document's language?
- How do I add a table of contents that updates itself (leaders, page numbers, authors, part rows)?
- How do I export a real PDF in the browser with the fonts embedded?
The short answer
// 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
The alt text and header cells the tags take from the resources
Ingredients
- Features
- Accessible tagged PDFTable of contentsPDF exportPDF bookmarksFigure and Table in your languageTables from dataFigures exactly hereColour swatchesCitations that place figuresDocument metadataHeading stylesUnnumbered chaptersDesigned openersFull-width chapter bandCovers, title pages and colophonsPictures in page designsCallout boxesFonts before layoutPages on a canvas
- Also uses
- Heading attributesNumbered headingsLeaving the grid on purposePage and column breaksParagraph stylesFonts embedded in the PDFFigures and tables as resourcesSection geometryRunning heads per sectionLine breaks in titles
- Type
- Atkinson Hyperlegible Next, Atkinson Hyperlegible Mono, Public Sans (SIL OFL 1.1)
- Assets
- None: every picture is drawn in code
Method
#1 · The document's language and title
locale: LANG, // → /Lang es, and "Figura", "Tabla" in the captions and the citations
// /Title and /Author come from the frontmatter's title and author
postext-pdf writes the language of the tags from locale, here /Lang es, so a screen reader reads the guide with Spanish pronunciation; without it the file declares en-US. The title and author of the frontmatter in content.es.md become the PDF's title and author, and the file asks viewers to show that title in the window bar instead of the file name. The same locale gives the captions and the citations their Spanish names: “Figura 1.1”, “tabla 1.1”. The short answer gives the figure and the tables their accessible text: altText becomes the figure's alternate description (/Alt) and each table's /Summary, and the first row and the first column of both tables are tagged as header cells.
#2 · One outline, and a cover band with nothing but the title
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
] };
The tag tree takes its H1 and H2 elements from the Markdown headings, and the PDF's bookmarks come from the same list, so the cover, the contents, the letter and both sections are level 1 and the crossheads level 2. postext-pdf tags every text element of a heading's design as part of that heading, so the cover's band holds only the title, and the lead and the council's name are set below it as paragraphs. The navy bands, the kerb and the row of bins are design elements, and the PDF marks design boxes and images as artifacts, so they need no alt text and a screen reader skips them.
#3 · Contents that link
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 lists the H1s and H2s with the page labels they print, and in the PDF each of its eleven rows links to the top of its page. The :ref citations “figura 1.1” and “tabla 1.1” on page 3 and “tabla 2.1” on page 4 link to the figure and the tables. The page numbers are set in the text face, Atkinson Hyperlegible Next Bold, and the leaders take the numbers' face, not the Public Sans of the entries.
#4 · Reading order, drawn on the page
// 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))];
}
A screen reader follows the tags. renderToPdf tags the band's title first, then each column from top to bottom, and it reads a float right after the paragraph that cites it, wherever the page paints it. This function replays that order to number the boxes on page 3, and the PDF's structure tree lists the same fourteen elements in the same order. The figure and both tables sit in the flow, with placement: { position: 'here' } and a ::resource line, so a sighted reader also meets each one under the sentence that cites it. The paragraph on glass that runs into the second column keeps one number, 9, because the PDF tags both parts as one paragraph.
#5 · Colours picked by contrast ratio
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);
PDF/UA-1 does not check colour, but WCAG 2.2 asks for 4.5:1 between text and its background. The ink measures 15.6:1 on white, white type 12.5:1 on the navy bands and the footer's grey 7.0:1. The yellow gives 1.8:1 on white, so it appears only on navy (6.9:1) and as a fill. The pictograms follow WCAG's 3:1 for graphics: white where it reaches that against the bin, ink on the yellow one. cell() writes each container's name beside its swatch, and gives the recycling centre an empty square, so no instruction depends on telling colours apart.
The whole recipe
// ═══ 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.
The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)
Variations
#Let the figure float
Drop the placement and figure 1.1 floats to the foot of page 3's first column. The PDF still reads it after the paragraph that cites it, so the overlay keeps its number, 3, and the order of the tags does not change.
- { id: 'contenedores', typeId: 'figure', kind: 'svg', placement: { position: 'here' },
+ { id: 'contenedores', typeId: 'figure', kind: 'svg',Pitfalls
Pitfall
A heading style inherits its level's page break
A headingStyles entry takes every field it leaves out from its heading level, breakBefore included. A contents page or a colophon styled on an H1 after a :::pagebreak inherits parity 'odd' and lands behind a blank page. Give such a style breakBefore: { enabled: false }. Heading styles →
Pitfall
Fontsource files cover letters, not symbols
The kit embeds a face's Fontsource latin file, plus its latin-ext file for č, ł, † and its greek file for α, χ (in a family that ships one: Lora and Gelasio do not), when the text sets them, on screen and in the PDF. Symbols such as →, ≈, ✓ and ★ are in none of those files and go missing in the PDF: draw them, set them as maths, or choose a face whose files hold them. Fonts embedded in the PDF →
The pen cannot validate its own PDF, because veraPDF runs outside the browser. Download the file and run verapdf -f ua1 accessible-tagged-pdf.pdf; the copy captured for this page passes. The checker cannot tell whether an alt text describes its picture, so listen to the guide with a screen reader as well.
The colophon prints the web address in full because the guide was written for postext 1.4.1, where a Markdown link printed its words and added no link to the PDF. From postext 1.10 a [text](url) link is live in the PDF, tagged as a Link element whose text is the linked words.
Credits
- Recipe
- Ignacio Ferro
- Text
- Original prose, CC BY 4.0
- Fonts
- Atkinson Hyperlegible Next (SIL OFL 1.1) · Atkinson Hyperlegible Mono (SIL OFL 1.1) · Public Sans (SIL OFL 1.1)
Edit this write-up ↗ (opens in a new tab)Recipe folder on GitHub ↗ (opens in a new tab)


