@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
package/src/metadata.ts
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// src/metadata.ts
|
|
2
|
+
|
|
3
|
+
// Copyright (c) 2026 Christian Mahnke
|
|
4
|
+
// Licensed under the MIT License.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Document metadata for the PDF information dictionary and XMP packet:
|
|
8
|
+
* extraction from the input (HTML document or publication manifest) and
|
|
9
|
+
* resolution against the CLI flags.
|
|
10
|
+
*
|
|
11
|
+
* Precedence: CLI flags > publication manifest > document > defaults.
|
|
12
|
+
* The only default is the language tag, which falls back to "de" when
|
|
13
|
+
* neither the flags nor the input provide one.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type { PdfAConformance, PdfAIdentification, PdfAPart, PdfXIdentification } from "./render/xmp.js";
|
|
17
|
+
|
|
18
|
+
/** Metadata fields shared by every source (document, manifest, CLI flags). */
|
|
19
|
+
export type DocumentMetadata = {
|
|
20
|
+
title?: string;
|
|
21
|
+
author?: string;
|
|
22
|
+
subject?: string;
|
|
23
|
+
keywords?: string;
|
|
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;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** Language tag assumed when no source provides one (project contract). */
|
|
32
|
+
export const DEFAULT_LANGUAGE = "de";
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Extracts metadata from the input document: <title>, the usual
|
|
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.
|
|
39
|
+
*/
|
|
40
|
+
export function extractMetadataFromDocument(document: Document): DocumentMetadata {
|
|
41
|
+
const title = document.querySelector("title")?.textContent?.trim();
|
|
42
|
+
const metaContent = (names: readonly string[]): string | undefined => {
|
|
43
|
+
for (const name of names) {
|
|
44
|
+
const element = document.querySelector(`meta[name="${name}" i]`) ?? document.querySelector(`meta[http-equiv="${name}" i]`);
|
|
45
|
+
const content = element?.getAttribute("content")?.trim();
|
|
46
|
+
if (content !== undefined && content !== "") return content;
|
|
47
|
+
}
|
|
48
|
+
return undefined;
|
|
49
|
+
};
|
|
50
|
+
return {
|
|
51
|
+
...(title === undefined || title === "" ? {} : { title }),
|
|
52
|
+
...optional(metaContent(["author", "dc.creator", "dcterms.creator"]), (value) => ({ author: value })),
|
|
53
|
+
...optional(metaContent(["description", "dc.description"]), (value) => ({ subject: value })),
|
|
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 })),
|
|
57
|
+
...optional(document.documentElement.getAttribute("lang")?.trim() || metaContent(["content-language"]), (value) => ({
|
|
58
|
+
language: value
|
|
59
|
+
}))
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Extracts metadata from a publication manifest (W3C Web Publication
|
|
65
|
+
* Manifest shape): title, author, description, keywords and language.
|
|
66
|
+
* Returns undefined when the text is not a JSON object.
|
|
67
|
+
*/
|
|
68
|
+
export function extractMetadataFromManifest(text: string): DocumentMetadata | undefined {
|
|
69
|
+
let manifest: unknown;
|
|
70
|
+
try {
|
|
71
|
+
manifest = JSON.parse(text);
|
|
72
|
+
} catch {
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
if (manifest === null || typeof manifest !== "object") return undefined;
|
|
76
|
+
const record = manifest as Record<string, unknown>;
|
|
77
|
+
return {
|
|
78
|
+
...optional(asString(record.title), (value) => ({ title: value })),
|
|
79
|
+
...optional(asAuthorList(record.author), (value) => ({ author: value })),
|
|
80
|
+
...optional(asString(record.description), (value) => ({ subject: value })),
|
|
81
|
+
...optional(asStringList(record.keywords, ", "), (value) => ({ keywords: value })),
|
|
82
|
+
...optional(asStringList(record.language ?? record.inLanguage, " "), (value) => ({ language: value }))
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Merges the sources: the CLI fields win over the extracted ones, and the
|
|
88
|
+
* language falls back to the project default.
|
|
89
|
+
*/
|
|
90
|
+
export function resolveMetadata(cli: DocumentMetadata, derived?: DocumentMetadata): DocumentMetadata & { language: string } {
|
|
91
|
+
const merged: DocumentMetadata = { ...derived, ...definedEntries(cli) };
|
|
92
|
+
if (merged.language === undefined || merged.language === "") {
|
|
93
|
+
merged.language = DEFAULT_LANGUAGE;
|
|
94
|
+
}
|
|
95
|
+
return merged as DocumentMetadata & { language: string };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Parses a `--pdfa` level like `2b`; part 4 takes no conformance level. */
|
|
99
|
+
export function parsePdfaLabel(value: string): PdfAIdentification {
|
|
100
|
+
const match = /^([1-4])([abu])?$/i.exec(value.trim());
|
|
101
|
+
if (match === null) {
|
|
102
|
+
throw new Error(`Invalid --pdfa level: "${value}". Allowed: 1a, 1b, 2a, 2b, 2u, 3a, 3b, 3u, 4`);
|
|
103
|
+
}
|
|
104
|
+
const part = match[1] as PdfAPart;
|
|
105
|
+
const conformance = match[2]?.toLowerCase() as PdfAConformance | undefined;
|
|
106
|
+
if (part === "4" && conformance !== undefined) {
|
|
107
|
+
throw new Error(`PDF/A-4 does not take a conformance level: "${value}". Use --pdfa 4`);
|
|
108
|
+
}
|
|
109
|
+
if (part !== "4" && conformance === undefined) {
|
|
110
|
+
throw new Error(`Missing PDF/A conformance level: "${value}". Use e.g. --pdfa 2b`);
|
|
111
|
+
}
|
|
112
|
+
return { kind: "pdfa", part, ...(conformance === undefined ? {} : { conformance }) };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Parses a `--pdfx` version; `X-1a` is accepted as shorthand for 2003. */
|
|
116
|
+
export function parsePdfxLabel(value: string): PdfXIdentification {
|
|
117
|
+
const normalized = value.trim();
|
|
118
|
+
if (normalized === "X-4") return { kind: "pdfx", version: "X-4" };
|
|
119
|
+
if (normalized === "X-1a" || normalized === "X-1a:2003") return { kind: "pdfx", version: "X-1a:2003" };
|
|
120
|
+
throw new Error(`Invalid --pdfx version: "${value}". Allowed: X-4, X-1a:2003`);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ---------------------------------------------------------------------------
|
|
124
|
+
// Helpers
|
|
125
|
+
// ---------------------------------------------------------------------------
|
|
126
|
+
|
|
127
|
+
function definedEntries(source: DocumentMetadata): DocumentMetadata {
|
|
128
|
+
const entries: DocumentMetadata = {};
|
|
129
|
+
for (const [key, value] of Object.entries(source)) {
|
|
130
|
+
if (value !== undefined && value !== "") (entries as Record<string, unknown>)[key] = value;
|
|
131
|
+
}
|
|
132
|
+
return entries;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function optional<T>(value: T | undefined | null, wrap: (value: T) => DocumentMetadata): DocumentMetadata {
|
|
136
|
+
return value === undefined || value === null || value === "" ? {} : wrap(value);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function asString(value: unknown): string | undefined {
|
|
140
|
+
return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Flattens string | {name} | ({name} | string)[] into "a; b" form. */
|
|
144
|
+
function asAuthorList(value: unknown): string | undefined {
|
|
145
|
+
const names = Array.isArray(value) ? value : [value];
|
|
146
|
+
const flattened = names
|
|
147
|
+
.map((entry) => {
|
|
148
|
+
if (typeof entry === "string") return entry.trim();
|
|
149
|
+
if (entry !== null && typeof entry === "object" && typeof (entry as Record<string, unknown>).name === "string") {
|
|
150
|
+
return ((entry as Record<string, unknown>).name as string).trim();
|
|
151
|
+
}
|
|
152
|
+
return "";
|
|
153
|
+
})
|
|
154
|
+
.filter((name) => name !== "");
|
|
155
|
+
return flattened.length === 0 ? undefined : flattened.join("; ");
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function asStringList(value: unknown, separator: string): string | undefined {
|
|
159
|
+
const entries = Array.isArray(value) ? value : [value];
|
|
160
|
+
const flattened = entries.map((entry) => (typeof entry === "string" ? entry.trim() : "")).filter((entry) => entry !== "");
|
|
161
|
+
return flattened.length === 0 ? undefined : flattened.join(separator);
|
|
162
|
+
}
|
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
// src/render/pdf-postprocess.ts
|
|
2
|
+
|
|
3
|
+
// Copyright (c) 2026 Christian Mahnke
|
|
4
|
+
// Licensed under the MIT License.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* PDF post-processing: document metadata, XMP and standards labeling.
|
|
8
|
+
*
|
|
9
|
+
* Runs on the PDF bytes Chrome printed (Skia output) and applies:
|
|
10
|
+
* - document information entries (title, author, subject, keywords, producer, creator)
|
|
11
|
+
* - the catalog /Lang entry for the document language
|
|
12
|
+
* - an XMP metadata stream kept consistent with the information dictionary
|
|
13
|
+
* - PDF/A or PDF/X identification: XMP identification properties, an
|
|
14
|
+
* OutputIntent with an embedded ICC profile and a stable file identifier
|
|
15
|
+
*
|
|
16
|
+
* This is a "label, don't convert" step — the same semantics vivliostyle-cli
|
|
17
|
+
* gives its PDF/X option: the content is neither converted nor checked, so
|
|
18
|
+
* conformance of the content is the author's responsibility. Verify with
|
|
19
|
+
* veraPDF (or a print provider's preflight) when it matters.
|
|
20
|
+
*
|
|
21
|
+
* The editing follows vivliostyle-cli's mupdf-based post-processing
|
|
22
|
+
* (src/output/pdfx.ts, pdf-document.ts, pdf-version.ts at v11.4).
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
26
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
27
|
+
import { dirname, join, resolve } from "node:path";
|
|
28
|
+
import { fileURLToPath } from "node:url";
|
|
29
|
+
import * as mupdf from "mupdf";
|
|
30
|
+
import { buildXmpPacket, pdfDateToXmpDate, toXmpDate, xmpDateToPdfDate, type PdfLabel } from "./xmp.js";
|
|
31
|
+
|
|
32
|
+
/** Document metadata written to the information dictionary and the XMP packet. */
|
|
33
|
+
export type PdfMetadata = {
|
|
34
|
+
title?: string;
|
|
35
|
+
author?: string;
|
|
36
|
+
subject?: string;
|
|
37
|
+
keywords?: string;
|
|
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;
|
|
43
|
+
creator: string;
|
|
44
|
+
producer: string;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export type PostProcessOptions = {
|
|
48
|
+
metadata: PdfMetadata;
|
|
49
|
+
label?: PdfLabel;
|
|
50
|
+
/** ICC profile embedded as the OutputIntent; required whenever a label is set. */
|
|
51
|
+
iccProfile?: Uint8Array;
|
|
52
|
+
iccProfileName?: string;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
type Destroyable = { destroy(): void };
|
|
56
|
+
|
|
57
|
+
type Scope = {
|
|
58
|
+
track<T extends Destroyable>(value: T): T;
|
|
59
|
+
dispose(): void;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Tracks MuPDF's native objects and destroys them in reverse order. Every
|
|
64
|
+
* PDFObject/Buffer/ColorSpace keeps native memory behind the wasm binding,
|
|
65
|
+
* which is only reclaimed on an explicit destroy.
|
|
66
|
+
*/
|
|
67
|
+
function createScope(): Scope {
|
|
68
|
+
const tracked: Destroyable[] = [];
|
|
69
|
+
return {
|
|
70
|
+
track<T extends Destroyable>(value: T): T {
|
|
71
|
+
tracked.push(value);
|
|
72
|
+
return value;
|
|
73
|
+
},
|
|
74
|
+
dispose(): void {
|
|
75
|
+
while (tracked.length > 0) {
|
|
76
|
+
try {
|
|
77
|
+
tracked.pop()?.destroy();
|
|
78
|
+
} catch {
|
|
79
|
+
// Cleanup is best-effort; a failed destroy must not mask the result.
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// MuPDF exposes PDF version x.y as x * 10 + y.
|
|
87
|
+
type PdfVersion = 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 20;
|
|
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
|
+
|
|
103
|
+
// The catalog /Version is written for every required version; MuPDF's wasm
|
|
104
|
+
// binding provides no API for the header version and a full save derives the
|
|
105
|
+
// header from the catalog entry (same approach as vivliostyle-cli).
|
|
106
|
+
function setMinimumPdfVersion(document: mupdf.PDFDocument, minimumVersion: PdfVersion, scope: Scope): void {
|
|
107
|
+
if (document.getVersion() >= minimumVersion) return;
|
|
108
|
+
const trailer = scope.track(document.getTrailer());
|
|
109
|
+
const catalog = scope.track(trailer.get("Root"));
|
|
110
|
+
const version = scope.track(document.newName(`${Math.trunc(minimumVersion / 10)}.${minimumVersion % 10}`));
|
|
111
|
+
catalog.put("Version", version);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function readInfoString(info: mupdf.PDFObject, key: string, scope: Scope): string | undefined {
|
|
115
|
+
const value = scope.track(info.get(key));
|
|
116
|
+
return value.isString() ? value.asString() : undefined;
|
|
117
|
+
}
|
|
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
|
+
|
|
144
|
+
function readTrapped(info: mupdf.PDFObject, scope: Scope): "True" | "False" {
|
|
145
|
+
const trapped = scope.track(info.get("Trapped"));
|
|
146
|
+
return trapped.isName() && trapped.asName() === "True" ? "True" : "False";
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function openPdfDocument(pdf: Uint8Array, scope: Scope): mupdf.PDFDocument {
|
|
150
|
+
// openDocument returns the Document base type; a PDF input yields a PDFDocument.
|
|
151
|
+
const document = mupdf.PDFDocument.openDocument(pdf, "application/pdf") as mupdf.PDFDocument;
|
|
152
|
+
return scope.track(document);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Runs `fn` with freshly fetched catalog handles. MuPDF replaces the trailer
|
|
157
|
+
* dict whenever an information entry is written through `setMetaData`, and a
|
|
158
|
+
* PDFObject handle held across such a write ends up detached from the
|
|
159
|
+
* document — edits into it silently disappear on save. Every mutation
|
|
160
|
+
* therefore re-fetches its handles right before it runs.
|
|
161
|
+
*/
|
|
162
|
+
function withCatalog<T>(document: mupdf.PDFDocument, scope: Scope, fn: (catalog: mupdf.PDFObject) => T): T {
|
|
163
|
+
const trailer = scope.track(document.getTrailer());
|
|
164
|
+
const catalog = scope.track(trailer.get("Root"));
|
|
165
|
+
return fn(catalog);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Runs `fn` with a freshly fetched information dictionary handle. */
|
|
169
|
+
function withInfo<T>(document: mupdf.PDFDocument, scope: Scope, fn: (info: mupdf.PDFObject) => T): T {
|
|
170
|
+
const trailer = scope.track(document.getTrailer());
|
|
171
|
+
const info = scope.track(trailer.get("Info"));
|
|
172
|
+
return fn(info);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Runs `fn` with a freshly fetched trailer handle. */
|
|
176
|
+
function withTrailer<T>(document: mupdf.PDFDocument, scope: Scope, fn: (trailer: mupdf.PDFObject) => T): T {
|
|
177
|
+
return fn(scope.track(document.getTrailer()));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Applies metadata and standards labeling to a printed PDF.
|
|
182
|
+
*
|
|
183
|
+
* Producer/Creator are always stamped (the wrapper owns them), so a build
|
|
184
|
+
* without explicit metadata still gets a consistent information dictionary
|
|
185
|
+
* and XMP packet. Dates come from what Skia wrote: CreationDate is kept,
|
|
186
|
+
* ModifyDate falls back to it, exactly like vivliostyle-cli handles output
|
|
187
|
+
* from print backends that skip the modification date.
|
|
188
|
+
*/
|
|
189
|
+
export async function postProcessPdf(pdf: Uint8Array, options: PostProcessOptions): Promise<Uint8Array> {
|
|
190
|
+
const scope = createScope();
|
|
191
|
+
try {
|
|
192
|
+
const { metadata, label } = options;
|
|
193
|
+
const document = openPdfDocument(pdf, scope);
|
|
194
|
+
|
|
195
|
+
// ── What the print backend already wrote ────────────────────────────────
|
|
196
|
+
const { creationDate, modifyDate, trapped } = withInfo(document, scope, (info) => ({
|
|
197
|
+
creationDate: readInfoString(info, "CreationDate", scope),
|
|
198
|
+
modifyDate: readInfoString(info, "ModDate", scope),
|
|
199
|
+
trapped: readTrapped(info, scope)
|
|
200
|
+
}));
|
|
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;
|
|
220
|
+
|
|
221
|
+
// ── Document information entries ────────────────────────────────────────
|
|
222
|
+
document.setMetaData("info:Producer", metadata.producer);
|
|
223
|
+
document.setMetaData("info:Creator", metadata.creator);
|
|
224
|
+
if (metadata.title !== undefined) document.setMetaData("info:Title", metadata.title);
|
|
225
|
+
if (metadata.author !== undefined) document.setMetaData("info:Author", metadata.author);
|
|
226
|
+
if (metadata.subject !== undefined) document.setMetaData("info:Subject", metadata.subject);
|
|
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
|
+
}
|
|
237
|
+
|
|
238
|
+
// ── Catalog language ────────────────────────────────────────────────────
|
|
239
|
+
const language = metadata.language;
|
|
240
|
+
if (language !== undefined && language !== "") {
|
|
241
|
+
withCatalog(document, scope, (catalog) => {
|
|
242
|
+
catalog.put("Lang", scope.track(document.newString(language)));
|
|
243
|
+
});
|
|
244
|
+
setMinimumPdfVersion(document, 14, scope);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// ── XMP metadata stream ─────────────────────────────────────────────────
|
|
248
|
+
const xmp = buildXmpPacket(
|
|
249
|
+
{
|
|
250
|
+
title: metadata.title,
|
|
251
|
+
author: metadata.author,
|
|
252
|
+
subject: metadata.subject,
|
|
253
|
+
keywords: metadata.keywords,
|
|
254
|
+
producer: metadata.producer,
|
|
255
|
+
creatorTool: metadata.creator,
|
|
256
|
+
createDate: createDateXmp,
|
|
257
|
+
modifyDate: modifyDateXmp,
|
|
258
|
+
metadataDate: toXmpDate(new Date()),
|
|
259
|
+
documentId: `uuid:${randomUUID()}`,
|
|
260
|
+
...(label !== undefined && label.kind === "pdfx" && label.version === "X-4" ? { trapped } : {})
|
|
261
|
+
},
|
|
262
|
+
label
|
|
263
|
+
);
|
|
264
|
+
withCatalog(document, scope, (catalog) => {
|
|
265
|
+
const xmpBuffer = scope.track(new mupdf.Buffer(xmp));
|
|
266
|
+
const metadataStream = scope.track(document.addStream(xmpBuffer, { Type: "Metadata", Subtype: "XML" }));
|
|
267
|
+
catalog.put("Metadata", metadataStream);
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
// ── OutputIntent with the embedded ICC profile ──────────────────────────
|
|
271
|
+
if (label !== undefined) {
|
|
272
|
+
const profile = options.iccProfile;
|
|
273
|
+
if (profile === undefined) {
|
|
274
|
+
throw new Error(
|
|
275
|
+
label.kind === "pdfx"
|
|
276
|
+
? "PDF/X labeling requires an ICC profile for the OutputIntent (--icc-profile)."
|
|
277
|
+
: "PDF/A labeling requires an ICC profile for the OutputIntent."
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
const profileName = options.iccProfileName ?? "output-intent.icc";
|
|
281
|
+
withCatalog(document, scope, (catalog) => {
|
|
282
|
+
const profileBuffer = scope.track(new mupdf.Buffer(profile));
|
|
283
|
+
const colorSpace = scope.track(new mupdf.ColorSpace(profileBuffer, profileName));
|
|
284
|
+
const profileStream = scope.track(document.addStream(profileBuffer, { N: colorSpace.getNumberOfComponents() }));
|
|
285
|
+
const identifier = scope.track(document.newString("Custom"));
|
|
286
|
+
const profileInfo = scope.track(document.newString(profileName));
|
|
287
|
+
// ISO 32000-1:2008, 7.7.2/14.11.5: OutputConditionIdentifier may be
|
|
288
|
+
// "Custom"; Info and DestOutputProfile are required for nonstandard
|
|
289
|
+
// production conditions.
|
|
290
|
+
const intent = scope.track(
|
|
291
|
+
document.addObject({
|
|
292
|
+
Type: "OutputIntent",
|
|
293
|
+
S: label.kind === "pdfa" ? "GTS_PDFA1" : "GTS_PDFX",
|
|
294
|
+
OutputConditionIdentifier: identifier,
|
|
295
|
+
Info: profileInfo,
|
|
296
|
+
DestOutputProfile: profileStream
|
|
297
|
+
})
|
|
298
|
+
);
|
|
299
|
+
catalog.put("OutputIntents", [intent]);
|
|
300
|
+
});
|
|
301
|
+
setMinimumPdfVersion(document, minimumVersionForLabel(label), scope);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// ── Standards identification outside the XMP packet ─────────────────────
|
|
305
|
+
if (label !== undefined && label.kind === "pdfx" && label.version === "X-1a:2003") {
|
|
306
|
+
// PDF/X-1a:2003 identification lives in the information dictionary, not
|
|
307
|
+
// in XMP (XMP identification is the PDF/X-4 form).
|
|
308
|
+
document.setMetaData("info:GTS_PDFXVersion", "PDF/X-1a:2003");
|
|
309
|
+
withInfo(document, scope, (info) => {
|
|
310
|
+
info.put("Trapped", scope.track(document.newName(trapped)));
|
|
311
|
+
// Acrobat's PDF/X-1a:2003 preflight requires ModDate, which some print
|
|
312
|
+
// backends never write; it takes the creation date then.
|
|
313
|
+
if (modifyDate === undefined && creationDate !== undefined) {
|
|
314
|
+
info.put("ModDate", scope.track(document.newString(creationDate)));
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// A stable file identifier is required for PDF/A and PDF/X. Written last,
|
|
320
|
+
// against a trailer handle fetched after every information entry write.
|
|
321
|
+
if (label !== undefined) {
|
|
322
|
+
withTrailer(document, scope, (trailer) => {
|
|
323
|
+
const existingId = scope.track(trailer.get("ID"));
|
|
324
|
+
if (!existingId.isArray()) {
|
|
325
|
+
const bytes = randomBytes(16);
|
|
326
|
+
trailer.put("ID", [document.newByteString(bytes), document.newByteString(bytes)]);
|
|
327
|
+
}
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
if (!document.hasUnsavedChanges()) return pdf;
|
|
332
|
+
const output = scope.track(document.saveToBuffer("compress"));
|
|
333
|
+
// Copy so the data stays valid after the buffer is destroyed.
|
|
334
|
+
return new Uint8Array(output.asUint8Array());
|
|
335
|
+
} finally {
|
|
336
|
+
scope.dispose();
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Loads the bundled sRGB profile, the default OutputIntent for PDF/A labeling.
|
|
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).
|
|
351
|
+
*/
|
|
352
|
+
export function loadDefaultIccProfile(): { bytes: Uint8Array; name: string } {
|
|
353
|
+
const moduleDir = dirname(fileURLToPath(import.meta.url));
|
|
354
|
+
const candidates = [
|
|
355
|
+
// Source layout (vitest, direct TS execution).
|
|
356
|
+
join(moduleDir, "srgb.icc"),
|
|
357
|
+
// Bundled layout: dist/vivliostyle-batch-cli.js ships next to src/.
|
|
358
|
+
resolve(moduleDir, "../src/render/srgb.icc")
|
|
359
|
+
];
|
|
360
|
+
for (const candidate of candidates) {
|
|
361
|
+
if (existsSync(candidate)) {
|
|
362
|
+
return { bytes: readFileSync(candidate), name: "sRGB IEC61966-2.1" };
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
throw new Error("Bundled sRGB ICC profile not found (expected at src/render/srgb.icc).");
|
|
366
|
+
}
|