本文へスキップ
レシピ番号39

レシピ集 · 第10章 · 出力と組み込み

アクセシブルなタグ付きPDF(PDF/UA)

代替テキスト、表の見出しセル、文書の言語、リンク付きの目次を備えたタグ付きPDF/UA-1として書き出したごみ分別ガイド。プレビューでは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行

かんたんな説明

町の役所が配る4ページのごみ分別ガイドです。画面読み上げソフトがたどれるPDFの作り方を示します。画像には代替テキストが付き、表も読み上げられます。

できあがり

『Reciclar en el barrio』は、架空のスペインの役所が作ったA4判4ページのごみ分別ガイドです。画面で読むことも、家で印刷することも想定しています。紺の表紙には、黄色の縁石の上に5つの街頭ごみ容器が並びます。2ページ目には目次と3つの囲み、その横に環境担当議員の挨拶文を置き、3・4ページ目に2つの節を、Atkinson Hyperlegible Nextの左そろえ(行末不ぞろい)2段組みで組みます。CodePenのサンプルは、veraPDFのPDF/UA-1検査に合格するタグ付きPDFを書き出します。見出し、リスト、囲み、表が読み上げ順に並び、図には代替テキストが、2つの表には見出しセルが付きます。ファイルは題と言語(es)を宣言し、しおりと目次の各行はそれぞれのページにリンクします。タグは印刷されないため、サンプルはプレビューの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つの表の1行目と1列目は見出しセルとしてタグ付けされます。

#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のしおりも同じ一覧から作られます。そのため表紙、目次、挨拶文、2つの節はレベル1、中見出しはレベル2になります。postext-pdfは見出しのデザインに含まれるテキスト要素をすべてその見出しの一部としてタグ付けします。そこで表紙の帯には題だけを載せ、リード文と役所の名前は帯の下に段落として組みます。紺の帯、縁石、並んだ容器はデザイン要素です。PDFはデザインの箱と画像をアーティファクトとして扱うので、代替テキストは要らず、画面読み上げソフトはこれらを読み飛ばします。

#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では11行それぞれが該当ページの先頭にリンクします。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の構造ツリーにも同じ14の要素が同じ順に並びます。図と2つの表はplacement: { position: 'here' }と::resource行で本文の流れの中に置いてあるので、目で読む人も、参照する文のすぐ下でそれぞれを見つけられます。2段目へ続くガラスの段落の番号が9ひとつなのは、PDFが2つの部分をひとつの段落としてタグ付けするからです。

#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()は各容器の名前を色見本の横に書き、リサイクルセンターには空の四角を付けます。色の見分けに頼る指示はひとつもありません。

レシピの全体

Sandbox
// ═══ 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ページ目の1段目の下端へフロートします。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に埋め込むフォント →

veraPDFはブラウザーの外で動くため、サンプルは自分のPDFを検証できません。ファイルをダウンロードしてverapdf -f ua1 accessible-tagged-pdf.pdfを実行してください。このページのために取得したファイルは合格しています。代替テキストが画像を正しく説明しているかは検査ツールには判断できないので、画面読み上げソフトでガイドを聞いて確かめてください。

奥付にウェブアドレスを省略せずに印刷しているのは、このガイドをpostext 1.4.1向けに書いたからです。このバージョンではMarkdownのリンクは文字を印刷するだけで、PDFにリンクを加えませんでした。postext 1.10からは[text](url)のリンクがPDF上で有効になり、リンクされた語をテキストとするLink要素としてタグ付けされます。

クレジット

レシピ
Ignacio Ferro
本文
書き下ろしの文章, CC BY 4.0
フォント
Atkinson Hyperlegible Next (SIL OFL 1.1) · Atkinson Hyperlegible Mono (SIL OFL 1.1) · Public Sans (SIL OFL 1.1)
SandboxPDF