@projektemacher/vivliostyle-batch-cli 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/dist/index.d.ts +19 -1
- package/dist/vivliostyle-batch-cli.js +413 -20
- package/package.json +4 -4
- package/src/metadata.ts +9 -1
- package/src/render/pdf-postprocess.ts +83 -10
- package/src/render/pdf-validate.ts +185 -0
- package/src/render/pdf.ts +56 -2
- package/src/render/srgb.icc +0 -0
- package/src/render/verapdf.ts +56 -0
- package/src/render/xmp.ts +12 -0
- package/src/vivliostyle-cli.ts +88 -10
package/src/metadata.ts
CHANGED
|
@@ -22,6 +22,10 @@ export type DocumentMetadata = {
|
|
|
22
22
|
subject?: string;
|
|
23
23
|
keywords?: string;
|
|
24
24
|
language?: string;
|
|
25
|
+
/** ISO 8601 creation date (information dictionary and XMP CreateDate). */
|
|
26
|
+
created?: string;
|
|
27
|
+
/** ISO 8601 modification date (information dictionary and XMP ModifyDate). */
|
|
28
|
+
modified?: string;
|
|
25
29
|
};
|
|
26
30
|
|
|
27
31
|
/** Language tag assumed when no source provides one (project contract). */
|
|
@@ -29,7 +33,9 @@ export const DEFAULT_LANGUAGE = "de";
|
|
|
29
33
|
|
|
30
34
|
/**
|
|
31
35
|
* Extracts metadata from the input document: <title>, the usual
|
|
32
|
-
* author/description/keywords meta tags
|
|
36
|
+
* author/description/keywords meta tags, the creation/modification dates
|
|
37
|
+
* (dcterms, falling back to the plain date meta tag) and the document
|
|
38
|
+
* language.
|
|
33
39
|
*/
|
|
34
40
|
export function extractMetadataFromDocument(document: Document): DocumentMetadata {
|
|
35
41
|
const title = document.querySelector("title")?.textContent?.trim();
|
|
@@ -46,6 +52,8 @@ export function extractMetadataFromDocument(document: Document): DocumentMetadat
|
|
|
46
52
|
...optional(metaContent(["author", "dc.creator", "dcterms.creator"]), (value) => ({ author: value })),
|
|
47
53
|
...optional(metaContent(["description", "dc.description"]), (value) => ({ subject: value })),
|
|
48
54
|
...optional(metaContent(["keywords"]), (value) => ({ keywords: value })),
|
|
55
|
+
...optional(metaContent(["dcterms.created", "dc.date", "date"]), (value) => ({ created: value })),
|
|
56
|
+
...optional(metaContent(["dcterms.modified", "dc.date.modified", "modified"]), (value) => ({ modified: value })),
|
|
49
57
|
...optional(document.documentElement.getAttribute("lang")?.trim() || metaContent(["content-language"]), (value) => ({
|
|
50
58
|
language: value
|
|
51
59
|
}))
|
|
@@ -27,7 +27,7 @@ import { existsSync, readFileSync } from "node:fs";
|
|
|
27
27
|
import { dirname, join, resolve } from "node:path";
|
|
28
28
|
import { fileURLToPath } from "node:url";
|
|
29
29
|
import * as mupdf from "mupdf";
|
|
30
|
-
import { buildXmpPacket, pdfDateToXmpDate, toXmpDate, type PdfLabel } from "./xmp.js";
|
|
30
|
+
import { buildXmpPacket, pdfDateToXmpDate, toXmpDate, xmpDateToPdfDate, type PdfLabel } from "./xmp.js";
|
|
31
31
|
|
|
32
32
|
/** Document metadata written to the information dictionary and the XMP packet. */
|
|
33
33
|
export type PdfMetadata = {
|
|
@@ -36,6 +36,10 @@ export type PdfMetadata = {
|
|
|
36
36
|
subject?: string;
|
|
37
37
|
keywords?: string;
|
|
38
38
|
language?: string;
|
|
39
|
+
/** ISO 8601 or PDF date; overrides the creation date the print backend wrote. */
|
|
40
|
+
created?: string;
|
|
41
|
+
/** ISO 8601 or PDF date; overrides the modification date the print backend wrote. */
|
|
42
|
+
modified?: string;
|
|
39
43
|
creator: string;
|
|
40
44
|
producer: string;
|
|
41
45
|
};
|
|
@@ -82,6 +86,20 @@ function createScope(): Scope {
|
|
|
82
86
|
// MuPDF exposes PDF version x.y as x * 10 + y.
|
|
83
87
|
type PdfVersion = 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 20;
|
|
84
88
|
|
|
89
|
+
/**
|
|
90
|
+
* The PDF version each standards label is defined against: PDF/A-1 and
|
|
91
|
+
* PDF/X-1a:2003 on PDF 1.4, PDF/X-4 on PDF 1.6, PDF/A-2 and PDF/A-3 on
|
|
92
|
+
* PDF 1.7 (ISO 32000-1) and PDF/A-4 on PDF 2.0 (ISO 32000-2).
|
|
93
|
+
*/
|
|
94
|
+
export function minimumVersionForLabel(label: PdfLabel): PdfVersion {
|
|
95
|
+
if (label.kind === "pdfa") {
|
|
96
|
+
if (label.part === "1") return 14;
|
|
97
|
+
if (label.part === "4") return 20;
|
|
98
|
+
return 17;
|
|
99
|
+
}
|
|
100
|
+
return label.version === "X-4" ? 16 : 14;
|
|
101
|
+
}
|
|
102
|
+
|
|
85
103
|
// The catalog /Version is written for every required version; MuPDF's wasm
|
|
86
104
|
// binding provides no API for the header version and a full save derives the
|
|
87
105
|
// header from the catalog entry (same approach as vivliostyle-cli).
|
|
@@ -98,6 +116,31 @@ function readInfoString(info: mupdf.PDFObject, key: string, scope: Scope): strin
|
|
|
98
116
|
return value.isString() ? value.asString() : undefined;
|
|
99
117
|
}
|
|
100
118
|
|
|
119
|
+
/**
|
|
120
|
+
* Parses an explicitly given date (ISO 8601, optionally date-only, or the PDF
|
|
121
|
+
* "D:…" form) into both formats the document needs: the information
|
|
122
|
+
* dictionary date (ISO 32000-1:2008, 7.9.4) and the XMP date (XMP Part 1,
|
|
123
|
+
* 8.2.1.2). A date without offset counts as UTC.
|
|
124
|
+
*/
|
|
125
|
+
export function parseExplicitDate(value: string, field: string): { pdfDate: string; xmpDate: string } {
|
|
126
|
+
const trimmed = value.trim();
|
|
127
|
+
const pdfFromXmp = xmpDateToPdfDate(trimmed);
|
|
128
|
+
if (pdfFromXmp !== undefined) return { pdfDate: pdfFromXmp, xmpDate: trimmed };
|
|
129
|
+
const xmpFromPdf = pdfDateToXmpDate(trimmed);
|
|
130
|
+
if (xmpFromPdf !== undefined) return { pdfDate: trimmed, xmpDate: xmpFromPdf };
|
|
131
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2}))?)?(?:[Zz]|([+\-])(\d{2}):?(\d{2}))?$/.exec(trimmed);
|
|
132
|
+
if (match === null) {
|
|
133
|
+
throw new Error(`Invalid ${field} date: "${value}". Use ISO 8601, e.g. 2024-11-18T00:00:00+01:00`);
|
|
134
|
+
}
|
|
135
|
+
const [, year, month, day, hour = "00", minute = "00", second = "00", sign, offsetHour, offsetMinute] = match;
|
|
136
|
+
const offset = sign === undefined ? "Z" : `${sign}${offsetHour}'${offsetMinute}`;
|
|
137
|
+
const xmpOffset = sign === undefined ? "Z" : `${sign}${offsetHour}:${offsetMinute}`;
|
|
138
|
+
return {
|
|
139
|
+
pdfDate: `D:${year}${month}${day}${hour}${minute}${second}${offset}`,
|
|
140
|
+
xmpDate: `${year}-${month}-${day}T${hour}:${minute}:${second}${xmpOffset}`
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
101
144
|
function readTrapped(info: mupdf.PDFObject, scope: Scope): "True" | "False" {
|
|
102
145
|
const trapped = scope.track(info.get("Trapped"));
|
|
103
146
|
return trapped.isName() && trapped.asName() === "True" ? "True" : "False";
|
|
@@ -155,10 +198,25 @@ export async function postProcessPdf(pdf: Uint8Array, options: PostProcessOption
|
|
|
155
198
|
modifyDate: readInfoString(info, "ModDate", scope),
|
|
156
199
|
trapped: readTrapped(info, scope)
|
|
157
200
|
}));
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
201
|
+
let infoCreationDate = creationDate;
|
|
202
|
+
let infoModifyDate = modifyDate;
|
|
203
|
+
let createDateXmp = creationDate !== undefined ? pdfDateToXmpDate(creationDate) : undefined;
|
|
204
|
+
let modifyDateXmp = modifyDate !== undefined ? pdfDateToXmpDate(modifyDate) : undefined;
|
|
205
|
+
if (metadata.created !== undefined) {
|
|
206
|
+
const parsed = parseExplicitDate(metadata.created, "--created");
|
|
207
|
+
infoCreationDate = parsed.pdfDate;
|
|
208
|
+
createDateXmp = parsed.xmpDate;
|
|
209
|
+
}
|
|
210
|
+
if (metadata.modified !== undefined) {
|
|
211
|
+
const parsed = parseExplicitDate(metadata.modified, "--modified");
|
|
212
|
+
infoModifyDate = parsed.pdfDate;
|
|
213
|
+
modifyDateXmp = parsed.xmpDate;
|
|
214
|
+
}
|
|
215
|
+
// Acrobat's preflight requires xmp:CreateDate/MetadataDate and, with
|
|
216
|
+
// ModifyDate absent (as with backends like Firefox's cairo), falls back to
|
|
217
|
+
// the creation date — so both dates are always present in the XMP packet.
|
|
218
|
+
createDateXmp ??= toXmpDate(new Date());
|
|
219
|
+
modifyDateXmp ??= createDateXmp;
|
|
162
220
|
|
|
163
221
|
// ── Document information entries ────────────────────────────────────────
|
|
164
222
|
document.setMetaData("info:Producer", metadata.producer);
|
|
@@ -167,6 +225,15 @@ export async function postProcessPdf(pdf: Uint8Array, options: PostProcessOption
|
|
|
167
225
|
if (metadata.author !== undefined) document.setMetaData("info:Author", metadata.author);
|
|
168
226
|
if (metadata.subject !== undefined) document.setMetaData("info:Subject", metadata.subject);
|
|
169
227
|
if (metadata.keywords !== undefined) document.setMetaData("info:Keywords", metadata.keywords);
|
|
228
|
+
// Explicit dates override the ones the print backend wrote (setMetaData
|
|
229
|
+
// replaces the information dictionary, so these run after the entries
|
|
230
|
+
// above and every later access re-fetches its handles).
|
|
231
|
+
if (infoCreationDate !== undefined && infoCreationDate !== creationDate) {
|
|
232
|
+
document.setMetaData("info:CreationDate", infoCreationDate);
|
|
233
|
+
}
|
|
234
|
+
if (infoModifyDate !== undefined && infoModifyDate !== modifyDate) {
|
|
235
|
+
document.setMetaData("info:ModDate", infoModifyDate);
|
|
236
|
+
}
|
|
170
237
|
|
|
171
238
|
// ── Catalog language ────────────────────────────────────────────────────
|
|
172
239
|
const language = metadata.language;
|
|
@@ -231,7 +298,7 @@ export async function postProcessPdf(pdf: Uint8Array, options: PostProcessOption
|
|
|
231
298
|
);
|
|
232
299
|
catalog.put("OutputIntents", [intent]);
|
|
233
300
|
});
|
|
234
|
-
setMinimumPdfVersion(document,
|
|
301
|
+
setMinimumPdfVersion(document, minimumVersionForLabel(label), scope);
|
|
235
302
|
}
|
|
236
303
|
|
|
237
304
|
// ── Standards identification outside the XMP packet ─────────────────────
|
|
@@ -272,9 +339,15 @@ export async function postProcessPdf(pdf: Uint8Array, options: PostProcessOption
|
|
|
272
339
|
|
|
273
340
|
/**
|
|
274
341
|
* Loads the bundled sRGB profile, the default OutputIntent for PDF/A labeling.
|
|
275
|
-
*
|
|
276
|
-
*
|
|
277
|
-
*
|
|
342
|
+
*
|
|
343
|
+
* The profile ships unchanged from Debian's icc-profiles-free package
|
|
344
|
+
* (sources.debian.org, sRGB.icc from the "sRGB IEC61966-2.1" distribution by
|
|
345
|
+
* Hewlett-Packard): a monitor-class ("mntr") RGB profile with the embedded
|
|
346
|
+
* copyright tag, as PDF/A requires (ISO 19005-2, 6.2.3: an OutputIntent
|
|
347
|
+
* profile must be of the output or monitor device class and older than
|
|
348
|
+
* ICC v5). The ICC/HP license permits redistribution provided the file,
|
|
349
|
+
* including its embedded copyright notice tag, is not modified
|
|
350
|
+
* (https://registry.color.org/profile-library/#license).
|
|
278
351
|
*/
|
|
279
352
|
export function loadDefaultIccProfile(): { bytes: Uint8Array; name: string } {
|
|
280
353
|
const moduleDir = dirname(fileURLToPath(import.meta.url));
|
|
@@ -286,7 +359,7 @@ export function loadDefaultIccProfile(): { bytes: Uint8Array; name: string } {
|
|
|
286
359
|
];
|
|
287
360
|
for (const candidate of candidates) {
|
|
288
361
|
if (existsSync(candidate)) {
|
|
289
|
-
return { bytes: readFileSync(candidate), name: "
|
|
362
|
+
return { bytes: readFileSync(candidate), name: "sRGB IEC61966-2.1" };
|
|
290
363
|
}
|
|
291
364
|
}
|
|
292
365
|
throw new Error("Bundled sRGB ICC profile not found (expected at src/render/srgb.icc).");
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// src/render/pdf-validate.ts
|
|
2
|
+
|
|
3
|
+
// Copyright (c) 2026 Christian Mahnke
|
|
4
|
+
// Licensed under the MIT License.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Built-in compliance checks for standards-labeled output (PDF/A, PDF/X).
|
|
8
|
+
*
|
|
9
|
+
* veraPDF implements the full ISO rule sets; this module covers the practical
|
|
10
|
+
* subset a print backend can violate and that the post-processing step is
|
|
11
|
+
* responsible for: the PDF version of the labeled part, the XMP
|
|
12
|
+
* identification, the OutputIntent with an embedded ICC profile, the file
|
|
13
|
+
* identifier, embedded fonts and the absence of JavaScript actions.
|
|
14
|
+
* Run the verapdf binary (see verapdf.ts) when the full rule set matters.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import * as mupdf from "mupdf";
|
|
18
|
+
import { minimumVersionForLabel } from "./pdf-postprocess.js";
|
|
19
|
+
import type { PdfLabel } from "./xmp.js";
|
|
20
|
+
|
|
21
|
+
export type LabelViolation = {
|
|
22
|
+
/** Short identifier of the failed check, e.g. "xmp-identification". */
|
|
23
|
+
check: string;
|
|
24
|
+
detail: string;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** Human-readable label, e.g. "PDF/A-2b" or "PDF/X-4". */
|
|
28
|
+
export function describeLabel(label: PdfLabel): string {
|
|
29
|
+
return label.kind === "pdfa" ? `PDF/A-${label.part}${label.conformance ?? ""}` : `PDF/${label.version}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const decoder = new TextDecoder("utf-8");
|
|
33
|
+
|
|
34
|
+
function decodeStream(stream: mupdf.PDFObject): string {
|
|
35
|
+
return decoder.decode(stream.readStream().asUint8Array());
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** True when the font dictionary carries one of the embedded font file keys. */
|
|
39
|
+
function hasEmbeddedFontFile(fontDescriptor: mupdf.PDFObject): boolean {
|
|
40
|
+
for (const key of ["FontFile", "FontFile2", "FontFile3"]) {
|
|
41
|
+
if (fontDescriptor.get(key).isStream()) return true;
|
|
42
|
+
}
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Checks a single font dictionary; returns a violation detail or null. */
|
|
47
|
+
function checkFont(font: mupdf.PDFObject): string | null {
|
|
48
|
+
const subtype = font.get("Subtype").asName();
|
|
49
|
+
if (subtype === "Type3") {
|
|
50
|
+
// PDF/A (parts 1-3) requires the character procedures of a Type3 font to
|
|
51
|
+
// be embedded streams; PDF/A-4 additionally allows them in the page.
|
|
52
|
+
return font.get("CharProcs").isDictionary() || font.get("CharProcs").isStream() ? null : "Type3 font without CharProcs";
|
|
53
|
+
}
|
|
54
|
+
let descriptor = font.get("FontDescriptor");
|
|
55
|
+
if (subtype === "Type0") {
|
|
56
|
+
const descendants = font.get("DescendantFonts");
|
|
57
|
+
if (!descendants.isArray()) return "Type0 font without DescendantFonts";
|
|
58
|
+
descriptor = descendants.get(0).resolve().get("FontDescriptor");
|
|
59
|
+
} else if (subtype === "CIDFontType0" || subtype === "CIDFontType2") {
|
|
60
|
+
descriptor = font.get("FontDescriptor");
|
|
61
|
+
}
|
|
62
|
+
if (!descriptor.isDictionary()) return `${subtype} font without FontDescriptor`;
|
|
63
|
+
if (!hasEmbeddedFontFile(descriptor)) return `${subtype} font without embedded FontFile`;
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function validateLabeledPdf(pdf: Uint8Array, label: PdfLabel): LabelViolation[] {
|
|
68
|
+
const violations: LabelViolation[] = [];
|
|
69
|
+
const document = mupdf.PDFDocument.openDocument(pdf, "application/pdf") as mupdf.PDFDocument;
|
|
70
|
+
try {
|
|
71
|
+
const trailer = document.getTrailer();
|
|
72
|
+
const catalog = trailer.get("Root");
|
|
73
|
+
|
|
74
|
+
// ── PDF version of the labeled part ───────────────────────────────────
|
|
75
|
+
const minimumVersion = minimumVersionForLabel(label);
|
|
76
|
+
if (document.getVersion() < minimumVersion) {
|
|
77
|
+
violations.push({
|
|
78
|
+
check: "pdf-version",
|
|
79
|
+
detail: `document is PDF ${Math.trunc(document.getVersion() / 10)}.${document.getVersion() % 10}, ${describeLabel(label)} requires at least ${Math.trunc(minimumVersion / 10)}.${minimumVersion % 10}`
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// ── XMP metadata stream with the standards identification ─────────────
|
|
84
|
+
// get() follows indirect references already; resolve() would hide the
|
|
85
|
+
// stream-ness of the handle (see the post-processing test comment).
|
|
86
|
+
const metadataStream = catalog.get("Metadata");
|
|
87
|
+
let xmp = "";
|
|
88
|
+
if (!metadataStream.isStream()) {
|
|
89
|
+
violations.push({ check: "xmp-metadata", detail: "catalog has no Metadata stream" });
|
|
90
|
+
} else {
|
|
91
|
+
xmp = decodeStream(metadataStream);
|
|
92
|
+
if (label.kind === "pdfa") {
|
|
93
|
+
if (!xmp.includes(`<pdfaid:part>${label.part}</pdfaid:part>`)) {
|
|
94
|
+
violations.push({ check: "xmp-identification", detail: `XMP is missing <pdfaid:part>${label.part}` });
|
|
95
|
+
}
|
|
96
|
+
if (
|
|
97
|
+
label.conformance !== undefined &&
|
|
98
|
+
!xmp.includes(`<pdfaid:conformance>${label.conformance.toUpperCase()}</pdfaid:conformance>`)
|
|
99
|
+
) {
|
|
100
|
+
violations.push({ check: "xmp-identification", detail: `XMP is missing <pdfaid:conformance>${label.conformance.toUpperCase()}` });
|
|
101
|
+
}
|
|
102
|
+
} else if (label.version === "X-4" && !xmp.includes("<pdfxid:GTS_PDFXVersion>PDF/X-4</pdfxid:GTS_PDFXVersion>")) {
|
|
103
|
+
violations.push({ check: "xmp-identification", detail: "XMP is missing the PDF/X-4 GTS_PDFXVersion" });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ── OutputIntent with an embedded ICC profile ──────────────────────────
|
|
108
|
+
if (label.kind === "pdfa" || label.version === "X-4") {
|
|
109
|
+
const intents = catalog.get("OutputIntents");
|
|
110
|
+
if (!intents.isArray() || intents.length < 1) {
|
|
111
|
+
violations.push({ check: "output-intent", detail: "catalog has no OutputIntents array" });
|
|
112
|
+
} else {
|
|
113
|
+
const intent = intents.get(0);
|
|
114
|
+
const expectedS = label.kind === "pdfa" ? "GTS_PDFA1" : "GTS_PDFX";
|
|
115
|
+
if (!intent.get("S").asName()?.startsWith(expectedS)) {
|
|
116
|
+
violations.push({ check: "output-intent", detail: `OutputIntent /S is not ${expectedS}` });
|
|
117
|
+
}
|
|
118
|
+
// MuPDF's PDFObject.resolve() does not surface stream-ness for
|
|
119
|
+
// indirect refs, so the embedded profile is checked through its
|
|
120
|
+
// stream data (same approach as the post-processing tests).
|
|
121
|
+
let profileReadable = false;
|
|
122
|
+
try {
|
|
123
|
+
profileReadable = intent.get("DestOutputProfile").readStream().asUint8Array().length > 0;
|
|
124
|
+
} catch {
|
|
125
|
+
profileReadable = false;
|
|
126
|
+
}
|
|
127
|
+
if (!profileReadable) {
|
|
128
|
+
violations.push({ check: "output-intent", detail: "OutputIntent has no embedded DestOutputProfile" });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ── File identifier (required for PDF/A and PDF/X) ──────────────────────
|
|
134
|
+
const fileId = trailer.get("ID");
|
|
135
|
+
if (!fileId.isArray() || fileId.length < 2) {
|
|
136
|
+
violations.push({ check: "file-identifier", detail: "trailer /ID pair missing" });
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// ── Fonts embedded ──────────────────────────────────────────────────────
|
|
140
|
+
const pageCount = document.countPages();
|
|
141
|
+
for (let index = 0; index < pageCount; index++) {
|
|
142
|
+
const page = document.loadPage(index);
|
|
143
|
+
try {
|
|
144
|
+
const fonts = page.getObject().get("Resources").resolve().get("Font");
|
|
145
|
+
if (!fonts.isDictionary()) continue;
|
|
146
|
+
fonts.forEach((fontRef) => {
|
|
147
|
+
const font = fontRef.resolve();
|
|
148
|
+
if (!font.isDictionary()) return;
|
|
149
|
+
const failure = checkFont(font);
|
|
150
|
+
if (failure !== null) violations.push({ check: "font-embedded", detail: `page ${index + 1}: ${failure}` });
|
|
151
|
+
});
|
|
152
|
+
} finally {
|
|
153
|
+
page.destroy();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ── No JavaScript actions ────────────────────────────────────────────────
|
|
158
|
+
const names = catalog.get("Names");
|
|
159
|
+
if (names.isDictionary() && names.get("JavaScript").isDictionary()) {
|
|
160
|
+
violations.push({ check: "no-javascript", detail: "document name tree contains JavaScript actions" });
|
|
161
|
+
}
|
|
162
|
+
const openAction = catalog.get("OpenAction");
|
|
163
|
+
if (openAction.isDictionary() && openAction.get("S").asName() === "JavaScript") {
|
|
164
|
+
violations.push({ check: "no-javascript", detail: "OpenAction is a JavaScript action" });
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// ── Information dictionary / XMP consistency ────────────────────────────
|
|
168
|
+
const info = trailer.get("Info");
|
|
169
|
+
if (info.isDictionary()) {
|
|
170
|
+
if (info.get("Title").isString() && xmp !== "" && !xmp.includes("<dc:title>")) {
|
|
171
|
+
violations.push({ check: "metadata-consistency", detail: "information dictionary has a Title but the XMP packet lacks dc:title" });
|
|
172
|
+
}
|
|
173
|
+
if (info.get("Author").isString() && xmp !== "" && !xmp.includes("<dc:creator>")) {
|
|
174
|
+
violations.push({
|
|
175
|
+
check: "metadata-consistency",
|
|
176
|
+
detail: "information dictionary has an Author but the XMP packet lacks dc:creator"
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return violations;
|
|
182
|
+
} finally {
|
|
183
|
+
document.destroy();
|
|
184
|
+
}
|
|
185
|
+
}
|
package/src/render/pdf.ts
CHANGED
|
@@ -22,6 +22,8 @@ import { PDFDocument } from "pdf-lib";
|
|
|
22
22
|
import log from "loglevel";
|
|
23
23
|
import { chromeArgs, resolveBrowserExecutable } from "./chrome.js";
|
|
24
24
|
import { postProcessPdf } from "./pdf-postprocess.js";
|
|
25
|
+
import { describeLabel, validateLabeledPdf } from "./pdf-validate.js";
|
|
26
|
+
import { runVeraPdf } from "./verapdf.js";
|
|
25
27
|
import type { PdfLabel } from "./xmp.js";
|
|
26
28
|
|
|
27
29
|
export type ViewerParams = Record<string, string | number | boolean | undefined>;
|
|
@@ -52,8 +54,16 @@ export type RenderPdfRequest = {
|
|
|
52
54
|
subject?: string;
|
|
53
55
|
keywords?: string;
|
|
54
56
|
language?: string;
|
|
57
|
+
/** ISO 8601 creation date; overrides the one the print backend wrote. */
|
|
58
|
+
created?: string;
|
|
59
|
+
/** ISO 8601 modification date; overrides the one the print backend wrote. */
|
|
60
|
+
modified?: string;
|
|
55
61
|
/** Standards labeling applied to the printed PDF (PDF/A or PDF/X). */
|
|
56
62
|
pdfLabel?: PdfLabel;
|
|
63
|
+
/** Run the built-in compliance checks for the label (default: on). */
|
|
64
|
+
validate?: boolean;
|
|
65
|
+
/** Additionally run the verapdf binary against the output. */
|
|
66
|
+
verapdf?: boolean;
|
|
57
67
|
/** ICC profile embedded as the OutputIntent; required whenever a label is set. */
|
|
58
68
|
iccProfile?: Uint8Array;
|
|
59
69
|
iccProfileName?: string;
|
|
@@ -92,6 +102,8 @@ function pdfMetadata(request: RenderPdfRequest) {
|
|
|
92
102
|
...(request.subject === undefined ? {} : { subject: request.subject }),
|
|
93
103
|
...(request.keywords === undefined ? {} : { keywords: request.keywords }),
|
|
94
104
|
...(request.language === undefined ? {} : { language: request.language }),
|
|
105
|
+
...(request.created === undefined ? {} : { created: request.created }),
|
|
106
|
+
...(request.modified === undefined ? {} : { modified: request.modified }),
|
|
95
107
|
creator: TOOL_IDENTITY,
|
|
96
108
|
producer: TOOL_IDENTITY
|
|
97
109
|
};
|
|
@@ -446,14 +458,32 @@ export async function renderPdf(request: RenderPdfRequest): Promise<RenderPdfRes
|
|
|
446
458
|
});
|
|
447
459
|
|
|
448
460
|
if (request.waitForSettle === true) {
|
|
461
|
+
// The gate image keeps the viewer's document processing pending until
|
|
462
|
+
// the settle fires; only then does vivliostyle drain the deferred and
|
|
463
|
+
// module scripts it queued (end-of-document execution) and dispatch
|
|
464
|
+
// DOMContentLoaded. Pages that depend on those late globals flip
|
|
465
|
+
// __vivReady after the gate settled, so hold print briefly for them.
|
|
466
|
+
const POST_SETTLE_READY_GRACE_MS = 2000;
|
|
467
|
+
let settledAt = -1;
|
|
449
468
|
const handle = await page.waitForFunction(
|
|
450
469
|
() => {
|
|
451
470
|
const settleState = (window as { __vivSettle?: { done?: boolean; reason?: string; at?: number } }).__vivSettle;
|
|
452
471
|
// Pages with mocked/measured async work set __vivReady when painted;
|
|
453
472
|
// Vivliostyle re-runs document scripts in the viewer context, so both
|
|
454
473
|
// live on the same window the renderer polls here.
|
|
455
|
-
const
|
|
456
|
-
if (
|
|
474
|
+
const readyState = (window as { __vivReady?: boolean }).__vivReady;
|
|
475
|
+
if (readyState === true) return { reason: "ready", at: 0 };
|
|
476
|
+
// An explicit not-ready beats a settled gate: quietness alone must
|
|
477
|
+
// not print the pre-paint DOM (async tails emit no network signal).
|
|
478
|
+
if (readyState === false) {
|
|
479
|
+
if (settleState?.done === true) {
|
|
480
|
+
if (settledAt < 0) settledAt = Date.now();
|
|
481
|
+
if (Date.now() - settledAt >= POST_SETTLE_READY_GRACE_MS) {
|
|
482
|
+
return { reason: settleState.reason ?? "settled", at: settleState.at ?? 0 };
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return false;
|
|
486
|
+
}
|
|
457
487
|
return settleState?.done === true ? { reason: settleState.reason ?? "settled", at: settleState.at ?? 0 } : false;
|
|
458
488
|
},
|
|
459
489
|
{ polling: 200, timeout: timeoutMs }
|
|
@@ -492,9 +522,33 @@ export async function renderPdf(request: RenderPdfRequest): Promise<RenderPdfRes
|
|
|
492
522
|
...(request.pdfLabel === undefined ? {} : { label: request.pdfLabel }),
|
|
493
523
|
...(request.iccProfile === undefined ? {} : { iccProfile: request.iccProfile, iccProfileName: request.iccProfileName })
|
|
494
524
|
});
|
|
525
|
+
if (request.pdfLabel !== undefined && request.validate !== false) {
|
|
526
|
+
const violations = validateLabeledPdf(stamped, request.pdfLabel);
|
|
527
|
+
if (violations.length > 0) {
|
|
528
|
+
throw new Error(
|
|
529
|
+
`${describeLabel(request.pdfLabel)} label failed validation, refusing to write a non-conforming output:\n` +
|
|
530
|
+
violations.map((violation) => ` - ${violation.check}: ${violation.detail}`).join("\n")
|
|
531
|
+
);
|
|
532
|
+
}
|
|
533
|
+
log.info(`[pdf] built-in ${describeLabel(request.pdfLabel)} validation passed`);
|
|
534
|
+
}
|
|
495
535
|
mkdirSync(dirname(request.output), { recursive: true });
|
|
496
536
|
writeFileSync(request.output, stamped);
|
|
497
537
|
|
|
538
|
+
if (request.verapdf === true && request.pdfLabel !== undefined) {
|
|
539
|
+
const vera = runVeraPdf(request.output, request.pdfLabel);
|
|
540
|
+
if (!vera.ran) {
|
|
541
|
+
throw new Error(
|
|
542
|
+
`--verapdf was requested, but veraPDF could not be run: ${vera.reason}. ` +
|
|
543
|
+
"Install veraPDF (https://verapdf.org/, requires Java) or drop --verapdf."
|
|
544
|
+
);
|
|
545
|
+
} else if (vera.passed !== true) {
|
|
546
|
+
throw new Error(`verapdf reports ${describeLabel(request.pdfLabel)} violations (exit ${vera.exitCode ?? "n/a"}):\n${vera.output}`);
|
|
547
|
+
} else {
|
|
548
|
+
log.info(`[pdf] verapdf reports ${describeLabel(request.pdfLabel)} conformance: PASS`);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
498
552
|
const pageCount = await PDFDocument.load(stamped).then((doc) => doc.getPageCount());
|
|
499
553
|
|
|
500
554
|
return { output: request.output, bytes: stamped.length, pageCount, settle };
|
package/src/render/srgb.icc
CHANGED
|
Binary file
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// src/render/verapdf.ts
|
|
2
|
+
|
|
3
|
+
// Copyright (c) 2026 Christian Mahnke
|
|
4
|
+
// Licensed under the MIT License.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Optional pass-through to the verapdf binary (https://verapdf.org/), which
|
|
8
|
+
* implements the full ISO conformance rule sets for PDF/A and PDF/X. The
|
|
9
|
+
* binary must be on the PATH; it is never bundled because it needs a Java
|
|
10
|
+
* runtime. Only invoked on explicit request (--verapdf).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { spawnSync } from "node:child_process";
|
|
14
|
+
import type { PdfLabel } from "./xmp.js";
|
|
15
|
+
|
|
16
|
+
export type VeraPdfResult = {
|
|
17
|
+
/** Whether the binary actually ran. */
|
|
18
|
+
ran: boolean;
|
|
19
|
+
/** Validation outcome; undefined when the binary could not be started. */
|
|
20
|
+
passed?: boolean;
|
|
21
|
+
exitCode?: number | null;
|
|
22
|
+
output?: string;
|
|
23
|
+
reason?: string;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** Maps a standards label onto a veraPDF --flavour value. */
|
|
27
|
+
export function veraPdfFlavour(label: PdfLabel): string {
|
|
28
|
+
if (label.kind === "pdfa") {
|
|
29
|
+
return label.part === "4" ? "4" : `${label.part}${label.conformance ?? ""}`;
|
|
30
|
+
}
|
|
31
|
+
return label.version === "X-4" ? "X-4" : "X-1a";
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function runVeraPdf(pdfPath: string, label: PdfLabel): VeraPdfResult {
|
|
35
|
+
const flavour = veraPdfFlavour(label);
|
|
36
|
+
let result: ReturnType<typeof spawnSync>;
|
|
37
|
+
try {
|
|
38
|
+
result = spawnSync("verapdf", ["--flavour", flavour, "--format", "text", pdfPath], {
|
|
39
|
+
encoding: "utf-8",
|
|
40
|
+
timeout: 120_000
|
|
41
|
+
});
|
|
42
|
+
} catch (error) {
|
|
43
|
+
return { ran: false, reason: error instanceof Error ? error.message : String(error) };
|
|
44
|
+
}
|
|
45
|
+
if (result.error !== undefined) {
|
|
46
|
+
const code = (result.error as NodeJS.ErrnoException).code;
|
|
47
|
+
return {
|
|
48
|
+
ran: false,
|
|
49
|
+
reason: code === "ENOENT" ? "verapdf binary not found on PATH" : String(result.error)
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
const stdout = typeof result.stdout === "string" ? result.stdout : "";
|
|
53
|
+
const stderr = typeof result.stderr === "string" ? result.stderr : "";
|
|
54
|
+
const output = `${stdout}${stderr}`.slice(0, 4000);
|
|
55
|
+
return { ran: true, passed: /\bPASS\b/.test(stdout), exitCode: result.status, output };
|
|
56
|
+
}
|
package/src/render/xmp.ts
CHANGED
|
@@ -89,6 +89,18 @@ export function pdfDateToXmpDate(value: string): string | undefined {
|
|
|
89
89
|
return `${year}-${month}-${day}T${hour}:${minute}:${second}${zone}`;
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
+
// The inverse of the PDF date form above: XMP Part 1, 8.2.1.2 date.
|
|
93
|
+
const XMP_DATE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+\-]\d{2}:\d{2})$/;
|
|
94
|
+
|
|
95
|
+
/** Reformats an XMP date string as a PDF date; `undefined` when not one. */
|
|
96
|
+
export function xmpDateToPdfDate(value: string): string | undefined {
|
|
97
|
+
const match = XMP_DATE.exec(value);
|
|
98
|
+
if (match === null) return undefined;
|
|
99
|
+
const [, year, month, day, hour, minute, second, zone] = match;
|
|
100
|
+
const offset = zone === "Z" ? "Z" : `${zone.slice(0, 3)}'${zone.slice(4, 6)}`;
|
|
101
|
+
return `D:${year}${month}${day}${hour}${minute}${second}${offset}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
92
104
|
function xmlEscape(text: string): string {
|
|
93
105
|
return text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
94
106
|
}
|