@projektemacher/vivliostyle-batch-cli 0.3.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/dist/index.d.ts CHANGED
@@ -64,6 +64,10 @@ type DocumentMetadata = {
64
64
  subject?: string;
65
65
  keywords?: string;
66
66
  language?: string;
67
+ /** ISO 8601 creation date (information dictionary and XMP CreateDate). */
68
+ created?: string;
69
+ /** ISO 8601 modification date (information dictionary and XMP ModifyDate). */
70
+ modified?: string;
67
71
  };
68
72
 
69
73
  type CliOptions = {
@@ -74,9 +78,14 @@ type CliOptions = {
74
78
  subject?: string;
75
79
  keywords?: string;
76
80
  language?: string;
81
+ created?: string;
82
+ modified?: string;
77
83
  pdfa?: string;
78
84
  pdfx?: string;
79
85
  iccProfile?: string;
86
+ /** Commander's negatable form of --no-validate. */
87
+ validate?: boolean;
88
+ verapdf?: boolean;
80
89
  static: string[];
81
90
  scripts: boolean;
82
91
  format: string;
@@ -349,7 +358,7 @@ declare function resolveIccProfile(options: Pick<CliOptions, "iccProfile">, labe
349
358
  * input (HTML meta tags or a publication manifest); the language falls back
350
359
  * to "de" when no source provides one.
351
360
  */
352
- declare function resolvePdfMetadata(options: Pick<CliOptions, "title" | "author" | "subject" | "keywords" | "language">, inputAbs: string, htmlMode: boolean): DocumentMetadata & {
361
+ declare function resolvePdfMetadata(options: Pick<CliOptions, "title" | "author" | "subject" | "keywords" | "language" | "created" | "modified">, inputAbs: string, htmlMode: boolean): DocumentMetadata & {
353
362
  language: string;
354
363
  };
355
364
  declare function execute(options: CliOptions, extraArgs?: string[]): Promise<void>;
@@ -11,6 +11,7 @@ import puppeteer from 'puppeteer-core';
11
11
  import { PDFDocument } from 'pdf-lib';
12
12
  import { randomUUID, randomBytes } from 'node:crypto';
13
13
  import * as mupdf from 'mupdf';
14
+ import { spawnSync } from 'node:child_process';
14
15
  import { createRequire } from 'node:module';
15
16
 
16
17
  // src/server.ts
@@ -365,6 +366,17 @@ function pdfDateToXmpDate(value) {
365
366
  const zone = sign === undefined ? "Z" : `${sign}${offsetHour}:${offsetMinute}`;
366
367
  return `${year}-${month}-${day}T${hour}:${minute}:${second}${zone}`;
367
368
  }
369
+ // The inverse of the PDF date form above: XMP Part 1, 8.2.1.2 date.
370
+ const XMP_DATE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|[+\-]\d{2}:\d{2})$/;
371
+ /** Reformats an XMP date string as a PDF date; `undefined` when not one. */
372
+ function xmpDateToPdfDate(value) {
373
+ const match = XMP_DATE.exec(value);
374
+ if (match === null)
375
+ return undefined;
376
+ const [, year, month, day, hour, minute, second, zone] = match;
377
+ const offset = zone === "Z" ? "Z" : `${zone.slice(0, 3)}'${zone.slice(4, 6)}`;
378
+ return `D:${year}${month}${day}${hour}${minute}${second}${offset}`;
379
+ }
368
380
  function xmlEscape(text) {
369
381
  return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
370
382
  }
@@ -493,6 +505,21 @@ function createScope() {
493
505
  }
494
506
  };
495
507
  }
508
+ /**
509
+ * The PDF version each standards label is defined against: PDF/A-1 and
510
+ * PDF/X-1a:2003 on PDF 1.4, PDF/X-4 on PDF 1.6, PDF/A-2 and PDF/A-3 on
511
+ * PDF 1.7 (ISO 32000-1) and PDF/A-4 on PDF 2.0 (ISO 32000-2).
512
+ */
513
+ function minimumVersionForLabel(label) {
514
+ if (label.kind === "pdfa") {
515
+ if (label.part === "1")
516
+ return 14;
517
+ if (label.part === "4")
518
+ return 20;
519
+ return 17;
520
+ }
521
+ return label.version === "X-4" ? 16 : 14;
522
+ }
496
523
  // The catalog /Version is written for every required version; MuPDF's wasm
497
524
  // binding provides no API for the header version and a full save derives the
498
525
  // header from the catalog entry (same approach as vivliostyle-cli).
@@ -508,6 +535,32 @@ function readInfoString(info, key, scope) {
508
535
  const value = scope.track(info.get(key));
509
536
  return value.isString() ? value.asString() : undefined;
510
537
  }
538
+ /**
539
+ * Parses an explicitly given date (ISO 8601, optionally date-only, or the PDF
540
+ * "D:…" form) into both formats the document needs: the information
541
+ * dictionary date (ISO 32000-1:2008, 7.9.4) and the XMP date (XMP Part 1,
542
+ * 8.2.1.2). A date without offset counts as UTC.
543
+ */
544
+ function parseExplicitDate(value, field) {
545
+ const trimmed = value.trim();
546
+ const pdfFromXmp = xmpDateToPdfDate(trimmed);
547
+ if (pdfFromXmp !== undefined)
548
+ return { pdfDate: pdfFromXmp, xmpDate: trimmed };
549
+ const xmpFromPdf = pdfDateToXmpDate(trimmed);
550
+ if (xmpFromPdf !== undefined)
551
+ return { pdfDate: trimmed, xmpDate: xmpFromPdf };
552
+ const match = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2}))?)?(?:[Zz]|([+\-])(\d{2}):?(\d{2}))?$/.exec(trimmed);
553
+ if (match === null) {
554
+ throw new Error(`Invalid ${field} date: "${value}". Use ISO 8601, e.g. 2024-11-18T00:00:00+01:00`);
555
+ }
556
+ const [, year, month, day, hour = "00", minute = "00", second = "00", sign, offsetHour, offsetMinute] = match;
557
+ const offset = sign === undefined ? "Z" : `${sign}${offsetHour}'${offsetMinute}`;
558
+ const xmpOffset = sign === undefined ? "Z" : `${sign}${offsetHour}:${offsetMinute}`;
559
+ return {
560
+ pdfDate: `D:${year}${month}${day}${hour}${minute}${second}${offset}`,
561
+ xmpDate: `${year}-${month}-${day}T${hour}:${minute}:${second}${xmpOffset}`
562
+ };
563
+ }
511
564
  function readTrapped(info, scope) {
512
565
  const trapped = scope.track(info.get("Trapped"));
513
566
  return trapped.isName() && trapped.asName() === "True" ? "True" : "False";
@@ -559,10 +612,25 @@ async function postProcessPdf(pdf, options) {
559
612
  modifyDate: readInfoString(info, "ModDate", scope),
560
613
  trapped: readTrapped(info, scope)
561
614
  }));
562
- const createDateXmp = (creationDate !== undefined ? pdfDateToXmpDate(creationDate) : undefined) ?? toXmpDate(new Date());
563
- // Acrobat's preflight requires xmp:ModifyDate/MetadataDate; backends like
564
- // Firefox's cairo skip them, so they take the creation date then.
565
- const modifyDateXmp = (modifyDate !== undefined ? pdfDateToXmpDate(modifyDate) : undefined) ?? createDateXmp;
615
+ let infoCreationDate = creationDate;
616
+ let infoModifyDate = modifyDate;
617
+ let createDateXmp = creationDate !== undefined ? pdfDateToXmpDate(creationDate) : undefined;
618
+ let modifyDateXmp = modifyDate !== undefined ? pdfDateToXmpDate(modifyDate) : undefined;
619
+ if (metadata.created !== undefined) {
620
+ const parsed = parseExplicitDate(metadata.created, "--created");
621
+ infoCreationDate = parsed.pdfDate;
622
+ createDateXmp = parsed.xmpDate;
623
+ }
624
+ if (metadata.modified !== undefined) {
625
+ const parsed = parseExplicitDate(metadata.modified, "--modified");
626
+ infoModifyDate = parsed.pdfDate;
627
+ modifyDateXmp = parsed.xmpDate;
628
+ }
629
+ // Acrobat's preflight requires xmp:CreateDate/MetadataDate and, with
630
+ // ModifyDate absent (as with backends like Firefox's cairo), falls back to
631
+ // the creation date — so both dates are always present in the XMP packet.
632
+ createDateXmp ??= toXmpDate(new Date());
633
+ modifyDateXmp ??= createDateXmp;
566
634
  // ── Document information entries ────────────────────────────────────────
567
635
  document.setMetaData("info:Producer", metadata.producer);
568
636
  document.setMetaData("info:Creator", metadata.creator);
@@ -574,6 +642,15 @@ async function postProcessPdf(pdf, options) {
574
642
  document.setMetaData("info:Subject", metadata.subject);
575
643
  if (metadata.keywords !== undefined)
576
644
  document.setMetaData("info:Keywords", metadata.keywords);
645
+ // Explicit dates override the ones the print backend wrote (setMetaData
646
+ // replaces the information dictionary, so these run after the entries
647
+ // above and every later access re-fetches its handles).
648
+ if (infoCreationDate !== undefined && infoCreationDate !== creationDate) {
649
+ document.setMetaData("info:CreationDate", infoCreationDate);
650
+ }
651
+ if (infoModifyDate !== undefined && infoModifyDate !== modifyDate) {
652
+ document.setMetaData("info:ModDate", infoModifyDate);
653
+ }
577
654
  // ── Catalog language ────────────────────────────────────────────────────
578
655
  const language = metadata.language;
579
656
  if (language !== undefined && language !== "") {
@@ -628,7 +705,7 @@ async function postProcessPdf(pdf, options) {
628
705
  }));
629
706
  catalog.put("OutputIntents", [intent]);
630
707
  });
631
- setMinimumPdfVersion(document, 14, scope);
708
+ setMinimumPdfVersion(document, minimumVersionForLabel(label), scope);
632
709
  }
633
710
  // ── Standards identification outside the XMP packet ─────────────────────
634
711
  if (label !== undefined && label.kind === "pdfx" && label.version === "X-1a:2003") {
@@ -667,9 +744,15 @@ async function postProcessPdf(pdf, options) {
667
744
  }
668
745
  /**
669
746
  * Loads the bundled sRGB profile, the default OutputIntent for PDF/A labeling.
670
- * The profile ships unchanged from the ICC ("sRGB_v4_ICC_preference.icc"); its
671
- * license permits redistribution provided the file, including its embedded
672
- * copyright notice tag, is not modified (https://www.color.org/srgbprofiles.xalter).
747
+ *
748
+ * The profile ships unchanged from Debian's icc-profiles-free package
749
+ * (sources.debian.org, sRGB.icc from the "sRGB IEC61966-2.1" distribution by
750
+ * Hewlett-Packard): a monitor-class ("mntr") RGB profile with the embedded
751
+ * copyright tag, as PDF/A requires (ISO 19005-2, 6.2.3: an OutputIntent
752
+ * profile must be of the output or monitor device class and older than
753
+ * ICC v5). The ICC/HP license permits redistribution provided the file,
754
+ * including its embedded copyright notice tag, is not modified
755
+ * (https://registry.color.org/profile-library/#license).
673
756
  */
674
757
  function loadDefaultIccProfile() {
675
758
  const moduleDir = dirname(fileURLToPath(import.meta.url));
@@ -681,12 +764,225 @@ function loadDefaultIccProfile() {
681
764
  ];
682
765
  for (const candidate of candidates) {
683
766
  if (existsSync(candidate)) {
684
- return { bytes: readFileSync(candidate), name: "sRGB_v4_ICC_preference.icc" };
767
+ return { bytes: readFileSync(candidate), name: "sRGB IEC61966-2.1" };
685
768
  }
686
769
  }
687
770
  throw new Error("Bundled sRGB ICC profile not found (expected at src/render/srgb.icc).");
688
771
  }
689
772
 
773
+ // src/render/pdf-validate.ts
774
+ // Copyright (c) 2026 Christian Mahnke
775
+ // Licensed under the MIT License.
776
+ /**
777
+ * Built-in compliance checks for standards-labeled output (PDF/A, PDF/X).
778
+ *
779
+ * veraPDF implements the full ISO rule sets; this module covers the practical
780
+ * subset a print backend can violate and that the post-processing step is
781
+ * responsible for: the PDF version of the labeled part, the XMP
782
+ * identification, the OutputIntent with an embedded ICC profile, the file
783
+ * identifier, embedded fonts and the absence of JavaScript actions.
784
+ * Run the verapdf binary (see verapdf.ts) when the full rule set matters.
785
+ */
786
+ /** Human-readable label, e.g. "PDF/A-2b" or "PDF/X-4". */
787
+ function describeLabel(label) {
788
+ return label.kind === "pdfa" ? `PDF/A-${label.part}${label.conformance ?? ""}` : `PDF/${label.version}`;
789
+ }
790
+ const decoder = new TextDecoder("utf-8");
791
+ function decodeStream(stream) {
792
+ return decoder.decode(stream.readStream().asUint8Array());
793
+ }
794
+ /** True when the font dictionary carries one of the embedded font file keys. */
795
+ function hasEmbeddedFontFile(fontDescriptor) {
796
+ for (const key of ["FontFile", "FontFile2", "FontFile3"]) {
797
+ if (fontDescriptor.get(key).isStream())
798
+ return true;
799
+ }
800
+ return false;
801
+ }
802
+ /** Checks a single font dictionary; returns a violation detail or null. */
803
+ function checkFont(font) {
804
+ const subtype = font.get("Subtype").asName();
805
+ if (subtype === "Type3") {
806
+ // PDF/A (parts 1-3) requires the character procedures of a Type3 font to
807
+ // be embedded streams; PDF/A-4 additionally allows them in the page.
808
+ return font.get("CharProcs").isDictionary() || font.get("CharProcs").isStream() ? null : "Type3 font without CharProcs";
809
+ }
810
+ let descriptor = font.get("FontDescriptor");
811
+ if (subtype === "Type0") {
812
+ const descendants = font.get("DescendantFonts");
813
+ if (!descendants.isArray())
814
+ return "Type0 font without DescendantFonts";
815
+ descriptor = descendants.get(0).resolve().get("FontDescriptor");
816
+ }
817
+ else if (subtype === "CIDFontType0" || subtype === "CIDFontType2") {
818
+ descriptor = font.get("FontDescriptor");
819
+ }
820
+ if (!descriptor.isDictionary())
821
+ return `${subtype} font without FontDescriptor`;
822
+ if (!hasEmbeddedFontFile(descriptor))
823
+ return `${subtype} font without embedded FontFile`;
824
+ return null;
825
+ }
826
+ function validateLabeledPdf(pdf, label) {
827
+ const violations = [];
828
+ const document = mupdf.PDFDocument.openDocument(pdf, "application/pdf");
829
+ try {
830
+ const trailer = document.getTrailer();
831
+ const catalog = trailer.get("Root");
832
+ // ── PDF version of the labeled part ───────────────────────────────────
833
+ const minimumVersion = minimumVersionForLabel(label);
834
+ if (document.getVersion() < minimumVersion) {
835
+ violations.push({
836
+ check: "pdf-version",
837
+ detail: `document is PDF ${Math.trunc(document.getVersion() / 10)}.${document.getVersion() % 10}, ${describeLabel(label)} requires at least ${Math.trunc(minimumVersion / 10)}.${minimumVersion % 10}`
838
+ });
839
+ }
840
+ // ── XMP metadata stream with the standards identification ─────────────
841
+ // get() follows indirect references already; resolve() would hide the
842
+ // stream-ness of the handle (see the post-processing test comment).
843
+ const metadataStream = catalog.get("Metadata");
844
+ let xmp = "";
845
+ if (!metadataStream.isStream()) {
846
+ violations.push({ check: "xmp-metadata", detail: "catalog has no Metadata stream" });
847
+ }
848
+ else {
849
+ xmp = decodeStream(metadataStream);
850
+ if (label.kind === "pdfa") {
851
+ if (!xmp.includes(`<pdfaid:part>${label.part}</pdfaid:part>`)) {
852
+ violations.push({ check: "xmp-identification", detail: `XMP is missing <pdfaid:part>${label.part}` });
853
+ }
854
+ if (label.conformance !== undefined &&
855
+ !xmp.includes(`<pdfaid:conformance>${label.conformance.toUpperCase()}</pdfaid:conformance>`)) {
856
+ violations.push({ check: "xmp-identification", detail: `XMP is missing <pdfaid:conformance>${label.conformance.toUpperCase()}` });
857
+ }
858
+ }
859
+ else if (label.version === "X-4" && !xmp.includes("<pdfxid:GTS_PDFXVersion>PDF/X-4</pdfxid:GTS_PDFXVersion>")) {
860
+ violations.push({ check: "xmp-identification", detail: "XMP is missing the PDF/X-4 GTS_PDFXVersion" });
861
+ }
862
+ }
863
+ // ── OutputIntent with an embedded ICC profile ──────────────────────────
864
+ if (label.kind === "pdfa" || label.version === "X-4") {
865
+ const intents = catalog.get("OutputIntents");
866
+ if (!intents.isArray() || intents.length < 1) {
867
+ violations.push({ check: "output-intent", detail: "catalog has no OutputIntents array" });
868
+ }
869
+ else {
870
+ const intent = intents.get(0);
871
+ const expectedS = label.kind === "pdfa" ? "GTS_PDFA1" : "GTS_PDFX";
872
+ if (!intent.get("S").asName()?.startsWith(expectedS)) {
873
+ violations.push({ check: "output-intent", detail: `OutputIntent /S is not ${expectedS}` });
874
+ }
875
+ // MuPDF's PDFObject.resolve() does not surface stream-ness for
876
+ // indirect refs, so the embedded profile is checked through its
877
+ // stream data (same approach as the post-processing tests).
878
+ let profileReadable = false;
879
+ try {
880
+ profileReadable = intent.get("DestOutputProfile").readStream().asUint8Array().length > 0;
881
+ }
882
+ catch {
883
+ profileReadable = false;
884
+ }
885
+ if (!profileReadable) {
886
+ violations.push({ check: "output-intent", detail: "OutputIntent has no embedded DestOutputProfile" });
887
+ }
888
+ }
889
+ }
890
+ // ── File identifier (required for PDF/A and PDF/X) ──────────────────────
891
+ const fileId = trailer.get("ID");
892
+ if (!fileId.isArray() || fileId.length < 2) {
893
+ violations.push({ check: "file-identifier", detail: "trailer /ID pair missing" });
894
+ }
895
+ // ── Fonts embedded ──────────────────────────────────────────────────────
896
+ const pageCount = document.countPages();
897
+ for (let index = 0; index < pageCount; index++) {
898
+ const page = document.loadPage(index);
899
+ try {
900
+ const fonts = page.getObject().get("Resources").resolve().get("Font");
901
+ if (!fonts.isDictionary())
902
+ continue;
903
+ fonts.forEach((fontRef) => {
904
+ const font = fontRef.resolve();
905
+ if (!font.isDictionary())
906
+ return;
907
+ const failure = checkFont(font);
908
+ if (failure !== null)
909
+ violations.push({ check: "font-embedded", detail: `page ${index + 1}: ${failure}` });
910
+ });
911
+ }
912
+ finally {
913
+ page.destroy();
914
+ }
915
+ }
916
+ // ── No JavaScript actions ────────────────────────────────────────────────
917
+ const names = catalog.get("Names");
918
+ if (names.isDictionary() && names.get("JavaScript").isDictionary()) {
919
+ violations.push({ check: "no-javascript", detail: "document name tree contains JavaScript actions" });
920
+ }
921
+ const openAction = catalog.get("OpenAction");
922
+ if (openAction.isDictionary() && openAction.get("S").asName() === "JavaScript") {
923
+ violations.push({ check: "no-javascript", detail: "OpenAction is a JavaScript action" });
924
+ }
925
+ // ── Information dictionary / XMP consistency ────────────────────────────
926
+ const info = trailer.get("Info");
927
+ if (info.isDictionary()) {
928
+ if (info.get("Title").isString() && xmp !== "" && !xmp.includes("<dc:title>")) {
929
+ violations.push({ check: "metadata-consistency", detail: "information dictionary has a Title but the XMP packet lacks dc:title" });
930
+ }
931
+ if (info.get("Author").isString() && xmp !== "" && !xmp.includes("<dc:creator>")) {
932
+ violations.push({
933
+ check: "metadata-consistency",
934
+ detail: "information dictionary has an Author but the XMP packet lacks dc:creator"
935
+ });
936
+ }
937
+ }
938
+ return violations;
939
+ }
940
+ finally {
941
+ document.destroy();
942
+ }
943
+ }
944
+
945
+ // src/render/verapdf.ts
946
+ // Copyright (c) 2026 Christian Mahnke
947
+ // Licensed under the MIT License.
948
+ /**
949
+ * Optional pass-through to the verapdf binary (https://verapdf.org/), which
950
+ * implements the full ISO conformance rule sets for PDF/A and PDF/X. The
951
+ * binary must be on the PATH; it is never bundled because it needs a Java
952
+ * runtime. Only invoked on explicit request (--verapdf).
953
+ */
954
+ /** Maps a standards label onto a veraPDF --flavour value. */
955
+ function veraPdfFlavour(label) {
956
+ if (label.kind === "pdfa") {
957
+ return label.part === "4" ? "4" : `${label.part}${label.conformance ?? ""}`;
958
+ }
959
+ return label.version === "X-4" ? "X-4" : "X-1a";
960
+ }
961
+ function runVeraPdf(pdfPath, label) {
962
+ const flavour = veraPdfFlavour(label);
963
+ let result;
964
+ try {
965
+ result = spawnSync("verapdf", ["--flavour", flavour, "--format", "text", pdfPath], {
966
+ encoding: "utf-8",
967
+ timeout: 120_000
968
+ });
969
+ }
970
+ catch (error) {
971
+ return { ran: false, reason: error instanceof Error ? error.message : String(error) };
972
+ }
973
+ if (result.error !== undefined) {
974
+ const code = result.error.code;
975
+ return {
976
+ ran: false,
977
+ reason: code === "ENOENT" ? "verapdf binary not found on PATH" : String(result.error)
978
+ };
979
+ }
980
+ const stdout = typeof result.stdout === "string" ? result.stdout : "";
981
+ const stderr = typeof result.stderr === "string" ? result.stderr : "";
982
+ const output = `${stdout}${stderr}`.slice(0, 4000);
983
+ return { ran: true, passed: /\bPASS\b/.test(stdout), exitCode: result.status, output };
984
+ }
985
+
690
986
  // src/render/pdf.ts
691
987
  // Copyright (c) 2026 Christian Mahnke
692
988
  // Licensed under the MIT License.
@@ -722,6 +1018,8 @@ function pdfMetadata(request) {
722
1018
  ...(request.subject === undefined ? {} : { subject: request.subject }),
723
1019
  ...(request.keywords === undefined ? {} : { keywords: request.keywords }),
724
1020
  ...(request.language === undefined ? {} : { language: request.language }),
1021
+ ...(request.created === undefined ? {} : { created: request.created }),
1022
+ ...(request.modified === undefined ? {} : { modified: request.modified }),
725
1023
  creator: TOOL_IDENTITY,
726
1024
  producer: TOOL_IDENTITY
727
1025
  };
@@ -1074,8 +1372,28 @@ async function renderPdf(request) {
1074
1372
  ...(request.pdfLabel === undefined ? {} : { label: request.pdfLabel }),
1075
1373
  ...(request.iccProfile === undefined ? {} : { iccProfile: request.iccProfile, iccProfileName: request.iccProfileName })
1076
1374
  });
1375
+ if (request.pdfLabel !== undefined && request.validate !== false) {
1376
+ const violations = validateLabeledPdf(stamped, request.pdfLabel);
1377
+ if (violations.length > 0) {
1378
+ throw new Error(`${describeLabel(request.pdfLabel)} label failed validation, refusing to write a non-conforming output:\n` +
1379
+ violations.map((violation) => ` - ${violation.check}: ${violation.detail}`).join("\n"));
1380
+ }
1381
+ log.info(`[pdf] built-in ${describeLabel(request.pdfLabel)} validation passed`);
1382
+ }
1077
1383
  mkdirSync(dirname(request.output), { recursive: true });
1078
1384
  writeFileSync(request.output, stamped);
1385
+ if (request.verapdf === true && request.pdfLabel !== undefined) {
1386
+ const vera = runVeraPdf(request.output, request.pdfLabel);
1387
+ if (!vera.ran) {
1388
+ log.warn(`[pdf] verapdf skipped: ${vera.reason}`);
1389
+ }
1390
+ else if (vera.passed !== true) {
1391
+ throw new Error(`verapdf reports ${describeLabel(request.pdfLabel)} violations (exit ${vera.exitCode ?? "n/a"}):\n${vera.output}`);
1392
+ }
1393
+ else {
1394
+ log.info(`[pdf] verapdf reports ${describeLabel(request.pdfLabel)} conformance: PASS`);
1395
+ }
1396
+ }
1079
1397
  const pageCount = await PDFDocument.load(stamped).then((doc) => doc.getPageCount());
1080
1398
  return { output: request.output, bytes: stamped.length, pageCount, settle };
1081
1399
  }
@@ -1121,7 +1439,9 @@ function fileURLOfSelf() {
1121
1439
  const DEFAULT_LANGUAGE = "de";
1122
1440
  /**
1123
1441
  * Extracts metadata from the input document: <title>, the usual
1124
- * author/description/keywords meta tags and the document language.
1442
+ * author/description/keywords meta tags, the creation/modification dates
1443
+ * (dcterms, falling back to the plain date meta tag) and the document
1444
+ * language.
1125
1445
  */
1126
1446
  function extractMetadataFromDocument(document) {
1127
1447
  const title = document.querySelector("title")?.textContent?.trim();
@@ -1139,6 +1459,8 @@ function extractMetadataFromDocument(document) {
1139
1459
  ...optional(metaContent(["author", "dc.creator", "dcterms.creator"]), (value) => ({ author: value })),
1140
1460
  ...optional(metaContent(["description", "dc.description"]), (value) => ({ subject: value })),
1141
1461
  ...optional(metaContent(["keywords"]), (value) => ({ keywords: value })),
1462
+ ...optional(metaContent(["dcterms.created", "dc.date", "date"]), (value) => ({ created: value })),
1463
+ ...optional(metaContent(["dcterms.modified", "dc.date.modified", "modified"]), (value) => ({ modified: value })),
1142
1464
  ...optional(document.documentElement.getAttribute("lang")?.trim() || metaContent(["content-language"]), (value) => ({
1143
1465
  language: value
1144
1466
  }))
@@ -2397,6 +2719,8 @@ function buildProgram() {
2397
2719
  .option("--subject <subject>", "Document subject (e.g. the page's description meta tag content)")
2398
2720
  .option("--keywords <keywords>", "Document keywords, comma separated")
2399
2721
  .option("--language <lang>", "Document language tag (e.g. en, de, ja). Taken from the document or manifest when omitted, falling back to 'de'")
2722
+ .option("--created <date>", "Document creation date (ISO 8601, e.g. 2024-11-18T00:00:00+01:00). Taken from the document's dcterms.created meta tag when omitted")
2723
+ .option("--modified <date>", "Document modification date (ISO 8601). Taken from the document's dcterms.modified meta tag when omitted")
2400
2724
  .option("--pdfa <level>", [
2401
2725
  "Label the output PDF as PDF/A (ISO 19005): the XMP identification,",
2402
2726
  "an OutputIntent with an embedded ICC profile (bundled sRGB unless",
@@ -2410,6 +2734,15 @@ function buildProgram() {
2410
2734
  "identification metadata as XMP, X-1a:2003 into the information",
2411
2735
  "dictionary. Both embed the --icc-profile as the OutputIntent.",
2412
2736
  "Same label-only semantics as --pdfa."
2737
+ ].join("\n "))
2738
+ .option("--no-validate", [
2739
+ "Skip the built-in compliance checks run for --pdfa/--pdfx output:",
2740
+ "PDF version of the labeled part, XMP identification, OutputIntent,",
2741
+ "file identifier, embedded fonts and the absence of JavaScript."
2742
+ ].join("\n "))
2743
+ .option("--verapdf", [
2744
+ "Additionally run the verapdf binary (must be on the PATH) against the",
2745
+ "output and fail the build on full ISO rule-set violations."
2413
2746
  ].join("\n "))
2414
2747
  .option("--icc-profile <path>", [
2415
2748
  "ICC profile embedded as the PDF output intent, e.g. a print",
@@ -2490,9 +2823,11 @@ function buildProgram() {
2490
2823
  " • the browser prints that page to PDF, so canvases and iframes stay real content.",
2491
2824
  " • Collapsed <details> content is opened for the PDF; the preview keeps the page as it is.",
2492
2825
  " • --asset-base localBase is also a fallback root for CSS-referenced assets.",
2493
- " • PDF metadata (--title/--author/--subject/--keywords/--language) overrides",
2826
+ " • PDF metadata (--title/--author/--subject/--keywords/--language/--created/--modified)",
2494
2827
  " • values read from the document or the publication manifest; language falls",
2495
- " • back to 'de'. --pdfa/--pdfx label the output, they do not convert content."
2828
+ " • back to 'de'. --pdfa/--pdfx label the output; the built-in validation",
2829
+ " • checks the practical subset (--no-validate skips it) and --verapdf runs",
2830
+ " • the full ISO rule set through the verapdf binary."
2496
2831
  ].join("\n"));
2497
2832
  }
2498
2833
  function printHelp() {
@@ -2530,8 +2865,12 @@ async function runRender(params) {
2530
2865
  ...(params.metaFields.subject === undefined ? {} : { subject: params.metaFields.subject }),
2531
2866
  ...(params.metaFields.keywords === undefined ? {} : { keywords: params.metaFields.keywords }),
2532
2867
  ...(params.metaFields.language === undefined ? {} : { language: params.metaFields.language }),
2868
+ ...(params.metaFields.created === undefined ? {} : { created: params.metaFields.created }),
2869
+ ...(params.metaFields.modified === undefined ? {} : { modified: params.metaFields.modified }),
2533
2870
  ...(params.pdfLabel === undefined ? {} : { pdfLabel: params.pdfLabel }),
2534
- ...(params.iccProfile === undefined ? {} : { iccProfile: params.iccProfile.bytes, iccProfileName: params.iccProfile.name })
2871
+ ...(params.iccProfile === undefined ? {} : { iccProfile: params.iccProfile.bytes, iccProfileName: params.iccProfile.name }),
2872
+ validate: params.validate,
2873
+ ...(params.verapdf === undefined ? {} : { verapdf: params.verapdf })
2535
2874
  };
2536
2875
  log.trace("renderPdf request", request);
2537
2876
  const result = await renderPdf(request);
@@ -2637,7 +2976,15 @@ function resolveIccProfile(options, label) {
2637
2976
  * to "de" when no source provides one.
2638
2977
  */
2639
2978
  function resolvePdfMetadata(options, inputAbs, htmlMode) {
2640
- const cliFields = pickDefinedStrings(options, ["title", "author", "subject", "keywords", "language"]);
2979
+ const cliFields = pickDefinedStrings(options, [
2980
+ "title",
2981
+ "author",
2982
+ "subject",
2983
+ "keywords",
2984
+ "language",
2985
+ "created",
2986
+ "modified"
2987
+ ]);
2641
2988
  let derived;
2642
2989
  if (htmlMode) {
2643
2990
  derived = extractMetadataFromDocument(new JSDOM(readFileSync(inputAbs, "utf-8")).window.document);
@@ -2841,7 +3188,9 @@ async function execute(options, extraArgs = []) {
2841
3188
  chromeExecutable: typeof extraConfig.executableBrowser === "string" ? extraConfig.executableBrowser : undefined,
2842
3189
  canvasScale,
2843
3190
  ...(pdfLabel === undefined ? {} : { pdfLabel }),
2844
- ...(iccProfile === undefined ? {} : { iccProfile })
3191
+ ...(iccProfile === undefined ? {} : { iccProfile }),
3192
+ validate: options.validate !== false,
3193
+ ...(options.verapdf === true ? { verapdf: true } : {})
2845
3194
  });
2846
3195
  }
2847
3196
  finally {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@projektemacher/vivliostyle-batch-cli",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "type": "module",
5
5
  "description": "A vivliostyle-cli with more options for batch processing",
6
6
  "bin": {
@@ -46,16 +46,16 @@
46
46
  "echarts": "^6.1.0",
47
47
  "eslint": "^10.15.0",
48
48
  "globals": "^17.14.0",
49
- "marked": "^18.2.0",
49
+ "marked": "^18.2.1",
50
50
  "openseadragon": "^6.1.1",
51
51
  "prettier": "^3.10.1",
52
52
  "rimraf": "^6.1.4",
53
- "rollup": "^4.68.3",
53
+ "rollup": "^4.68.4",
54
54
  "rollup-plugin-dts": "^6.5.1",
55
55
  "three": "^0.187.0",
56
56
  "tslib": "^2.9.1",
57
57
  "typescript": "^6.0.3",
58
- "typescript-eslint": "^8.72.2",
58
+ "typescript-eslint": "^8.73.0",
59
59
  "vite": "^8.3.8",
60
60
  "vitest": "^5.1.0"
61
61
  },
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 and the document language.
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
- const createDateXmp = (creationDate !== undefined ? pdfDateToXmpDate(creationDate) : undefined) ?? toXmpDate(new Date());
159
- // Acrobat's preflight requires xmp:ModifyDate/MetadataDate; backends like
160
- // Firefox's cairo skip them, so they take the creation date then.
161
- const modifyDateXmp = (modifyDate !== undefined ? pdfDateToXmpDate(modifyDate) : undefined) ?? createDateXmp;
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, 14, scope);
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
- * The profile ships unchanged from the ICC ("sRGB_v4_ICC_preference.icc"); its
276
- * license permits redistribution provided the file, including its embedded
277
- * copyright notice tag, is not modified (https://www.color.org/srgbprofiles.xalter).
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: "sRGB_v4_ICC_preference.icc" };
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
  };
@@ -492,9 +504,30 @@ export async function renderPdf(request: RenderPdfRequest): Promise<RenderPdfRes
492
504
  ...(request.pdfLabel === undefined ? {} : { label: request.pdfLabel }),
493
505
  ...(request.iccProfile === undefined ? {} : { iccProfile: request.iccProfile, iccProfileName: request.iccProfileName })
494
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
+ }
495
517
  mkdirSync(dirname(request.output), { recursive: true });
496
518
  writeFileSync(request.output, stamped);
497
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
+
498
531
  const pageCount = await PDFDocument.load(stamped).then((doc) => doc.getPageCount());
499
532
 
500
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
+ }
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("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
94
106
  }
@@ -36,9 +36,14 @@ type CliOptions = {
36
36
  subject?: string;
37
37
  keywords?: string;
38
38
  language?: string;
39
+ created?: string;
40
+ modified?: string;
39
41
  pdfa?: string;
40
42
  pdfx?: string;
41
43
  iccProfile?: string;
44
+ /** Commander's negatable form of --no-validate. */
45
+ validate?: boolean;
46
+ verapdf?: boolean;
42
47
  static: string[];
43
48
  scripts: boolean;
44
49
  format: string;
@@ -1397,6 +1402,11 @@ function buildProgram(): Command {
1397
1402
  "--language <lang>",
1398
1403
  "Document language tag (e.g. en, de, ja). Taken from the document or manifest when omitted, falling back to 'de'"
1399
1404
  )
1405
+ .option(
1406
+ "--created <date>",
1407
+ "Document creation date (ISO 8601, e.g. 2024-11-18T00:00:00+01:00). Taken from the document's dcterms.created meta tag when omitted"
1408
+ )
1409
+ .option("--modified <date>", "Document modification date (ISO 8601). Taken from the document's dcterms.modified meta tag when omitted")
1400
1410
  .option(
1401
1411
  "--pdfa <level>",
1402
1412
  [
@@ -1417,6 +1427,21 @@ function buildProgram(): Command {
1417
1427
  "Same label-only semantics as --pdfa."
1418
1428
  ].join("\n ")
1419
1429
  )
1430
+ .option(
1431
+ "--no-validate",
1432
+ [
1433
+ "Skip the built-in compliance checks run for --pdfa/--pdfx output:",
1434
+ "PDF version of the labeled part, XMP identification, OutputIntent,",
1435
+ "file identifier, embedded fonts and the absence of JavaScript."
1436
+ ].join("\n ")
1437
+ )
1438
+ .option(
1439
+ "--verapdf",
1440
+ [
1441
+ "Additionally run the verapdf binary (must be on the PATH) against the",
1442
+ "output and fail the build on full ISO rule-set violations."
1443
+ ].join("\n ")
1444
+ )
1420
1445
  .option(
1421
1446
  "--icc-profile <path>",
1422
1447
  [
@@ -1539,9 +1564,11 @@ function buildProgram(): Command {
1539
1564
  " • the browser prints that page to PDF, so canvases and iframes stay real content.",
1540
1565
  " • Collapsed <details> content is opened for the PDF; the preview keeps the page as it is.",
1541
1566
  " • --asset-base localBase is also a fallback root for CSS-referenced assets.",
1542
- " • PDF metadata (--title/--author/--subject/--keywords/--language) overrides",
1567
+ " • PDF metadata (--title/--author/--subject/--keywords/--language/--created/--modified)",
1543
1568
  " • values read from the document or the publication manifest; language falls",
1544
- " • back to 'de'. --pdfa/--pdfx label the output, they do not convert content."
1569
+ " • back to 'de'. --pdfa/--pdfx label the output; the built-in validation",
1570
+ " • checks the practical subset (--no-validate skips it) and --verapdf runs",
1571
+ " • the full ISO rule set through the verapdf binary."
1545
1572
  ].join("\n")
1546
1573
  );
1547
1574
  }
@@ -1576,7 +1603,7 @@ export function parseArgs(argv: string[]): {
1576
1603
  // ---------------------------------------------------------------------------
1577
1604
 
1578
1605
  /** Metadata fields the CLI layer resolves before handing them to the renderer. */
1579
- type MetadataFieldName = "title" | "author" | "subject" | "keywords" | "language";
1606
+ type MetadataFieldName = "title" | "author" | "subject" | "keywords" | "language" | "created" | "modified";
1580
1607
 
1581
1608
  /** ICC profile bytes with the name they get in the PDF's OutputIntent. */
1582
1609
  type IccProfile = { bytes: Uint8Array; name: string };
@@ -1593,6 +1620,10 @@ type RenderParams = {
1593
1620
  canvasScale?: number;
1594
1621
  pdfLabel?: PdfLabel;
1595
1622
  iccProfile?: IccProfile;
1623
+ /** Run the built-in compliance checks for the label (default: on). */
1624
+ validate: boolean;
1625
+ /** Additionally run the verapdf binary against the output. */
1626
+ verapdf?: boolean;
1596
1627
  };
1597
1628
 
1598
1629
  async function runRender(params: RenderParams): Promise<void> {
@@ -1610,8 +1641,12 @@ async function runRender(params: RenderParams): Promise<void> {
1610
1641
  ...(params.metaFields.subject === undefined ? {} : { subject: params.metaFields.subject }),
1611
1642
  ...(params.metaFields.keywords === undefined ? {} : { keywords: params.metaFields.keywords }),
1612
1643
  ...(params.metaFields.language === undefined ? {} : { language: params.metaFields.language }),
1644
+ ...(params.metaFields.created === undefined ? {} : { created: params.metaFields.created }),
1645
+ ...(params.metaFields.modified === undefined ? {} : { modified: params.metaFields.modified }),
1613
1646
  ...(params.pdfLabel === undefined ? {} : { pdfLabel: params.pdfLabel }),
1614
- ...(params.iccProfile === undefined ? {} : { iccProfile: params.iccProfile.bytes, iccProfileName: params.iccProfile.name })
1647
+ ...(params.iccProfile === undefined ? {} : { iccProfile: params.iccProfile.bytes, iccProfileName: params.iccProfile.name }),
1648
+ validate: params.validate,
1649
+ ...(params.verapdf === undefined ? {} : { verapdf: params.verapdf })
1615
1650
  };
1616
1651
 
1617
1652
  log.trace("renderPdf request", request);
@@ -1721,11 +1756,19 @@ export function resolveIccProfile(options: Pick<CliOptions, "iccProfile">, label
1721
1756
  * to "de" when no source provides one.
1722
1757
  */
1723
1758
  export function resolvePdfMetadata(
1724
- options: Pick<CliOptions, "title" | "author" | "subject" | "keywords" | "language">,
1759
+ options: Pick<CliOptions, "title" | "author" | "subject" | "keywords" | "language" | "created" | "modified">,
1725
1760
  inputAbs: string,
1726
1761
  htmlMode: boolean
1727
1762
  ): DocumentMetadata & { language: string } {
1728
- const cliFields = pickDefinedStrings(options, ["title", "author", "subject", "keywords", "language"]) as DocumentMetadata;
1763
+ const cliFields = pickDefinedStrings(options, [
1764
+ "title",
1765
+ "author",
1766
+ "subject",
1767
+ "keywords",
1768
+ "language",
1769
+ "created",
1770
+ "modified"
1771
+ ]) as DocumentMetadata;
1729
1772
  let derived: DocumentMetadata | undefined;
1730
1773
  if (htmlMode) {
1731
1774
  derived = extractMetadataFromDocument(new JSDOM(readFileSync(inputAbs, "utf-8")).window.document);
@@ -1957,7 +2000,9 @@ export async function execute(options: CliOptions, extraArgs: string[] = []): Pr
1957
2000
  chromeExecutable: typeof extraConfig.executableBrowser === "string" ? extraConfig.executableBrowser : undefined,
1958
2001
  canvasScale,
1959
2002
  ...(pdfLabel === undefined ? {} : { pdfLabel }),
1960
- ...(iccProfile === undefined ? {} : { iccProfile })
2003
+ ...(iccProfile === undefined ? {} : { iccProfile }),
2004
+ validate: options.validate !== false,
2005
+ ...(options.verapdf === true ? { verapdf: true } : {})
1961
2006
  });
1962
2007
  } finally {
1963
2008
  htmlResource.cleanup();