From cd7d9acfa22a044617edb6a23484a56f58f0387c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20R=C3=B8sdal?= Date: Wed, 2 Dec 2026 22:35:39 +0100 Subject: [PATCH] Support PDF/X-4 PDF/X-4 (ISO 15930-7:2010) is the current exchange format for print production. Unlike PDF/X-1a and PDF/X-3, which OpenPDF already supports, it allows transparency, layers and ICC based colour. - PdfWriter.PDFX4 writes the document as PDF 1.6. - Transparency, soft masks and layers are allowed, as for PDF/A-2 and PDF/A-3. Fonts must still be embedded and encryption is refused. - The info dictionary gets /GTS_PDFXVersion (PDF/X-4), /Trapped and, for every PDF/X level, the /ModDate that PDF/X requires. - The XMP metadata is created when the document is closed, unless it was set before. For PDF/X-4 it has pdfxid:GTS_PDFXVersion, xmpMM:DocumentID, VersionID and RenditionClass, xmp:MetadataDate and pdf:Trapped. - An output intent with an ICC profile is required. Closing the document without one throws a PdfXConformanceException. Co-Authored-By: Claude Opus 5.5 --- changelogs/4.0.1.md | 2 + .../java/org/openpdf/text/pdf/PdfWriter.java | 27 +++ .../text/pdf/internal/PdfXConformanceImp.java | 53 +++++- .../org/openpdf/text/xml/xmp/PdfSchema.java | 4 + .../org/openpdf/text/xml/xmp/XmpWriter.java | 25 +++ .../java/org/openpdf/text/pdf/PdfX4Test.java | 165 ++++++++++++++++++ 6 files changed, 271 insertions(+), 5 deletions(-) create mode 100644 openpdf-core/src/test/java/org/openpdf/text/pdf/PdfX4Test.java diff --git a/changelogs/4.0.1.md b/changelogs/4.0.1.md index 8e4007f40..c8edb3b12 100644 --- a/changelogs/4.0.1.md +++ b/changelogs/4.0.1.md @@ -6,6 +6,7 @@ * **Associated files (PR #1806).** `PdfFileSpecification.setAFRelationship(PdfName)` and `associateWith(PdfDictionary)`, `PdfWriter.addAssociatedFile` and `addPageAssociatedFile`, and `PdfStamper.addAssociatedFile` link embedded files to the document, a page or another component, as PDF 2.0 and PDF/A-3 define them, for example the XML of a ZUGFeRD or Factur-X invoice. * **Tagged annotations (PR #1804, port of #1617).** `PdfStructureElement.addAnnotation(PdfAnnotation)` references a link or another annotation from the structure tree, as PDF/UA requires. The structure tree root gets a `/ParentTreeNextKey` entry. * **PDF/A extension schemas and Factur-X metadata (PR #1808).** `PdfWriter.addXmpSchema(XmpSchema, PdfAExtensionSchema.Schema)` adds custom XMP properties and the PDF/A extension schema that describes them to the metadata of `createXmpMetadata()`. `FacturXSchema` has the `fx` properties of ZUGFeRD and Factur-X invoices, so that a PDF/A-3 invoice with the invoice XML as an associated file passes veraPDF. +* **PDF/X-4 (PR #1809).** `PdfWriter.PDFX4` creates PDF/X-4 (ISO 15930-7:2010) documents for print production, with transparency, layers and ICC based colour. OpenPDF writes PDF 1.6, the PDF/X-4 identification and media management properties in the XMP metadata and `/GTS_PDFXVersion` and `/Trapped` in the info dictionary, and requires an output intent with an ICC profile and embedded fonts. ## ๐Ÿ›  Bug Fixes @@ -15,6 +16,7 @@ * **Fonts:** `PdfContentByte.showText(GlyphVector)` honors the X positions of the glyphs, so complex scripts such as Devanagari are placed correctly (PR #1804, port of #1618). * **Tagged PDF:** Structure elements after a marked-content identifier in the kids of an element are written to the structure tree (PR #1804). * **HTML colors:** `WebColors.getRGBColor` throws an `IllegalArgumentException`, as documented, for an `rgb()` or `rgba()` value with fewer than three components instead of a `NoSuchElementException` (PR #1801). +* **PDF/X:** The info dictionary of a PDF/X document gets a `/ModDate`, which PDF/X requires, and the XMP metadata repeats `/Trapped` as `pdf:Trapped` (PR #1809). ## ๐Ÿงน Maintenance & Refactoring diff --git a/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfWriter.java b/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfWriter.java index 8d98f22fb..d45f0d2de 100644 --- a/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfWriter.java +++ b/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfWriter.java @@ -417,6 +417,14 @@ public class PdfWriter extends DocWriter implements * PDFA-3U level. */ public static final int PDFA3U = 10; + /** + * PDF/X-4 (ISO 15930-7:2010), the exchange format for print production that allows transparency, layers and ICC + * based colour. The document is written as PDF 1.6. It needs an output intent with an ICC profile, see + * {@link #setOutputIntents(String, String, String, String, java.awt.color.ICC_Profile)}, and all fonts must be + * embedded. The XMP metadata with the PDF/X-4 identification is created when the document is closed, unless it was + * set before. + */ + public static final int PDFX4 = 11; /** * No encryption */ @@ -1358,6 +1366,10 @@ public void close() { PdfIndirectReference rootRef = root.writePageTree(); // make the catalog-object and add it to the body PdfDictionary catalog = getCatalog(rootRef); + // PDF/X-4 requires XMP metadata with its identification + if (xmpMetadata == null && isPdfX4()) { + createXmpMetadata(); + } // [C9] if there is XMP data to add: add it if (xmpMetadata != null) { PdfStream xmp = new PdfStream(xmpMetadata); @@ -1888,6 +1900,10 @@ public void addXmpSchema(XmpSchema schema, PdfAExtensionSchema.Schema descriptio */ private byte[] createXmpMetadataBytes() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); + if (isPdfX4()) { + // the metadata of PDF/X-4 repeats the PDF/X keys of the info dictionary, such as Trapped + pdfxConformance.completeInfoDictionary(getInfo()); + } try { XmpWriter xmp = new XmpWriter(baos, pdf.getInfo(), pdfxConformance.getPDFXConformance()); for (XmpSchema schema : additionalXmpSchemas) { @@ -1933,6 +1949,8 @@ public void setPDFXConformance(int pdfx) { } else if (pdfx == PDFA2A || pdfx == PDFA2B || pdfx == PDFA2U || pdfx == PDFA3A || pdfx == PDFA3B || pdfx == PDFA3U) { setPdfVersion(VERSION_1_7); + } else if (pdfx == PDFX4) { + setPdfVersion(VERSION_1_6); } else if (pdfx != PDFXNONE) { setPdfVersion(VERSION_1_3); } @@ -1946,6 +1964,15 @@ public boolean isPdfX() { return pdfxConformance.isPdfX(); } + /** + * Checks if the PDF has to be in conformance with PDF/X-4. + * + * @return true if the PDF has to be in conformance with PDF/X-4 + */ + public boolean isPdfX4() { + return pdfxConformance.isPdfX4(); + } + // [F12] tagged PDF public boolean isPdfA1() { diff --git a/openpdf-core/src/main/java/org/openpdf/text/pdf/internal/PdfXConformanceImp.java b/openpdf-core/src/main/java/org/openpdf/text/pdf/internal/PdfXConformanceImp.java index 5646f469c..18477ce81 100644 --- a/openpdf-core/src/main/java/org/openpdf/text/pdf/internal/PdfXConformanceImp.java +++ b/openpdf-core/src/main/java/org/openpdf/text/pdf/internal/PdfXConformanceImp.java @@ -54,6 +54,7 @@ import org.openpdf.text.pdf.ExtendedColor; import org.openpdf.text.pdf.PatternColor; import org.openpdf.text.pdf.PdfArray; +import org.openpdf.text.pdf.PdfDate; import org.openpdf.text.pdf.PdfDictionary; import org.openpdf.text.pdf.PdfGState; import org.openpdf.text.pdf.PdfImage; @@ -229,24 +230,24 @@ public static void checkPDFXConformance(PdfWriter writer, int key, Object obj1) /** * Tells if the conformance level of the writer allows transparency: soft masks, constant alpha and blend modes. - * PDF/A-2 and PDF/A-3 allow it, PDF/A-1, PDF/X-1a and PDF/X-3 do not. + * PDF/A-2, PDF/A-3 and PDF/X-4 allow it, PDF/A-1, PDF/X-1a and PDF/X-3 do not. * * @param writer the writer * @return {@code true} if transparency is allowed */ private static boolean allowsTransparency(PdfWriter writer) { - return writer.isPdfA2() || writer.isPdfA3(); + return writer.isPdfA2() || writer.isPdfA3() || writer.isPdfX4(); } /** - * Tells if the conformance level of the writer allows optional content (layers). PDF/A-2 and PDF/A-3 allow it, - * PDF/A-1, PDF/X-1a and PDF/X-3 do not. + * Tells if the conformance level of the writer allows optional content (layers). PDF/A-2, PDF/A-3 and PDF/X-4 + * allow it, PDF/A-1, PDF/X-1a and PDF/X-3 do not. * * @param writer the writer * @return {@code true} if optional content is allowed */ private static boolean allowsOptionalContent(PdfWriter writer) { - return writer.isPdfA2() || writer.isPdfA3(); + return writer.isPdfA2() || writer.isPdfA3() || writer.isPdfX4(); } /** @@ -286,6 +287,15 @@ public boolean isPdfX1A2001() { * * @return true of the PDF has to be in conformance with PDF/X-3:2002 */ + /** + * Checks if the PDF has to be in conformance with PDF/X-4. + * + * @return true if the PDF has to be in conformance with PDF/X-4 + */ + public boolean isPdfX4() { + return pdfxConformance == PdfWriter.PDFX4; + } + public boolean isPdfX32002() { return pdfxConformance == PdfWriter.PDFX32002; } @@ -347,6 +357,8 @@ public void completeInfoDictionary(PdfDictionary info) { info.put(new PdfName("GTS_PDFXConformance"), new PdfString("PDF/X-1a:2001")); } else if (isPdfX32002()) { info.put(PdfName.GTS_PDFXVERSION, new PdfString("PDF/X-3:2002")); + } else if (isPdfX4()) { + info.put(PdfName.GTS_PDFXVERSION, new PdfString("PDF/X-4")); } } if (info.get(PdfName.TITLE) == null) { @@ -358,10 +370,19 @@ public void completeInfoDictionary(PdfDictionary info) { if (info.get(PdfName.TRAPPED) == null) { info.put(PdfName.TRAPPED, new PdfName("False")); } + // PDF/X requires the modification date as well as the creation date + if (info.get(PdfName.MODDATE) == null) { + PdfObject creationDate = info.get(PdfName.CREATIONDATE); + info.put(PdfName.MODDATE, creationDate != null ? creationDate : new PdfDate()); + } } } public void completeExtraCatalog(PdfDictionary extraCatalog) { + if (isPdfX4()) { + checkPdfX4OutputIntent(extraCatalog); + return; + } if (isPdfX() && !isPdfA()) { if (extraCatalog.get(PdfName.OUTPUTINTENTS) == null) { PdfDictionary out = new PdfDictionary(PdfName.OUTPUTINTENT); @@ -374,4 +395,26 @@ public void completeExtraCatalog(PdfDictionary extraCatalog) { } } } + + /** + * Checks that a PDF/X-4 document has a PDF/X output intent with an embedded ICC profile (ISO 15930-7, 6.2.4). Unlike + * PDF/X-1a and PDF/X-3, PDF/X-4 does not allow an output intent that only names a registered characterization. + * + * @param extraCatalog the extra keys of the catalog, with the output intents + * @throws PdfXConformanceException if the output intent or its ICC profile is missing + */ + private static void checkPdfX4OutputIntent(PdfDictionary extraCatalog) { + PdfArray outputIntents = extraCatalog.getAsArray(PdfName.OUTPUTINTENTS); + if (outputIntents != null) { + for (int i = 0; i < outputIntents.size(); i++) { + PdfDictionary outputIntent = outputIntents.getAsDict(i); + if (outputIntent != null && PdfName.GTS_PDFX.equals(outputIntent.getAsName(PdfName.S)) + && outputIntent.get(PdfName.DESTOUTPUTPROFILE) != null) { + return; + } + } + } + throw new PdfXConformanceException("PDF/X-4 requires an output intent with an ICC profile. " + + "Use PdfWriter.setOutputIntents(String, String, String, String, ICC_Profile)."); + } } diff --git a/openpdf-core/src/main/java/org/openpdf/text/xml/xmp/PdfSchema.java b/openpdf-core/src/main/java/org/openpdf/text/xml/xmp/PdfSchema.java index 7bab46b36..db21d6871 100644 --- a/openpdf-core/src/main/java/org/openpdf/text/xml/xmp/PdfSchema.java +++ b/openpdf-core/src/main/java/org/openpdf/text/xml/xmp/PdfSchema.java @@ -76,6 +76,10 @@ public class PdfSchema extends XmpSchema { * The Producer. */ public static final String PRODUCER = "pdf:Producer"; + /** + * Tells if the document has been trapped: True, False or Unknown. + */ + public static final String TRAPPED = "pdf:Trapped"; private static final long serialVersionUID = -1541148669123992185L; diff --git a/openpdf-core/src/main/java/org/openpdf/text/xml/xmp/XmpWriter.java b/openpdf-core/src/main/java/org/openpdf/text/xml/xmp/XmpWriter.java index 96e3dee6a..5c438e789 100644 --- a/openpdf-core/src/main/java/org/openpdf/text/xml/xmp/XmpWriter.java +++ b/openpdf-core/src/main/java/org/openpdf/text/xml/xmp/XmpWriter.java @@ -59,6 +59,7 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Map; +import java.util.UUID; /** * With this class you can create an Xmp Stream that can be used for adding Metadata to a PDF Dictionary. Remark that @@ -194,6 +195,12 @@ public XmpWriter(OutputStream os, PdfDictionary info, int PdfXConformance) throw } if (PdfName.MODDATE.equals(key)) { basic.addModDate(((PdfDate) obj).getW3CDate()); + if (PdfXConformance == PdfWriter.PDFX4) { + basic.setProperty(XmpBasicSchema.METADATADATE, ((PdfDate) obj).getW3CDate()); + } + } + if (PdfName.TRAPPED.equals(key) && obj.isName()) { + p.setProperty(PdfSchema.TRAPPED, PdfName.decodeName(obj.toString())); } } if (dc.size() > 0) { @@ -237,6 +244,8 @@ public XmpWriter(OutputStream os, PdfDictionary info, int PdfXConformance) throw pdfA3Schema.addConformance("U"); } addRdfDescription(pdfA3Schema); + } else if (PdfXConformance == PdfWriter.PDFX4) { + addPdfX4Identification(); } } } @@ -302,6 +311,22 @@ public XmpWriter(OutputStream os, Map info) throws IOException { /** * Sets the XMP to read-only */ + /** + * Writes the identification of PDF/X-4 (ISO 15930-7, 6.2.2): the version in {@code pdfxid:GTS_PDFXVersion} and + * the document ID, version ID and rendition class of the XMP media management schema. + * + * @throws IOException on error + */ + private void addPdfX4Identification() throws IOException { + addRdfDescription("xmlns:pdfxid=\"http://www.npes.org/pdfx/ns/id/\"", + "PDF/X-4"); + XmpMMSchema mm = new XmpMMSchema(); + mm.setProperty(XmpMMSchema.DOCUMENTID, "uuid:" + UUID.randomUUID()); + mm.setProperty(XmpMMSchema.VERSIONID, "1"); + mm.setProperty(XmpMMSchema.RENDITIONCLASS, "default"); + addRdfDescription(mm); + } + public void setReadOnly() { end = 'r'; } diff --git a/openpdf-core/src/test/java/org/openpdf/text/pdf/PdfX4Test.java b/openpdf-core/src/test/java/org/openpdf/text/pdf/PdfX4Test.java new file mode 100644 index 000000000..d0ac85408 --- /dev/null +++ b/openpdf-core/src/test/java/org/openpdf/text/pdf/PdfX4Test.java @@ -0,0 +1,165 @@ +package org.openpdf.text.pdf; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.awt.color.ColorSpace; +import java.awt.color.ICC_Profile; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; +import org.openpdf.text.Document; +import org.openpdf.text.Font; +import org.openpdf.text.PageSize; +import org.openpdf.text.Paragraph; + +/** + * Tests PDF/X-4 (ISO 15930-7:2010) output. veraPDF does not validate PDF/X, so the tests check the requirements of + * the standard in the written file. + */ +class PdfX4Test { + + private static final String FONT = "/fonts/liberation/LiberationSerif-Regular.ttf"; + + @Test + void pdfX4DocumentHasTheRequiredStructure() throws Exception { + byte[] pdf = createPdfX4(true, true); + + assertThat(new String(pdf, 0, 8, StandardCharsets.ISO_8859_1)).isEqualTo("%PDF-1.6"); + try (PdfReader reader = new PdfReader(pdf)) { + assertThat(reader.getInfo()) + .containsEntry("GTS_PDFXVersion", "PDF/X-4") + .containsEntry("Title", "PDF/X-4 test") + .containsKey("CreationDate") + .containsKey("ModDate"); + assertThat(reader.getTrailer().getAsDict(PdfName.INFO).getAsName(PdfName.TRAPPED)) + .isEqualTo(new PdfName("False")); + assertThat(reader.isEncrypted()).isFalse(); + + String xmp = new String(reader.getMetadata(), StandardCharsets.UTF_8); + assertThat(xmp).contains("PDF/X-4") + .containsPattern("uuid:[0-9a-f-]{36}") + .contains("1") + .contains("default") + .contains("False") + .contains("") + .contains("") + .contains("") + .contains("PDF/X-4 test"); + + PdfDictionary outputIntent = reader.getCatalog().getAsArray(PdfName.OUTPUTINTENTS).getAsDict(0); + assertThat(outputIntent.getAsName(PdfName.S)).isEqualTo(PdfName.GTS_PDFX); + assertThat(outputIntent.get(PdfName.DESTOUTPUTPROFILE)).isNotNull(); + + PdfDictionary page = reader.getPageN(1); + assertThat(page.get(PdfName.TRIMBOX) != null || page.get(PdfName.ARTBOX) != null).isTrue(); + // transparency and layers are allowed in PDF/X-4 + assertThat(reader.getCatalog().get(PdfName.OCPROPERTIES)).isNotNull(); + } + } + + @Test + void metadataThatWasSetIsKept() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (Document document = new Document(PageSize.A4)) { + PdfWriter writer = PdfWriter.getInstance(document, out); + writer.setPDFXConformance(PdfWriter.PDFX4); + document.open(); + setOutputIntent(writer); + document.add(new Paragraph("Text", embeddedFont())); + writer.getInfo().put(PdfName.TRAPPED, new PdfName("True")); + writer.createXmpMetadata(); + } + + try (PdfReader reader = new PdfReader(out.toByteArray())) { + String xmp = new String(reader.getMetadata(), StandardCharsets.UTF_8); + assertThat(xmp).contains("True") + .contains("PDF/X-4"); + assertThat(reader.getTrailer().getAsDict(PdfName.INFO).getAsName(PdfName.TRAPPED)) + .isEqualTo(new PdfName("True")); + } + } + + @Test + void outputIntentWithoutIccProfileIsRejected() { + assertThatThrownBy(() -> createPdfX4(false, false)) + .isInstanceOf(PdfXConformanceException.class) + .hasMessageContaining("ICC profile"); + } + + @Test + void fontThatIsNotEmbeddedIsRejected() { + assertThatThrownBy(() -> { + try (Document document = new Document(PageSize.A4)) { + PdfWriter writer = PdfWriter.getInstance(document, new ByteArrayOutputStream()); + writer.setPDFXConformance(PdfWriter.PDFX4); + document.open(); + setOutputIntent(writer); + document.add(new Paragraph("Text", new Font(BaseFont.createFont(BaseFont.HELVETICA, + BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 12))); + } + }).hasRootCauseInstanceOf(PdfXConformanceException.class); + } + + @Test + void pdfX1aStillRejectsTransparency() { + assertThatThrownBy(() -> { + try (Document document = new Document(PageSize.A4)) { + PdfWriter writer = PdfWriter.getInstance(document, new ByteArrayOutputStream()); + writer.setPDFXConformance(PdfWriter.PDFX1A2001); + document.open(); + PdfGState gState = new PdfGState(); + gState.setFillOpacity(0.5f); + writer.getDirectContent().setGState(gState); + } + }).isInstanceOf(PdfXConformanceException.class); + } + + private static byte[] createPdfX4(boolean withProfile, boolean withTransparencyAndLayer) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (Document document = new Document(PageSize.A4)) { + PdfWriter writer = PdfWriter.getInstance(document, out); + writer.setPDFXConformance(PdfWriter.PDFX4); + document.addTitle("PDF/X-4 test"); + document.open(); + if (withProfile) { + setOutputIntent(writer); + } else { + writer.setOutputIntents("CGATS TR 001", "SWOP", "http://www.color.org", null, (ICC_Profile) null); + } + document.add(new Paragraph("PDF/X-4 document created by OpenPDF", embeddedFont())); + if (withTransparencyAndLayer) { + PdfContentByte cb = writer.getDirectContent(); + PdfLayer layer = new PdfLayer("Varnish", writer); + cb.beginLayer(layer); + cb.saveState(); + PdfGState gState = new PdfGState(); + gState.setFillOpacity(0.5f); + gState.setBlendMode(PdfGState.BM_MULTIPLY); + cb.setGState(gState); + cb.setCMYKColorFill(0, 255, 255, 0); + cb.rectangle(100, 400, 200, 100); + cb.fill(); + cb.restoreState(); + cb.endLayer(); + } + } + return out.toByteArray(); + } + + private static void setOutputIntent(PdfWriter writer) throws IOException { + // a real print job uses the CMYK profile of the printing condition, for example FOGRA39 + writer.setOutputIntents("sRGB IEC61966-2.1", null, "http://www.color.org", "sRGB IEC61966-2.1", + ICC_Profile.getInstance(ColorSpace.CS_sRGB)); + } + + private static Font embeddedFont() throws IOException { + try (InputStream in = PdfX4Test.class.getResourceAsStream(FONT)) { + assertThat(in).isNotNull(); + return new Font(BaseFont.createFont("LiberationSerif-Regular.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, + true, in.readAllBytes(), null), 12); + } + } +}