跳到主要内容
食谱编号39

排版食谱 · 第10章 · 输出与集成

带标签的无障碍PDF(PDF/UA)

一份垃圾分类指南,导出为符合PDF/UA-1的带标签PDF,带替代文字、表头单元格、文档语言和可跳转的目录;预览在第3页上画出了各个标签。

本页内容
类型
报告
输出
Canvas · PDF
难度
中级
Postext
已用Postext 1.65.0测试
需要≥ 1.25.0 · postext-pdf ≥ 1.25.0
许可证
更新于2026年10月10日
代码MIT · 文本CC BY 4.0

第2–3页,共4页

  • 西班牙文样例:尚无中文版本
  • 成品尺寸210 × 297 mm
  • 2栏, 栏间距8 mm
  • Atkinson Hyperlegible Next 10.5/15.5
  • Atkinson Hyperlegible Mono
  • Public Sans
  • 4页
  • 难度
  • Postext 1.65.0
  • 排版用时205 ms
  • 179行代码

简单来说

一份四页的市政垃圾分类指南。示例演示怎样做出读屏软件能顺利朗读的PDF,图片有文字说明,表格也能读出来。

成品一览

Reciclar en el barrio是一份四页A4的垃圾分类指南,出自一个虚构的西班牙市政府,适合在屏幕上阅读,也可以在家打印。藏青色封面上,五个街头垃圾桶立在黄色路缘上。第2页是目录和三个框,旁边是市议员的一封信;第3、4页是两个章节,用Atkinson Hyperlegible Next排成两栏齐左文字。这支pen导出的带标签PDF通过了veraPDF的PDF/UA-1检查:标题、列表、框和表格按阅读顺序排列,图带有替代文字,两张表都有表头单元格。文件声明了标题和语言(es),书签和目录各行都链接到对应页面。标签不会打印出来,所以pen在预览的第3页上把它们画了出来(即此处所示):每个带标签的块套在一个编号框里,并注明标签名。下载的PDF里没有这层叠加。

这道食谱解答

  • 怎样生成带替代文本和文档语言的无障碍PDF(带标签,PDF/UA)?
  • 怎样让“图”和“表”的标签使用文档的语言?
  • 怎样添加自动更新的目录(前导符、页码、作者、篇名行)?
  • 怎样在浏览器中导出嵌入字体的真正PDF?

简短回答

script.js · 第47–70行在完整代码中
// 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

用料

类型
Atkinson Hyperlegible Next, Atkinson Hyperlegible Mono, Public Sans(SIL OFL 1.1)
素材
无:所有图片都用代码绘制

做法

#1 · 文档的语言和标题

script.js · 第126–127行在完整代码中
  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根据locale写入标签的语言,这里是/Lang es,屏幕阅读器因此会用西班牙语发音朗读这份指南;不设的话,文件声明的是en-US。content.es.md前置元数据里的title和author会成为PDF的标题和作者,文件还会要求阅读器在窗口标题栏显示这个标题,而不是文件名。同一个locale让题注和引用用上西班牙语名称:“Figura 1.1”“tabla 1.1”。简短回答为图和表提供无障碍文本:altText成为图的替代描述(/Alt)和每张表的/Summary,两张表的第一行和第一列都标记为表头单元格。

#2 · 一份大纲,以及只放标题的封面色带

script.js · 第74–104行在完整代码中
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
  ] };

标签树的H1和H2元素来自Markdown标题,PDF书签也来自同一份列表,所以封面、目录、那封信和两个章节都是1级,小标题是2级。postext-pdf会把标题设计里的每个文本元素都标记为该标题的一部分,所以封面色带里只放标题,导语和市政府名称作为段落排在色带下方。藏青色色带、路缘和那排垃圾桶都是设计元素,PDF把设计框和图像标记为artifact,因此它们不需要替代文字,屏幕阅读器也会跳过。

#3 · 可跳转的目录

script.js · 第108–113行在完整代码中
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列出H1和H2及其印出的页码标签;在PDF中,这十一行每一行都链接到对应页面顶部。第3页的:ref引用“figura 1.1”“tabla 1.1”和第4页的“tabla 2.1”都链接到对应的图和表。页码用正文字体Atkinson Hyperlegible Next Bold,前导符跟着页码的字体走,不用条目的Public Sans。

#4 · 画在页面上的阅读顺序

script.js · 第299–319行在完整代码中
// 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))];
}

屏幕阅读器按标签朗读。renderToPdf先给色带里的标题加标签,然后各栏从上到下;浮动体不管画在页面何处,都紧跟在引用它的段落之后读出。这个函数重放这一顺序,给第3页的框编号;PDF的结构树也按同样的顺序列出这十四个元素。图和两张表用placement: { position: 'here' }加一行::resource留在文本流中,这样看版面的读者也能在引用它们的句子下面找到它们。延续到第二栏的玻璃那一段只有一个编号9,因为PDF把前后两部分标记为同一个段落。

#5 · 按对比度选颜色

script.js · 第15–34行在完整代码中
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不检查颜色,但WCAG 2.2要求文字与背景的对比度达到4.5:1。正文墨色在白底上为15.6:1,白字在藏青色色带上为12.5:1,页脚的灰色为7.0:1。黄色在白底上只有1.8:1,所以它只出现在藏青底上(6.9:1)或作为填充色。图标遵循WCAG对图形的3:1要求:与桶身对比够的用白色,黄色桶上用墨色。cell()在每个色块旁写出垃圾桶的名称,回收站则给一个空心方块,这样任何说明都不依赖分辨颜色。

完整食谱

沙盒
// ═══ 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.

组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)

变化

#让图浮动

去掉placement,图1.1就会浮动到第3页第一栏底部。PDF仍然在引用它的段落之后读出它,所以叠加层里它的编号还是3,标签的顺序不变。

-  { id: 'contenedores', typeId: 'figure', kind: 'svg', placement: { position: 'here' },
+  { id: 'contenedores', typeId: 'figure', kind: 'svg',

常见问题

易错点

标题样式会继承其级别的分页设置

headingStyles中的条目没有写出的字段都取自它所属的标题级别,breakBefore也不例外。在:::pagebreak之后以H1设置样式的目录页或版权页会继承parity 'odd',结果落在一张空白页之后。给这类样式设置breakBefore: { enabled: false }。 标题样式 →

易错点

Fontsource的文件只覆盖字母,不含符号

工具包嵌入每种字体在Fontsource的latin文件;正文用到č、ł、†时再嵌入latin-ext文件,用到α、χ时再嵌入greek文件(字体族须有该文件:Lora和Gelasio没有),屏幕和PDF都一样。→、≈、✓、★等符号不在这些文件里,会在PDF中缺失:把它们画出来、写成数学公式,或换用文件中包含它们的字体。 嵌入PDF的字体 →

pen无法校验自己生成的PDF,因为veraPDF在浏览器之外运行。下载文件后运行verapdf -f ua1 accessible-tagged-pdf.pdf;本页截取的这份文件可以通过。检查工具判断不了替代文字是否真的描述了图片,所以还要用屏幕阅读器把指南听一遍。

版权页把网址完整印了出来,因为这份指南是为postext 1.4.1写的,那时Markdown链接只印出文字,不会在PDF里加链接。从postext 1.10起,[text](url)链接在PDF中可以点击,并标记为一个Link元素,其文本就是链接的文字。

致谢

文本
原创文字, CC BY 4.0
字体
Atkinson Hyperlegible Next (SIL OFL 1.1) · Atkinson Hyperlegible Mono (SIL OFL 1.1) · Public Sans (SIL OFL 1.1)
沙盒PDF