Kurz gesagt
Ein vierseitiger Abfallratgeber einer Stadtverwaltung. Er zeigt, wie ein PDF entsteht, dem Screenreader folgen können, mit Bildbeschreibungen und Tabellen, die sie vorlesen können.
Was Sie setzen
Reciclar en el barrio ist ein vierseitiger Abfallratgeber im Format A4 von einer erfundenen spanischen Stadtverwaltung, zum Lesen am Bildschirm oder zum Ausdrucken zu Hause. Der marineblaue Umschlag zeigt die fünf Straßentonnen auf einer gelben Bordsteinkante. Seite 2 enthält das Inhaltsverzeichnis und drei Kästen neben einem Brief des Dezernenten, die Seiten 3 und 4 die beiden Abschnitte in zwei Spalten im Flattersatz aus der Atkinson Hyperlegible Next. Der Pen exportiert ein getaggtes PDF, das die PDF/UA-1-Prüfungen von veraPDF besteht: Überschriften, Listen, Kästen und Tabellen in Lesereihenfolge, Alternativtext an der Abbildung und Kopfzellen in beiden Tabellen. Die Datei gibt ihren Titel und ihre Sprache (es) an, und ihre Lesezeichen wie die Zeilen des Inhaltsverzeichnisses verlinken auf die Seiten. Tags werden nicht gedruckt, deshalb zeichnet der Pen sie über Seite 3 seiner Vorschau, die hier zu sehen ist: jeden getaggten Block in einem nummerierten Rahmen, beschriftet mit seinem Tag. Das heruntergeladene PDF hat diese Überlagerung nicht.
Dieses Rezept beantwortet
- Wie erzeuge ich ein barrierefreies (getaggtes, PDF/UA-)PDF mit Alternativtext und Dokumentsprache?
- Wie erhalte ich die Beschriftungen „Abbildung“ und „Tabelle“ in der Sprache meines Dokuments?
- Wie füge ich ein Inhaltsverzeichnis hinzu, das sich selbst aktualisiert (Führungspunkte, Seitenzahlen, Autoren, Teilzeilen)?
- Wie exportiere ich im Browser ein echtes PDF mit eingebetteten Schriften?
Die kurze Antwort
// 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
Zutaten
- Funktionen
- Barrierefreies getaggtes PDFInhaltsverzeichnisPDF-ExportPDF-LesezeichenAbbildung und Tabelle in Ihrer SpracheTabellen aus DatenAbbildungen genau hierFarbfelderVerweise, die Abbildungen platzierenDokument-MetadatenÜberschriftenformateKapitel ohne NummerGestaltete AuftakteKapitelband über die ganze BreiteUmschläge, Titelseiten und ImpressumBilder in SeitengestaltungenKästenSchriften vor dem LayoutSeiten auf einem Canvas
- Nutzt außerdem
- ÜberschriftenattributeNummerierte ÜberschriftenDas Raster bewusst verlassenSeiten- und SpaltenumbrücheAbsatzformateIm PDF eingebettete SchriftenAbbildungen und Tabellen als RessourcenAbschnittsgeometrieKolumnentitel je AbschnittZeilenumbrüche in Titeln
- Schrift
- Atkinson Hyperlegible Next, Atkinson Hyperlegible Mono, Public Sans (SIL OFL 1.1)
- Dateien
- Keine: Jedes Bild wird im Code gezeichnet
Zubereitung
#1 · Sprache und Titel des Dokuments
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 schreibt die Sprache der Tags aus locale, hier /Lang es, sodass ein Screenreader den Ratgeber mit spanischer Aussprache liest; ohne diese Angabe gibt die Datei en-US an. title und author aus dem Frontmatter von content.es.md werden Titel und Autor des PDF, und die Datei bittet Betrachter, diesen Titel statt des Dateinamens in der Fensterleiste zu zeigen. Dieselbe locale gibt den Legenden und Verweisen ihre spanischen Namen: „Figura 1.1“, „tabla 1.1“. Die kurze Antwort gibt der Abbildung und den Tabellen ihren zugänglichen Text: altText wird zur Alternativbeschreibung der Abbildung (/Alt) und zur /Summary jeder Tabelle, und die erste Zeile und die erste Spalte beider Tabellen werden als Kopfzellen getaggt.
#2 · Eine Gliederung und ein Umschlagband nur mit dem Titel
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
] };
Der Tag-Baum nimmt seine H1- und H2-Elemente aus den Markdown-Überschriften, und die Lesezeichen des PDF stammen aus derselben Liste: Umschlag, Inhaltsverzeichnis, Brief und beide Abschnitte sind Ebene 1, die Zwischentitel Ebene 2. postext-pdf taggt jedes Textelement in der Gestaltung einer Überschrift als Teil dieser Überschrift. Deshalb enthält das Band des Umschlags nur den Titel, und Vorspann und Name der Stadtverwaltung stehen als Absätze darunter. Die marineblauen Bänder, die Bordsteinkante und die Reihe der Tonnen sind Gestaltungselemente, und das PDF markiert Gestaltungskästen und -bilder als Artefakte; sie brauchen also keinen Alternativtext, und ein Screenreader überspringt sie.
#3 · Ein Inhaltsverzeichnis mit 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 listet die H1 und H2 mit ihren Seitenzahlen, und im PDF verlinkt jede seiner elf Zeilen auf den Kopf ihrer Seite. Die :ref-Verweise „figura 1.1“ und „tabla 1.1“ auf Seite 3 und „tabla 2.1“ auf Seite 4 verlinken auf die Abbildung und die Tabellen. Die Seitenzahlen stehen in der Textschrift, Atkinson Hyperlegible Next Bold, und die Punktlinien übernehmen die Schrift der Zahlen, nicht die Public Sans der Einträge.
#4 · Die Lesereihenfolge, auf die Seite gezeichnet
// 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))];
}
Ein Screenreader folgt den Tags. renderToPdf taggt zuerst den Titel im Band, dann jede Spalte von oben nach unten, und jedes Gleitobjekt folgt direkt auf den Absatz, der darauf verweist, gleich wo die Seite es zeichnet. Diese Funktion spielt dieselbe Reihenfolge nach, um die Rahmen auf Seite 3 zu nummerieren, und der Strukturbaum des PDF listet dieselben vierzehn Elemente in derselben Reihenfolge. Die Abbildung und beide Tabellen stehen im Textfluss, mit placement: { position: 'here' } und einer Zeile ::resource, sodass auch sehende Leser jede von ihnen unter dem Satz finden, der auf sie verweist. Der Absatz über Glas, der in die zweite Spalte weiterläuft, behält eine einzige Nummer, 9, weil das PDF beide Teile als einen Absatz taggt.
#5 · Farben nach Kontrastverhältnis gewählt
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 prüft keine Farben, doch WCAG 2.2 verlangt 4,5:1 zwischen Text und Hintergrund. Die Textfarbe erreicht 15,6:1 auf Weiß, weiße Schrift 12,5:1 auf den marineblauen Bändern und das Grau der Fußzeile 7,0:1. Das Gelb kommt auf Weiß nur auf 1,8:1, deshalb erscheint es nur auf Marineblau (6,9:1) und als Fläche. Die Piktogramme folgen der WCAG-Schwelle von 3:1 für Grafiken: weiß, wo Weiß sie gegen die Tonne erreicht, in Textfarbe auf der gelben. cell() schreibt den Namen jeder Tonne neben ihr Farbfeld und gibt dem Wertstoffhof ein leeres Quadrat, sodass keine Anweisung davon abhängt, Farben unterscheiden zu können.
Das ganze Rezept
// ═══ 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.
Das zusammengesetzte script.js läuft unverändert: Fügen Sie es in das Modulskript einer beliebigen Seite ein, oder öffnen Sie das Rezept auf CodePen. Ordner des Rezepts auf GitHub ↗ (öffnet sich in einem neuen Tab)
Varianten
#Die Abbildung gleiten lassen
Entfernen Sie die Platzierung, und Abbildung 1.1 gleitet an den Fuß der ersten Spalte von Seite 3. Im PDF folgt sie weiterhin auf den Absatz, der auf sie verweist, deshalb behält die Überlagerung ihre Nummer 3, und die Reihenfolge der Tags ändert sich nicht.
- { id: 'contenedores', typeId: 'figure', kind: 'svg', placement: { position: 'here' },
+ { id: 'contenedores', typeId: 'figure', kind: 'svg',Häufige Fehler
Häufiger Fehler
Ein Überschriftenformat erbt den Seitenumbruch seiner Ebene
Ein Eintrag in headingStyles übernimmt jedes Feld, das er auslässt, von seiner Überschriftenebene, breakBefore eingeschlossen. Ein Inhaltsverzeichnis oder Impressum, das nach einem :::pagebreak über eine H1 gestaltet wird, erbt die Parität 'odd' und landet hinter einer Vakatseite. Geben Sie einem solchen Format breakBefore: { enabled: false }. Überschriftenformate →
Häufiger Fehler
Fontsource-Dateien decken Buchstaben ab, keine Symbole
Das Kit bettet die latin-Datei einer Schrift von Fontsource ein, dazu ihre latin-ext-Datei für č, ł, † und ihre greek-Datei für α, χ (bei einer Familie, die eine mitliefert: Lora und Gelasio tun es nicht), wenn der Text diese Zeichen setzt, auf dem Bildschirm und im PDF. Symbole wie →, ≈, ✓ und ★ stehen in keiner dieser Dateien und fehlen im PDF: zeichnen Sie sie, setzen Sie sie als Mathematik oder wählen Sie eine Schrift, deren Dateien sie enthalten. Im PDF eingebettete Schriften →
Der Pen kann sein eigenes PDF nicht validieren, weil veraPDF außerhalb des Browsers läuft. Laden Sie die Datei herunter und führen Sie verapdf -f ua1 accessible-tagged-pdf.pdf aus; die für diese Seite erfasste Kopie besteht die Prüfung. Ob ein Alternativtext sein Bild beschreibt, kann die Prüfung nicht erkennen, hören Sie sich den Ratgeber also auch mit einem Screenreader an.
Im Impressum steht die Webadresse ausgeschrieben, weil der Ratgeber für postext 1.4.1 geschrieben wurde, wo ein Markdown-Link nur seine Wörter ausgab und dem PDF keinen Link hinzufügte. Seit postext 1.10 ist ein Link [text](url) im PDF aktiv, getaggt als Element Link, dessen Text die verlinkten Wörter sind.
Nachweise
- Rezept
- Ignacio Ferro
- Text
- Eigener Text, CC BY 4.0
- Schriften
- Atkinson Hyperlegible Next (SIL OFL 1.1) · Atkinson Hyperlegible Mono (SIL OFL 1.1) · Public Sans (SIL OFL 1.1)
- Code
- MIT, wie Postext
Diesen Text bearbeiten ↗ (öffnet sich in einem neuen Tab)Ordner des Rezepts auf GitHub ↗ (öffnet sich in einem neuen Tab)


