@projektemacher/vivliostyle-batch-cli 0.2.0 → 0.3.1
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 +47 -26
- package/dist/index.d.ts +108 -1
- package/dist/vivliostyle-batch-cli.js +1339 -46
- package/package.json +23 -19
- package/scripts/convert-docs-pdf.mjs +520 -0
- package/src/metadata.ts +162 -0
- package/src/render/pdf-postprocess.ts +366 -0
- package/src/render/pdf-validate.ts +185 -0
- package/src/render/pdf.ts +254 -23
- package/src/render/srgb.icc +0 -0
- package/src/render/verapdf.ts +56 -0
- package/src/render/xmp.ts +195 -0
- package/src/server.ts +18 -1
- package/src/vivliostyle-cli.ts +369 -18
|
@@ -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
|
@@ -9,6 +9,10 @@
|
|
|
9
9
|
* The viewer page is served by our own static server (see src/server.ts), so
|
|
10
10
|
* the document's origin — and therefore the base URI of the scripts the page
|
|
11
11
|
* runs — is the site we serve, not an internal viewer base.
|
|
12
|
+
*
|
|
13
|
+
* Printed pages run through the post-processing step (see
|
|
14
|
+
* src/render/pdf-postprocess.ts), which stamps the document metadata and
|
|
15
|
+
* applies the requested PDF/A or PDF/X labeling.
|
|
12
16
|
*/
|
|
13
17
|
|
|
14
18
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
@@ -17,6 +21,10 @@ import puppeteer from "puppeteer-core";
|
|
|
17
21
|
import { PDFDocument } from "pdf-lib";
|
|
18
22
|
import log from "loglevel";
|
|
19
23
|
import { chromeArgs, resolveBrowserExecutable } from "./chrome.js";
|
|
24
|
+
import { postProcessPdf } from "./pdf-postprocess.js";
|
|
25
|
+
import { describeLabel, validateLabeledPdf } from "./pdf-validate.js";
|
|
26
|
+
import { runVeraPdf } from "./verapdf.js";
|
|
27
|
+
import type { PdfLabel } from "./xmp.js";
|
|
20
28
|
|
|
21
29
|
export type ViewerParams = Record<string, string | number | boolean | undefined>;
|
|
22
30
|
|
|
@@ -46,6 +54,19 @@ export type RenderPdfRequest = {
|
|
|
46
54
|
subject?: string;
|
|
47
55
|
keywords?: string;
|
|
48
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;
|
|
61
|
+
/** Standards labeling applied to the printed PDF (PDF/A or PDF/X). */
|
|
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;
|
|
67
|
+
/** ICC profile embedded as the OutputIntent; required whenever a label is set. */
|
|
68
|
+
iccProfile?: Uint8Array;
|
|
69
|
+
iccProfileName?: string;
|
|
49
70
|
/** Hard limit for the whole render. */
|
|
50
71
|
timeoutMs?: number;
|
|
51
72
|
/** Wait for the page to report that it settled before printing. */
|
|
@@ -71,20 +92,21 @@ export type RenderPdfResult = {
|
|
|
71
92
|
|
|
72
93
|
const DEFAULT_TIMEOUT_MS = 300_000;
|
|
73
94
|
|
|
74
|
-
/**
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
95
|
+
/** The wrapper owns the producer/creator entries of every PDF it prints. */
|
|
96
|
+
const TOOL_IDENTITY = "vivliostyle-batch-cli";
|
|
97
|
+
|
|
98
|
+
function pdfMetadata(request: RenderPdfRequest) {
|
|
99
|
+
return {
|
|
100
|
+
...(request.title === undefined ? {} : { title: request.title }),
|
|
101
|
+
...(request.author === undefined ? {} : { author: request.author }),
|
|
102
|
+
...(request.subject === undefined ? {} : { subject: request.subject }),
|
|
103
|
+
...(request.keywords === undefined ? {} : { keywords: request.keywords }),
|
|
104
|
+
...(request.language === undefined ? {} : { language: request.language }),
|
|
105
|
+
...(request.created === undefined ? {} : { created: request.created }),
|
|
106
|
+
...(request.modified === undefined ? {} : { modified: request.modified }),
|
|
107
|
+
creator: TOOL_IDENTITY,
|
|
108
|
+
producer: TOOL_IDENTITY
|
|
109
|
+
};
|
|
88
110
|
}
|
|
89
111
|
|
|
90
112
|
type SettleState = { reason: string; at: number };
|
|
@@ -98,9 +120,13 @@ export type FrameRenderCapability = {
|
|
|
98
120
|
webgpu: boolean;
|
|
99
121
|
canvasCount: number;
|
|
100
122
|
canvases: string;
|
|
101
|
-
iframeCount: number;
|
|
123
|
+
iframeCount: number | null;
|
|
102
124
|
dpr: number;
|
|
103
125
|
resized: string | null;
|
|
126
|
+
/** A-Frame scenes materialized into 2D overlay canvases for print. */
|
|
127
|
+
materialized?: number;
|
|
128
|
+
/** Scene-graph state at print time (debug aid). */
|
|
129
|
+
sceneDiag?: string | null;
|
|
104
130
|
};
|
|
105
131
|
|
|
106
132
|
/**
|
|
@@ -130,8 +156,179 @@ export function buildFrameProbeScript(factor: number): string {
|
|
|
130
156
|
try { window.__vivResize(factor); } catch(e){ resized = "error:"+String(e); }
|
|
131
157
|
}
|
|
132
158
|
try { window.dispatchEvent(new Event("resize")); } catch(e){}
|
|
159
|
+
// Bridge the viewer's broken page lifecycle. A-Frame scenes can end up
|
|
160
|
+
// loaded-but-never-playing in the paginated tree (render loop, default
|
|
161
|
+
// lights and asset loads all missed their window) while the same page
|
|
162
|
+
// renders fine in a real browser. Start the scene's own loop and give
|
|
163
|
+
// collapsed scenes a box (their display:block stylesheet does not reach
|
|
164
|
+
// the re-parented tree, so unsized unknown elements stay inline).
|
|
165
|
+
try {
|
|
166
|
+
var bridgeScenes = document.querySelectorAll("a-scene");
|
|
167
|
+
for (var bi = 0; bi < bridgeScenes.length; bi++) {
|
|
168
|
+
var bridgeScene = bridgeScenes[bi];
|
|
169
|
+
if (!bridgeScene.isPlaying && typeof bridgeScene.play === "function") {
|
|
170
|
+
try { bridgeScene.play(); } catch (e) {}
|
|
171
|
+
}
|
|
172
|
+
if (bridgeScene.clientWidth === 0 || bridgeScene.clientHeight === 0) {
|
|
173
|
+
var sized = bridgeScene.parentElement;
|
|
174
|
+
while (sized && (sized.clientWidth === 0 || sized.clientHeight === 0)) sized = sized.parentElement;
|
|
175
|
+
if (sized) {
|
|
176
|
+
bridgeScene.style.display = "block";
|
|
177
|
+
bridgeScene.style.width = sized.clientWidth + "px";
|
|
178
|
+
bridgeScene.style.height = sized.clientHeight + "px";
|
|
179
|
+
if (typeof bridgeScene.resize === "function") bridgeScene.resize();
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
await nextFrame();
|
|
184
|
+
} catch(e){}
|
|
185
|
+
// Give each scene what it needs to render like the browser does, then
|
|
186
|
+
// materialize its WebGL canvas into a 2D overlay (2D canvases always
|
|
187
|
+
// survive print-to-PDF): re-kick unloaded assets, swap unlit materials for
|
|
188
|
+
// flat ones when no lights exist, render, and blit synchronously.
|
|
189
|
+
var materialized = 0;
|
|
190
|
+
var sceneDiag = "";
|
|
191
|
+
try {
|
|
192
|
+
var scenes = document.querySelectorAll("a-scene");
|
|
193
|
+
for (var si = 0; si < scenes.length; si++) {
|
|
194
|
+
var sceneEl = scenes[si];
|
|
195
|
+
// The viewer clones scenes into its page boxes; only the VISIBLE one
|
|
196
|
+
// (with a box) is what the PDF will show. The hidden original's render
|
|
197
|
+
// would materialize nothing.
|
|
198
|
+
if (!(sceneEl.clientWidth > 0 && sceneEl.clientHeight > 0)) continue;
|
|
199
|
+
if (!sceneEl.renderer || !sceneEl.camera) continue;
|
|
200
|
+
try {
|
|
201
|
+
var gltfEl = sceneEl.querySelector("[gltf-model]");
|
|
202
|
+
if (gltfEl) {
|
|
203
|
+
var gmObj = gltfEl.object3D;
|
|
204
|
+
sceneDiag += " gmKids=" + gmObj.children.length + "/" + (gltfEl.components["gltf-model"] ? String(gltfEl.components["gltf-model"].model !== null) : "nocomp");
|
|
205
|
+
}
|
|
206
|
+
sceneDiag += " tree=" + sceneEl.object3D.children.map(function (c) { return c.type + (c.children ? ":" + c.children.length : ""); }).join("|").slice(0, 110);
|
|
207
|
+
} catch (e) {
|
|
208
|
+
sceneDiag += " diagErr " + String(e).slice(0, 50);
|
|
209
|
+
}
|
|
210
|
+
try {
|
|
211
|
+
var assetItems = sceneEl.querySelectorAll("a-asset-item");
|
|
212
|
+
var assetWaits = [];
|
|
213
|
+
for (var ai = 0; ai < assetItems.length; ai++) {
|
|
214
|
+
var assetEl = assetItems[ai];
|
|
215
|
+
if (assetEl.hasLoaded) continue;
|
|
216
|
+
assetWaits.push(
|
|
217
|
+
new Promise(function (resolve) {
|
|
218
|
+
var settled = false;
|
|
219
|
+
var finish = function () {
|
|
220
|
+
if (settled) return;
|
|
221
|
+
settled = true;
|
|
222
|
+
resolve();
|
|
223
|
+
};
|
|
224
|
+
assetEl.addEventListener("loaded", finish, { once: true });
|
|
225
|
+
assetEl.addEventListener("error", finish, { once: true });
|
|
226
|
+
setTimeout(finish, 8000);
|
|
227
|
+
var src = assetEl.getAttribute("src");
|
|
228
|
+
if (src) assetEl.setAttribute("src", src);
|
|
229
|
+
})
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
if (assetWaits.length > 0) {
|
|
233
|
+
await Promise.race([Promise.all(assetWaits), new Promise(function (r) { setTimeout(r, 9000); })]);
|
|
234
|
+
}
|
|
235
|
+
} catch (e) {}
|
|
236
|
+
try {
|
|
237
|
+
var lightsFound = 0;
|
|
238
|
+
sceneEl.object3D.traverse(function (n) { if (n.isLight) lightsFound++; });
|
|
239
|
+
if (lightsFound === 0) {
|
|
240
|
+
var basicCtor = null;
|
|
241
|
+
sceneEl.object3D.traverse(function (n) {
|
|
242
|
+
if (n.isMesh && n.material && n.material.isMeshBasicMaterial && basicCtor === null) basicCtor = n.material.constructor;
|
|
243
|
+
});
|
|
244
|
+
if (basicCtor) {
|
|
245
|
+
sceneEl.object3D.traverse(function (n) {
|
|
246
|
+
if (!n.isMesh || !n.material || n.material.isMeshBasicMaterial) return;
|
|
247
|
+
try {
|
|
248
|
+
var m = n.material;
|
|
249
|
+
var flat = new basicCtor({ color: m.color ? m.color.clone() : undefined });
|
|
250
|
+
flat.side = m.side;
|
|
251
|
+
flat.transparent = m.transparent;
|
|
252
|
+
flat.opacity = m.opacity;
|
|
253
|
+
if (m.map) flat.map = m.map;
|
|
254
|
+
n.material = flat;
|
|
255
|
+
} catch (e) {}
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
} catch(e){}
|
|
260
|
+
try {
|
|
261
|
+
sceneEl.renderer.render(sceneEl.object3D, sceneEl.camera);
|
|
262
|
+
var glCanvas = sceneEl.canvas;
|
|
263
|
+
if (!glCanvas || glCanvas.width === 0 || glCanvas.height === 0) continue;
|
|
264
|
+
var overlay = document.createElement("canvas");
|
|
265
|
+
overlay.setAttribute("data-viv-gl-overlay", "");
|
|
266
|
+
overlay.width = glCanvas.width;
|
|
267
|
+
overlay.height = glCanvas.height;
|
|
268
|
+
overlay.style.position = "absolute";
|
|
269
|
+
overlay.style.pointerEvents = "none";
|
|
270
|
+
overlay.style.width = glCanvas.clientWidth + "px";
|
|
271
|
+
overlay.style.height = glCanvas.clientHeight + "px";
|
|
272
|
+
var cr = glCanvas.getBoundingClientRect();
|
|
273
|
+
var pr = (glCanvas.offsetParent || document.body).getBoundingClientRect();
|
|
274
|
+
overlay.style.left = cr.left - pr.left + "px";
|
|
275
|
+
overlay.style.top = cr.top - pr.top + "px";
|
|
276
|
+
overlay.style.zIndex = "1";
|
|
277
|
+
(glCanvas.parentNode || document.body).appendChild(overlay);
|
|
278
|
+
overlay.getContext("2d").drawImage(glCanvas, 0, 0);
|
|
279
|
+
// Empty capture = the scene never initialized in this tree (its
|
|
280
|
+
// framework lifecycle was lost to the viewer's re-parenting). Replace
|
|
281
|
+
// it with a fresh copy: the custom-element upgrade re-runs the full
|
|
282
|
+
// framework lifecycle (assets, lights, render loop) in the now-sized
|
|
283
|
+
// tree.
|
|
284
|
+
var empty = true;
|
|
285
|
+
try {
|
|
286
|
+
var dd = overlay.getContext("2d").getImageData(0, 0, overlay.width, overlay.height).data;
|
|
287
|
+
for (var di = 3; di < dd.length; di += 256) {
|
|
288
|
+
if (dd[di] > 0) {
|
|
289
|
+
empty = false;
|
|
290
|
+
break;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
} catch (e) {
|
|
294
|
+
empty = false;
|
|
295
|
+
}
|
|
296
|
+
if (empty) {
|
|
297
|
+
var fresh = sceneEl.cloneNode(true);
|
|
298
|
+
sceneEl.parentNode.replaceChild(fresh, sceneEl);
|
|
299
|
+
sceneEl = fresh;
|
|
300
|
+
// Enough time for the fresh scene's asset fetches (a real GLB over
|
|
301
|
+
// the network) + first renders.
|
|
302
|
+
await new Promise(function (r) {
|
|
303
|
+
setTimeout(r, 8000);
|
|
304
|
+
});
|
|
305
|
+
if (!sceneEl.renderer || !sceneEl.camera) continue;
|
|
306
|
+
}
|
|
307
|
+
sceneEl.renderer.render(sceneEl.object3D, sceneEl.camera);
|
|
308
|
+
var gl2 = sceneEl.canvas;
|
|
309
|
+
if (!gl2 || gl2.width === 0 || gl2.height === 0) continue;
|
|
310
|
+
overlay.width = gl2.width;
|
|
311
|
+
overlay.height = gl2.height;
|
|
312
|
+
overlay.getContext("2d").drawImage(gl2, 0, 0);
|
|
313
|
+
materialized++;
|
|
314
|
+
try {
|
|
315
|
+
var od = overlay.getContext("2d").getImageData(0, 0, overlay.width, overlay.height).data;
|
|
316
|
+
var alphaN = 0;
|
|
317
|
+
var orangeN = 0;
|
|
318
|
+
for (var oi = 3; oi < od.length; oi += 16) {
|
|
319
|
+
if (od[oi] > 0) alphaN++;
|
|
320
|
+
if (od[oi - 3] > 150 && od[oi - 2] > 60 && od[oi - 2] < 200 && od[oi - 1] < 110 && od[oi - 3] > od[oi - 2] + 40) orangeN++;
|
|
321
|
+
}
|
|
322
|
+
glSample = [alphaN, orangeN];
|
|
323
|
+
} catch (e) {}
|
|
324
|
+
} catch (e) {}
|
|
325
|
+
}
|
|
326
|
+
} catch(e){}
|
|
133
327
|
// Hooks like echarts re-init dispose the canvas synchronously; let layout
|
|
134
328
|
// settle a frame before measuring so sizes reflect the repainted state.
|
|
329
|
+
// This also lets render loops refill their drawing buffers after the
|
|
330
|
+
// resize above — drawImage on a just-resized WebGL canvas would read the
|
|
331
|
+
// cleared buffer.
|
|
135
332
|
try { await nextFrame(); } catch(e){}
|
|
136
333
|
if (resized === null && factor > 1 && typeof window.__vivResize === "function") resized = canvasSizes();
|
|
137
334
|
var webgl = false, webgl2 = false;
|
|
@@ -150,7 +347,9 @@ export function buildFrameProbeScript(factor: number): string {
|
|
|
150
347
|
canvasCount: document.querySelectorAll("canvas").length, canvases: canvasSizes(),
|
|
151
348
|
iframeCount: document.querySelectorAll("iframe").length,
|
|
152
349
|
dpr: typeof window.devicePixelRatio === "number" ? window.devicePixelRatio : 1,
|
|
153
|
-
resized: resized
|
|
350
|
+
resized: resized,
|
|
351
|
+
materialized: materialized,
|
|
352
|
+
sceneDiag: sceneDiag
|
|
154
353
|
};
|
|
155
354
|
})(${JSON.stringify(factor)})`;
|
|
156
355
|
}
|
|
@@ -158,7 +357,7 @@ export function buildFrameProbeScript(factor: number): string {
|
|
|
158
357
|
/** Best-effort capability + HiDPI pass over every frame before `page.pdf()`. */
|
|
159
358
|
export async function prepareForPrint(
|
|
160
359
|
page: {
|
|
161
|
-
frames: () => Array<{ evaluate: (script: string) => Promise<unknown> }>;
|
|
360
|
+
frames: () => Array<{ url?: () => string; evaluate: (script: string) => Promise<unknown> }>;
|
|
162
361
|
},
|
|
163
362
|
options: { canvasScale?: number; settleMs?: number } = {}
|
|
164
363
|
): Promise<FrameRenderCapability[]> {
|
|
@@ -169,8 +368,9 @@ export async function prepareForPrint(
|
|
|
169
368
|
for (const frame of page.frames()) {
|
|
170
369
|
try {
|
|
171
370
|
out.push((await frame.evaluate(script)) as FrameRenderCapability);
|
|
172
|
-
} catch {
|
|
371
|
+
} catch (err) {
|
|
173
372
|
// Cross-origin embeds that refuse evaluation still print as pixels.
|
|
373
|
+
log.trace("frame probe failed", frame.url?.() ?? "(frame)", err instanceof Error ? err.message : String(err));
|
|
174
374
|
continue;
|
|
175
375
|
}
|
|
176
376
|
}
|
|
@@ -183,12 +383,13 @@ export async function prepareForPrint(
|
|
|
183
383
|
/** One-line summary for logs: capabilities per frame that owns content. */
|
|
184
384
|
export function summarizeCapabilities(caps: FrameRenderCapability[]): string {
|
|
185
385
|
return caps
|
|
186
|
-
.filter((c) => c.canvasCount > 0 || c.iframeCount > 0 || c.fixture !== null)
|
|
386
|
+
.filter((c) => c.canvasCount > 0 || (c.iframeCount ?? 0) > 0 || c.fixture !== null)
|
|
187
387
|
.map(
|
|
188
388
|
(c) =>
|
|
189
389
|
`${c.fixture ?? c.url} canvases=[${c.canvases}] iframes=${c.iframeCount} ` +
|
|
190
390
|
`webgl=${String(c.webgl)}/2=${String(c.webgl2)} webgpu=${String(c.webgpu)}` +
|
|
191
|
-
(c.resized !== null ? ` resized=[${c.resized}]` : "")
|
|
391
|
+
(c.resized !== null ? ` resized=[${c.resized}]` : "") +
|
|
392
|
+
(c.materialized ? ` materialized=${c.materialized} ${c.sceneDiag ?? ""}` : "")
|
|
192
393
|
)
|
|
193
394
|
.join(" | ");
|
|
194
395
|
}
|
|
@@ -228,11 +429,16 @@ export async function renderPdf(request: RenderPdfRequest): Promise<RenderPdfRes
|
|
|
228
429
|
|
|
229
430
|
page.on("pageerror", (err: unknown) => log.warn(`[render] page error: ${err instanceof Error ? err.message : String(err)}`));
|
|
230
431
|
// Viewer and page errors are the usual reason a render produces nothing.
|
|
432
|
+
// Debug/info console messages (fetch traces from the runtime script) are
|
|
433
|
+
// shown at debug level, so -d traces every page-side request.
|
|
434
|
+
const debugConsole = log.getLevel() <= log.levels.DEBUG;
|
|
231
435
|
page.on("console", (message) => {
|
|
232
436
|
const type = message.type();
|
|
233
|
-
if (type !== "error" && type !== "warn") return;
|
|
437
|
+
if (type !== "error" && type !== "warn" && !(debugConsole && (type === "debug" || type === "info"))) return;
|
|
234
438
|
const where = message.location();
|
|
235
|
-
log
|
|
439
|
+
log[debugConsole && type !== "error" && type !== "warn" ? "trace" : "warn"](
|
|
440
|
+
`[render] console.${type}: ${message.text()}${where.url === "" ? "" : ` (${where.url})`}`
|
|
441
|
+
);
|
|
236
442
|
});
|
|
237
443
|
page.on("requestfailed", (request) => {
|
|
238
444
|
log.warn(`[render] request failed: ${request.url()} (${request.failure()?.errorText ?? "unknown"})`);
|
|
@@ -293,10 +499,35 @@ export async function renderPdf(request: RenderPdfRequest): Promise<RenderPdfRes
|
|
|
293
499
|
tagged: true
|
|
294
500
|
});
|
|
295
501
|
|
|
296
|
-
const stamped = await
|
|
502
|
+
const stamped = await postProcessPdf(pdf, {
|
|
503
|
+
metadata: pdfMetadata(request),
|
|
504
|
+
...(request.pdfLabel === undefined ? {} : { label: request.pdfLabel }),
|
|
505
|
+
...(request.iccProfile === undefined ? {} : { iccProfile: request.iccProfile, iccProfileName: request.iccProfileName })
|
|
506
|
+
});
|
|
507
|
+
if (request.pdfLabel !== undefined && request.validate !== false) {
|
|
508
|
+
const violations = validateLabeledPdf(stamped, request.pdfLabel);
|
|
509
|
+
if (violations.length > 0) {
|
|
510
|
+
throw new Error(
|
|
511
|
+
`${describeLabel(request.pdfLabel)} label failed validation, refusing to write a non-conforming output:\n` +
|
|
512
|
+
violations.map((violation) => ` - ${violation.check}: ${violation.detail}`).join("\n")
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
log.info(`[pdf] built-in ${describeLabel(request.pdfLabel)} validation passed`);
|
|
516
|
+
}
|
|
297
517
|
mkdirSync(dirname(request.output), { recursive: true });
|
|
298
518
|
writeFileSync(request.output, stamped);
|
|
299
519
|
|
|
520
|
+
if (request.verapdf === true && request.pdfLabel !== undefined) {
|
|
521
|
+
const vera = runVeraPdf(request.output, request.pdfLabel);
|
|
522
|
+
if (!vera.ran) {
|
|
523
|
+
log.warn(`[pdf] verapdf skipped: ${vera.reason}`);
|
|
524
|
+
} else if (vera.passed !== true) {
|
|
525
|
+
throw new Error(`verapdf reports ${describeLabel(request.pdfLabel)} violations (exit ${vera.exitCode ?? "n/a"}):\n${vera.output}`);
|
|
526
|
+
} else {
|
|
527
|
+
log.info(`[pdf] verapdf reports ${describeLabel(request.pdfLabel)} conformance: PASS`);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
300
531
|
const pageCount = await PDFDocument.load(stamped).then((doc) => doc.getPageCount());
|
|
301
532
|
|
|
302
533
|
return { output: request.output, bytes: stamped.length, pageCount, settle };
|
|
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
|
+
}
|