Skip to content

Commit e30a0bb

Browse files
claude: Validate PDFs against pdf-standard using verapdf
When a document specifies pdf-standard (PDF/A or PDF/UA) and verapdf is available on PATH, the generated PDF is validated for compliance. Validation warnings are shown if the PDF doesn't meet the specified standard. Supported standards for validation: PDF/A-1a, 1b, 2a, 2b, 2u, 3a, 3b, 3u, 4, 4e, 4f and PDF/UA-1, UA-2. If verapdf is not installed, a warning suggests installing it via `quarto install verapdf`. CI installs verapdf for pdf-standard tests. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent ba5de12 commit e30a0bb

10 files changed

Lines changed: 413 additions & 43 deletions

File tree

‎.github/workflows/test-smokes.yml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,13 @@ jobs:
201201
run: |
202202
quarto install tinytex
203203
204+
- name: Install veraPDF for PDF standard validation
205+
if: runner.os == 'Linux' && contains(inputs.buckets, 'pdf-standard')
206+
env:
207+
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
208+
run: |
209+
quarto install verapdf
210+
204211
- name: Cache Typst packages
205212
id: cache-typst
206213
uses: ./.github/actions/cache-typst

‎src/command/render/output-tex.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,12 @@ import {
1515
kKeepTex,
1616
kOutputExt,
1717
kOutputFile,
18+
kPdfStandard,
1819
kTargetFormat,
1920
} from "../../config/constants.ts";
2021
import { Format } from "../../config/types.ts";
22+
import { asArray } from "../../core/array.ts";
23+
import { validatePdfStandards } from "../../core/verapdf.ts";
2124

2225
import { PandocOptions, RenderFlags, RenderOptions } from "./types.ts";
2326
import { kStdOut, replacePandocOutputArg } from "./flags.ts";
@@ -80,6 +83,16 @@ export function texToPdfOutputRecipe(
8083
const input = join(inputDir, output);
8184
const pdfOutput = await pdfGenerator.generate(input, format, pandocOptions);
8285

86+
// Validate PDF against specified standards using verapdf (if available)
87+
const pdfStandards = asArray(
88+
format.render?.[kPdfStandard] ?? format.metadata?.[kPdfStandard],
89+
) as string[];
90+
if (pdfStandards.length > 0) {
91+
await validatePdfStandards(pdfOutput, pdfStandards, {
92+
quiet: pandocOptions.flags?.quiet,
93+
});
94+
}
95+
8396
// keep tex if requested
8497
const compileTex = join(inputDir, output);
8598
if (!format.render[kKeepTex]) {

‎src/command/render/output-typst.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import {
1515
kPdfStandard,
1616
kVariant,
1717
} from "../../config/constants.ts";
18-
import { warning } from "../../deno_ral/log.ts";
18+
import { error, warning } from "../../deno_ral/log.ts";
1919
import { Format } from "../../config/types.ts";
2020
import { writeFileToStdout } from "../../core/console.ts";
2121
import { dirAndStem, expandPath } from "../../core/path.ts";
@@ -29,6 +29,7 @@ import {
2929
} from "../../core/typst.ts";
3030
import { asArray } from "../../core/array.ts";
3131
import { ProjectContext } from "../../project/types.ts";
32+
import { validatePdfStandards } from "../../core/verapdf.ts";
3233

3334
export function useTypstPdfOutputRecipe(
3435
format: Format,
@@ -83,7 +84,21 @@ export function typstPdfOutputRecipe(
8384
typstOptions,
8485
);
8586
if (!result.success) {
86-
throw new Error();
87+
// Log the error so test framework can detect it via shouldError
88+
if (result.stderr) {
89+
error(result.stderr);
90+
}
91+
throw new Error("Typst compilation failed");
92+
}
93+
94+
// Validate PDF against specified standards using verapdf (if available)
95+
const pdfStandards = asArray(
96+
format.render?.[kPdfStandard] ?? format.metadata?.[kPdfStandard],
97+
) as string[];
98+
if (pdfStandards.length > 0) {
99+
await validatePdfStandards(pdfOutput, pdfStandards, {
100+
quiet: options.flags?.quiet,
101+
});
87102
}
88103

89104
// keep typ if requested

‎src/core/verapdf.ts‎

Lines changed: 274 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,274 @@
1+
/*
2+
* verapdf.ts
3+
*
4+
* Copyright (C) 2020-2022 Posit Software, PBC
5+
*/
6+
7+
import { info, warning } from "../deno_ral/log.ts";
8+
import { basename, join } from "../deno_ral/path.ts";
9+
import * as colors from "fmt/colors";
10+
11+
import { execProcess } from "./process.ts";
12+
import { which } from "./path.ts";
13+
import { quartoDataDir } from "./appdirs.ts";
14+
import { existsSync } from "../deno_ral/fs.ts";
15+
import { isWindows } from "../deno_ral/platform.ts";
16+
17+
// verapdf flavours (profiles) supported for validation
18+
// Maps quarto pdf-standard values to verapdf --flavour values
19+
const kVerapdfFlavours: Record<string, string> = {
20+
// PDF/A standards
21+
"a-1a": "1a",
22+
"a-1b": "1b",
23+
"a-2a": "2a",
24+
"a-2b": "2b",
25+
"a-2u": "2u",
26+
"a-3a": "3a",
27+
"a-3b": "3b",
28+
"a-3u": "3u",
29+
"a-4": "4",
30+
"a-4e": "4e",
31+
"a-4f": "4f",
32+
// PDF/UA standards
33+
"ua-1": "ua1",
34+
"ua-2": "ua2",
35+
};
36+
37+
// Standards that verapdf can validate (keys of the above map)
38+
const kVerapdfSupportedStandards = new Set(Object.keys(kVerapdfFlavours));
39+
40+
/**
41+
* Check if a pdf-standard value can be validated by verapdf
42+
*/
43+
export function isVerapdfSupportedStandard(standard: string): boolean {
44+
const normalized = standard.toLowerCase().replace(/^pdf[/-]?/, "");
45+
return kVerapdfSupportedStandards.has(normalized);
46+
}
47+
48+
/**
49+
* Get verapdf flavour for a pdf-standard value, or undefined if not supported
50+
*/
51+
export function getVerapdfFlavour(standard: string): string | undefined {
52+
const normalized = standard.toLowerCase().replace(/^pdf[/-]?/, "");
53+
return kVerapdfFlavours[normalized];
54+
}
55+
56+
/**
57+
* Find verapdf binary path - checks PATH and quarto install location
58+
*/
59+
export async function findVerapdfPath(): Promise<string | undefined> {
60+
// First check PATH
61+
const pathResult = await which("verapdf");
62+
if (pathResult) {
63+
return pathResult;
64+
}
65+
66+
// Check quarto install location
67+
const quartoVerapdfDir = quartoDataDir("verapdf");
68+
const quartoVerapdfBin = isWindows
69+
? join(quartoVerapdfDir, "verapdf.bat")
70+
: join(quartoVerapdfDir, "verapdf");
71+
72+
if (existsSync(quartoVerapdfBin)) {
73+
return quartoVerapdfBin;
74+
}
75+
76+
return undefined;
77+
}
78+
79+
export interface VerapdfValidationResult {
80+
valid: boolean;
81+
flavour: string;
82+
errors: string[];
83+
output: string;
84+
}
85+
86+
/**
87+
* Run verapdf validation on a PDF file
88+
*/
89+
export async function validatePdf(
90+
pdfPath: string,
91+
flavour: string,
92+
quiet = false,
93+
): Promise<VerapdfValidationResult> {
94+
const verapdfPath = await findVerapdfPath();
95+
if (!verapdfPath) {
96+
throw new Error("verapdf not found");
97+
}
98+
99+
if (!quiet) {
100+
info(
101+
`[verapdf]: Validating ${
102+
basename(pdfPath)
103+
} against PDF/${flavour.toUpperCase()}...`,
104+
{ newline: false },
105+
);
106+
}
107+
108+
const result = await execProcess({
109+
cmd: verapdfPath,
110+
args: ["-f", flavour, pdfPath],
111+
stdout: "piped",
112+
stderr: "piped",
113+
});
114+
115+
const output = result.stdout || "";
116+
117+
// Parse verapdf XML output to determine compliance
118+
// Look for isCompliant="true" in validationReport or compliant count in batchSummary
119+
const isCompliantMatch = output.match(/isCompliant="(true|false)"/);
120+
const batchSummaryMatch = output.match(
121+
/validationReports[^>]*compliant="(\d+)"[^>]*nonCompliant="(\d+)"/,
122+
);
123+
124+
let valid = false;
125+
if (isCompliantMatch) {
126+
valid = isCompliantMatch[1] === "true";
127+
} else if (batchSummaryMatch) {
128+
const compliant = parseInt(batchSummaryMatch[1]);
129+
const nonCompliant = parseInt(batchSummaryMatch[2]);
130+
valid = nonCompliant === 0 && compliant > 0;
131+
} else {
132+
// Fallback: assume valid if exit code is 0 and no obvious failure indicators
133+
valid = result.success;
134+
}
135+
136+
// Extract error messages from output when validation fails
137+
const errors: string[] = [];
138+
if (!valid) {
139+
// Look for failed rules with descriptions
140+
// Pattern: <rule ...><description>...</description>
141+
const ruleDescMatches = output.matchAll(
142+
/<rule[^>]*>[\s\S]*?<description>([^<]+)<\/description>/g,
143+
);
144+
for (const match of ruleDescMatches) {
145+
const desc = match[1].trim();
146+
if (desc && !errors.includes(desc)) {
147+
errors.push(desc);
148+
}
149+
}
150+
151+
// Also look for clause violations in ruleId
152+
if (errors.length === 0) {
153+
const clauseMatches = output.matchAll(
154+
/<ruleId[^>]*clause="([^"]*)"[^>]*specification="([^"]*)"/g,
155+
);
156+
for (const match of clauseMatches) {
157+
errors.push(`${match[2]} clause ${match[1]} violation`);
158+
}
159+
}
160+
161+
// Extract failedChecks count for summary
162+
const failedChecksMatch = output.match(/failedChecks="(\d+)"/);
163+
if (failedChecksMatch && parseInt(failedChecksMatch[1]) > 0) {
164+
const count = failedChecksMatch[1];
165+
if (errors.length === 0) {
166+
errors.push(`${count} compliance check(s) failed`);
167+
}
168+
}
169+
}
170+
171+
if (!quiet) {
172+
if (valid) {
173+
info(colors.green("PASSED\n"));
174+
} else {
175+
info(colors.red("FAILED\n"));
176+
}
177+
}
178+
179+
return {
180+
valid,
181+
flavour,
182+
errors,
183+
output,
184+
};
185+
}
186+
187+
export interface PdfValidationOptions {
188+
quiet?: boolean;
189+
warnOnMissingVerapdf?: boolean;
190+
}
191+
192+
/**
193+
* Validate a PDF against specified standards using verapdf
194+
* Returns true if all validations pass (or if no validatable standards specified)
195+
*/
196+
export async function validatePdfStandards(
197+
pdfPath: string,
198+
standards: string[],
199+
options: PdfValidationOptions = {},
200+
): Promise<boolean> {
201+
const quiet = options.quiet ?? false;
202+
const warnOnMissingVerapdf = options.warnOnMissingVerapdf ?? true;
203+
204+
// Filter to standards that verapdf can validate
205+
const validatableStandards: { standard: string; flavour: string }[] = [];
206+
const nonValidatableStandards: string[] = [];
207+
208+
for (const standard of standards) {
209+
const normalized = standard.toLowerCase().replace(/^pdf[/-]?/, "");
210+
// Skip version numbers (1.4, 1.5, etc.)
211+
if (/^\d+\.\d+$/.test(normalized)) {
212+
continue;
213+
}
214+
const flavour = getVerapdfFlavour(normalized);
215+
if (flavour) {
216+
validatableStandards.push({ standard: normalized, flavour });
217+
} else {
218+
nonValidatableStandards.push(standard);
219+
}
220+
}
221+
222+
// Nothing to validate
223+
if (validatableStandards.length === 0) {
224+
return true;
225+
}
226+
227+
// Check if verapdf is available
228+
const verapdfPath = await findVerapdfPath();
229+
if (!verapdfPath) {
230+
if (warnOnMissingVerapdf) {
231+
warning(
232+
`PDF standard validation requested but verapdf is not installed.\n` +
233+
`Install with: quarto install verapdf\n` +
234+
`Standards requested: ${
235+
validatableStandards.map((s) => s.standard).join(", ")
236+
}`,
237+
);
238+
}
239+
return true; // Don't fail the build, just warn
240+
}
241+
242+
// Warn about standards we can't validate
243+
if (nonValidatableStandards.length > 0) {
244+
warning(
245+
`The following PDF standards cannot be validated by verapdf and will be skipped: ` +
246+
nonValidatableStandards.join(", "),
247+
);
248+
}
249+
250+
// Run validation for each standard
251+
let allValid = true;
252+
for (const { standard, flavour } of validatableStandards) {
253+
try {
254+
const result = await validatePdf(pdfPath, flavour, quiet);
255+
if (!result.valid) {
256+
allValid = false;
257+
if (!quiet) {
258+
warning(
259+
`PDF validation failed for ${standard}:\n` +
260+
(result.errors.length > 0
261+
? result.errors.slice(0, 5).join("\n")
262+
: "See verapdf output for details"),
263+
);
264+
}
265+
}
266+
} catch (error) {
267+
if (!quiet) {
268+
warning(`Failed to run verapdf validation: ${error}`);
269+
}
270+
}
271+
}
272+
273+
return allValid;
274+
}

‎tests/docs/smoke-all/pdf-standard/latex-pdfa.qmd‎

Lines changed: 0 additions & 18 deletions
This file was deleted.

0 commit comments

Comments
 (0)