From 615bf36dc62bb38eeb5b3bfc4736427fbd42e70b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20R=C3=B8sdal?= Date: Wed, 2 Dec 2026 22:25:11 +0100 Subject: [PATCH 1/2] Validate PDF/A and PDF/UA output with veraPDF and fix PDF/A-2/A-3 VeraPdfConformanceTest creates documents with text in an embedded font, a JPEG image, a table, a link, transparency, an image with an alpha channel and a layer, and validates them with veraPDF as PDF/A-1b, PDF/A-2b, PDF/A-2u, PDF/A-3b, PDF/A-3u and PDF/UA-1. The tests found that PDF/A-2 and PDF/A-3 documents could not be created with features these standards allow: - PdfXConformanceImp rejected transparency, images with an /SMask and layers for every PDF/A part. Only PDF/A-1, PDF/X-1a and PDF/X-3 forbid them. - TrueTypeFontUnicode wrote a CIDSet with only the used CIDs. PDF/A-2 and PDF/A-3 (6.2.11.4.2) require all CIDs of the font program, and the CIDSet is optional there, so it is left out. - The default optional content configuration had no /Name and could have an /AS entry, which PDF/A-2 and PDF/A-3 (6.9) do not allow. Co-Authored-By: Claude Opus 5.5 --- changelogs/4.0.1.md | 5 + .../java/org/openpdf/text/pdf/PdfWriter.java | 13 +- .../openpdf/text/pdf/TrueTypeFontUnicode.java | 5 + .../text/pdf/internal/PdfXConformanceImp.java | 32 +- .../validation/VeraPdfConformanceTest.java | 279 ++++++++++++++++++ 5 files changed, 328 insertions(+), 6 deletions(-) create mode 100644 openpdf-core/src/test/java/org/openpdf/text/validation/VeraPdfConformanceTest.java diff --git a/changelogs/4.0.1.md b/changelogs/4.0.1.md index 19b1ea75a8..dc2442b9d8 100644 --- a/changelogs/4.0.1.md +++ b/changelogs/4.0.1.md @@ -4,3 +4,8 @@ ## 🛠 Bug Fixes * Fix rendering and extraction when a TrueType glyph index matches a BMP character code (#1793). +* **PDF/A-2 and PDF/A-3:** Transparency, images with an alpha channel (`/SMask`) and layers are allowed, as these standards permit. Before, `PdfWriter` rejected them as for PDF/A-1. Fonts in Identity-H encoding no longer write an incomplete `CIDSet`, and the optional content configuration gets a `/Name` and no `/AS` entry. + +## 🧹 Maintenance & Refactoring + +* **Tests:** `VeraPdfConformanceTest` validates documents created by OpenPDF with veraPDF for PDF/A-1b, PDF/A-2b, PDF/A-2u, PDF/A-3b, PDF/A-3u and PDF/UA-1. 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 88f701cceb..974207fb1d 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 @@ -2532,6 +2532,8 @@ protected void fillOCProperties(boolean erase) { } PdfDictionary d = new PdfDictionary(); OCProperties.put(PdfName.D, d); + // PDF/A-2 and PDF/A-3 (rule 6.9) require a name for the optional content configuration + d.put(PdfName.NAME, new PdfString("Default")); d.put(PdfName.ORDER, order); PdfArray gr = new PdfArray(); for (PdfOCG o : documentOCG) { @@ -2549,10 +2551,13 @@ protected void fillOCProperties(boolean erase) { if (OCGLocked != null && !OCGLocked.isEmpty()) { d.put(PdfName.LOCKED, OCGLocked); } - addASEvent(PdfName.VIEW, PdfName.ZOOM); - addASEvent(PdfName.VIEW, PdfName.VIEW); - addASEvent(PdfName.PRINT, PdfName.PRINT); - addASEvent(PdfName.EXPORT, PdfName.EXPORT); + // PDF/A-2 and PDF/A-3 (rule 6.9) do not allow the AS key in the optional content configuration + if (!isPdfA()) { + addASEvent(PdfName.VIEW, PdfName.ZOOM); + addASEvent(PdfName.VIEW, PdfName.VIEW); + addASEvent(PdfName.PRINT, PdfName.PRINT); + addASEvent(PdfName.EXPORT, PdfName.EXPORT); + } d.put(PdfName.LISTMODE, PdfName.VISIBLEPAGES); } diff --git a/openpdf-core/src/main/java/org/openpdf/text/pdf/TrueTypeFontUnicode.java b/openpdf-core/src/main/java/org/openpdf/text/pdf/TrueTypeFontUnicode.java index 08af36b6cd..5ee73fa2a9 100644 --- a/openpdf-core/src/main/java/org/openpdf/text/pdf/TrueTypeFontUnicode.java +++ b/openpdf-core/src/main/java/org/openpdf/text/pdf/TrueTypeFontUnicode.java @@ -558,6 +558,11 @@ private PdfIndirectReference writeCidSet(PdfWriter writer, int[][] metrics) thro && writer.getPDFXConformance() != PdfWriter.PDFA1B) { return null; } + // PDF/A-2 and PDF/A-3 (rule 6.2.11.4.2) require a CIDSet to identify all CIDs of the font program, also of a + // subset. The CIDSet is optional there, so it is left out. + if (writer.isPdfA2() || writer.isPdfA3()) { + return null; + } PdfStream stream; if (metrics.length == 0) { stream = new PdfStream(new byte[]{(byte) 0x80}); 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 e886188e3e..5646f469c6 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 @@ -169,7 +169,7 @@ public static void checkPDFXConformance(PdfWriter writer, int key, Object obj1) } case PDFXKEY_IMAGE -> { PdfImage image = (PdfImage) obj1; - if (image.get(PdfName.SMASK) != null) { + if (image.get(PdfName.SMASK) != null && !allowsTransparency(writer)) { throw new PdfXConformanceException( MessageLocalization.getComposedMessage("the.smask.key.is.not.allowed.in.images")); } @@ -194,6 +194,9 @@ public static void checkPDFXConformance(PdfWriter writer, int key, Object obj1) } } case PDFXKEY_GSTATE -> { + if (allowsTransparency(writer)) { + return; + } PdfDictionary gs = (PdfDictionary) obj1; PdfObject obj = gs.get(PdfName.BM); if (obj != null && !PdfGState.BM_NORMAL.equals(obj) && !PdfGState.BM_COMPATIBLE.equals(obj)) { @@ -216,11 +219,36 @@ public static void checkPDFXConformance(PdfWriter writer, int key, Object obj1) } } case PDFXKEY_LAYER -> { - throw new PdfXConformanceException(MessageLocalization.getComposedMessage("layers.are.not.allowed")); + if (!allowsOptionalContent(writer)) { + throw new PdfXConformanceException( + MessageLocalization.getComposedMessage("layers.are.not.allowed")); + } } } } + /** + * 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. + * + * @param writer the writer + * @return {@code true} if transparency is allowed + */ + private static boolean allowsTransparency(PdfWriter writer) { + return writer.isPdfA2() || writer.isPdfA3(); + } + + /** + * 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. + * + * @param writer the writer + * @return {@code true} if optional content is allowed + */ + private static boolean allowsOptionalContent(PdfWriter writer) { + return writer.isPdfA2() || writer.isPdfA3(); + } + /** * @see org.openpdf.text.pdf.interfaces.PdfXConformance#getPDFXConformance() */ diff --git a/openpdf-core/src/test/java/org/openpdf/text/validation/VeraPdfConformanceTest.java b/openpdf-core/src/test/java/org/openpdf/text/validation/VeraPdfConformanceTest.java new file mode 100644 index 0000000000..254bbc42a7 --- /dev/null +++ b/openpdf-core/src/test/java/org/openpdf/text/validation/VeraPdfConformanceTest.java @@ -0,0 +1,279 @@ +package org.openpdf.text.validation; + +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.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.openpdf.text.Chunk; +import org.openpdf.text.Document; +import org.openpdf.text.Font; +import org.openpdf.text.Image; +import org.openpdf.text.PageSize; +import org.openpdf.text.Paragraph; +import org.openpdf.text.Phrase; +import org.openpdf.text.pdf.BaseFont; +import org.openpdf.text.pdf.PdfBoolean; +import org.openpdf.text.pdf.PdfContentByte; +import org.openpdf.text.pdf.PdfGState; +import org.openpdf.text.pdf.PdfLayer; +import org.openpdf.text.pdf.PdfName; +import org.openpdf.text.pdf.PdfPCell; +import org.openpdf.text.pdf.PdfPTable; +import org.openpdf.text.pdf.PdfString; +import org.openpdf.text.pdf.PdfStructureElement; +import org.openpdf.text.pdf.PdfWriter; +import org.openpdf.text.pdf.PdfXConformanceException; +import org.openpdf.text.xml.xmp.DublinCoreSchema; +import org.openpdf.text.xml.xmp.XmpWriter; +import org.verapdf.gf.model.GFModelParser; +import org.verapdf.pdfa.PDFAValidator; +import org.verapdf.pdfa.flavours.PDFAFlavour; +import org.verapdf.pdfa.results.TestAssertion; +import org.verapdf.pdfa.results.ValidationResult; +import org.verapdf.pdfa.validation.validators.ValidatorFactory; + +/** + * Validates PDF documents created by OpenPDF with veraPDF, for several parts and levels of PDF/A and for PDF/UA-1. + */ +class VeraPdfConformanceTest { + + private static final String FONT = "/fonts/liberation/LiberationSerif-Regular.ttf"; + + @Test + void pdfA1bWithTextImageTableAndLink() throws Exception { + byte[] pdf = createPdfA(PdfWriter.PDFA1B, false); + + assertCompliant(pdf, PDFAFlavour.PDFA_1_B); + } + + @Test + void pdfA2bWithTextImageTableLinkAndTransparency() throws Exception { + byte[] pdf = createPdfA(PdfWriter.PDFA2B, true); + + assertCompliant(pdf, PDFAFlavour.PDFA_2_B); + } + + @Test + void pdfA2uWithTextImageTableLinkAndTransparency() throws Exception { + byte[] pdf = createPdfA(PdfWriter.PDFA2U, true); + + assertCompliant(pdf, PDFAFlavour.PDFA_2_U); + } + + @Test + void pdfA3bWithTextImageTableLinkAndTransparency() throws Exception { + byte[] pdf = createPdfA(PdfWriter.PDFA3B, true); + + assertCompliant(pdf, PDFAFlavour.PDFA_3_B); + } + + @Test + void pdfA3uWithTextImageTableLinkAndTransparency() throws Exception { + byte[] pdf = createPdfA(PdfWriter.PDFA3U, true); + + assertCompliant(pdf, PDFAFlavour.PDFA_3_U); + } + + @Test + void pdfA2bWithImageWithAlphaChannelAndLayer() throws Exception { + byte[] pdf = createPdfAWithAlphaImageAndLayer(PdfWriter.PDFA2B); + + assertCompliant(pdf, PDFAFlavour.PDFA_2_B); + } + + @Test + void pdfA3bWithImageWithAlphaChannelAndLayer() throws Exception { + byte[] pdf = createPdfAWithAlphaImageAndLayer(PdfWriter.PDFA3B); + + assertCompliant(pdf, PDFAFlavour.PDFA_3_B); + } + + @Test + void pdfA1bStillRejectsTransparency() { + assertThatThrownBy(() -> createPdfA(PdfWriter.PDFA1B, true)) + .isInstanceOf(PdfXConformanceException.class) + .hasMessageContaining("Transparency"); + } + + @Test + void pdfA1bStillRejectsImageWithAlphaChannel() { + assertThatThrownBy(() -> createPdfAWithAlphaImageAndLayer(PdfWriter.PDFA1B)) + .hasRootCauseInstanceOf(PdfXConformanceException.class); + } + + @Test + void pdfUa1WithTaggedHeadingAndParagraph() throws Exception { + byte[] pdf = createPdfUa(); + + assertCompliant(pdf, PDFAFlavour.PDFUA_1); + } + + private static byte[] createPdfA(int conformance, boolean transparency) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Document document = new Document(PageSize.A4); + try { + PdfWriter writer = PdfWriter.getInstance(document, out); + writer.setPDFXConformance(conformance); + document.addTitle("OpenPDF PDF/A test"); + document.addAuthor("OpenPDF"); + document.addSubject("veraPDF validation"); + document.addKeywords("PDF/A, veraPDF"); + document.addCreator("OpenPDF tests"); + document.open(); + writer.setOutputIntents("sRGB IEC61966-2.1", null, "http://www.color.org", "sRGB IEC61966-2.1", + ICC_Profile.getInstance(ColorSpace.CS_sRGB)); + + Font font = new Font(BaseFont.createFont("LiberationSerif-Regular.ttf", BaseFont.IDENTITY_H, + BaseFont.EMBEDDED, true, readResource(FONT), null), 12); + document.add(new Paragraph("PDF/A document created by OpenPDF: Grüße, Ærø, Ελληνικά.", font)); + + Image image = Image.getInstance(readResource("/imageTest/ImageTest.jpg")); + image.scaleToFit(200, 200); + document.add(image); + + PdfPTable table = new PdfPTable(2); + for (String text : new String[]{"Name", "Value", "Conformance", String.valueOf(conformance)}) { + table.addCell(new PdfPCell(new Phrase(text, font))); + } + document.add(table); + + Chunk link = new Chunk("https://github.com/LibrePDF/OpenPDF", font); + link.setAnchor("https://github.com/LibrePDF/OpenPDF"); + document.add(new Paragraph(link)); + + if (transparency) { + PdfContentByte cb = writer.getDirectContent(); + cb.saveState(); + PdfGState gState = new PdfGState(); + gState.setFillOpacity(0.5f); + cb.setGState(gState); + cb.setRGBColorFill(200, 30, 30); + cb.rectangle(300, 100, 200, 100); + cb.fill(); + cb.restoreState(); + } + writer.createXmpMetadata(); + } finally { + closeQuietly(document); + } + return out.toByteArray(); + } + + private static byte[] createPdfAWithAlphaImageAndLayer(int conformance) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Document document = new Document(PageSize.A4); + try { + PdfWriter writer = PdfWriter.getInstance(document, out); + writer.setPDFXConformance(conformance); + document.addTitle("OpenPDF PDF/A test with an alpha channel and a layer"); + document.open(); + writer.setOutputIntents("sRGB IEC61966-2.1", null, "http://www.color.org", "sRGB IEC61966-2.1", + ICC_Profile.getInstance(ColorSpace.CS_sRGB)); + + // a PNG image with an alpha channel is written with an /SMask + Image image = Image.getInstance(readResource("/GitHub-Mark-32px.png")); + image.setAbsolutePosition(100, 600); + PdfContentByte cb = writer.getDirectContent(); + cb.addImage(image); + + PdfLayer layer = new PdfLayer("Background", writer); + layer.setPrint("Print", true); + cb.beginLayer(layer); + cb.setRGBColorFill(30, 120, 200); + cb.rectangle(100, 400, 200, 100); + cb.fill(); + cb.endLayer(); + writer.createXmpMetadata(); + } finally { + closeQuietly(document); + } + return out.toByteArray(); + } + + private static byte[] createPdfUa() throws Exception { + String title = "OpenPDF PDF/UA test"; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (Document document = new Document(PageSize.A4)) { + PdfWriter writer = PdfWriter.getInstance(document, out); + writer.setPdfVersion(PdfWriter.VERSION_1_7); + writer.setTagged(); + writer.getExtraCatalog().put(PdfName.LANG, new PdfString("en-US")); + document.addTitle(title); + document.open(); + writer.addViewerPreference(PdfName.DISPLAYDOCTITLE, PdfBoolean.PDFTRUE); + writer.setXmpMetadata(pdfUaXmp(title)); + + BaseFont font = BaseFont.createFont("LiberationSerif-Regular.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, + true, readResource(FONT), null); + PdfContentByte cb = writer.getDirectContent(); + PdfStructureElement root = new PdfStructureElement(writer.getStructureTreeRoot(), PdfName.DOCUMENT); + writeTaggedText(cb, new PdfStructureElement(root, new PdfName("H1")), font, 18, 790, title); + writeTaggedText(cb, new PdfStructureElement(root, PdfName.P), font, 12, 760, + "A tagged document with a heading and a paragraph."); + } + return out.toByteArray(); + } + + private static void writeTaggedText(PdfContentByte cb, PdfStructureElement element, BaseFont font, float size, + float y, String text) { + cb.beginMarkedContentSequence(element); + cb.beginText(); + cb.setFontAndSize(font, size); + cb.setTextMatrix(72, y); + cb.showText(text); + cb.endText(); + cb.endMarkedContentSequence(); + } + + private static byte[] pdfUaXmp(String title) throws IOException { + ByteArrayOutputStream xmp = new ByteArrayOutputStream(); + try (XmpWriter writer = new XmpWriter(xmp)) { + DublinCoreSchema dc = new DublinCoreSchema(); + dc.addTitle(title); + writer.addRdfDescription(dc); + writer.addRdfDescription("xmlns:pdfuaid=\"http://www.aiim.org/pdfua/ns/id/\"", + "1"); + } + return xmp.toByteArray(); + } + + private static void closeQuietly(Document document) { + try { + document.close(); + } catch (RuntimeException e) { + // the document is incomplete after a conformance exception + } + } + + private static void assertCompliant(byte[] pdf, PDFAFlavour flavour) throws Exception { + List failures = validate(pdf, flavour); + assertThat(failures).as("veraPDF %s violations", flavour.getId()).isEmpty(); + } + + private static List validate(byte[] pdf, PDFAFlavour flavour) throws Exception { + try (GFModelParser parser = GFModelParser.createModelWithFlavour(new ByteArrayInputStream(pdf), flavour)) { + PDFAValidator validator = ValidatorFactory.createValidator(flavour, false, 100); + ValidationResult result = validator.validate(parser); + return result.getTestAssertions().stream() + .filter(assertion -> assertion.getStatus() == TestAssertion.Status.FAILED) + .map(assertion -> assertion.getRuleId().getClause() + "-" + assertion.getRuleId().getTestNumber() + + ": " + assertion.getMessage()) + .distinct() + .toList(); + } + } + + private static byte[] readResource(String name) throws IOException { + try (InputStream in = VeraPdfConformanceTest.class.getResourceAsStream(name)) { + assertThat(in).as(name).isNotNull(); + return in.readAllBytes(); + } + } +} From 99a373ca8d10257b5bbee3532c9be51021d67e8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20R=C3=B8sdal?= Date: Wed, 2 Dec 2026 22:29:11 +0100 Subject: [PATCH 2/2] Complete the changelog of 4.0.1 Add the changes of #1801, #1803, #1804, #1805 and #1806, which were merged without a changelog entry, the pull request number of #1802 and #1807, and the contributors. Co-Authored-By: Claude Opus 5.5 --- changelogs/4.0.1.md | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/changelogs/4.0.1.md b/changelogs/4.0.1.md index dc2442b9d8..b44aea3a02 100644 --- a/changelogs/4.0.1.md +++ b/changelogs/4.0.1.md @@ -1,11 +1,25 @@ # Release Notes - OpenPDF 4.0.1 +## 🌟 New Features & Enhancements + +* **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. + ## 🛠 Bug Fixes -* Fix rendering and extraction when a TrueType glyph index matches a BMP character code (#1793). -* **PDF/A-2 and PDF/A-3:** Transparency, images with an alpha channel (`/SMask`) and layers are allowed, as these standards permit. Before, `PdfWriter` rejected them as for PDF/A-1. Fonts in Identity-H encoding no longer write an incomplete `CIDSet`, and the optional content configuration gets a `/Name` and no `/AS` entry. +* Fix rendering and extraction when a TrueType glyph index matches a BMP character code (PR #1802, fixes #1793). +* **PDF/A-2 and PDF/A-3:** Transparency, images with an alpha channel (`/SMask`) and layers are allowed, as these standards permit. Before, `PdfWriter` rejected them as for PDF/A-1. Fonts in Identity-H encoding no longer write an incomplete `CIDSet`, and the optional content configuration gets a `/Name` and no `/AS` entry (PR #1807). +* **PDF 2.0:** Text strings in UTF-8 are read correctly. `PdfString.toUnicodeString()` decoded them as PDFDocEncoding (PR #1805). +* **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). ## 🧹 Maintenance & Refactoring -* **Tests:** `VeraPdfConformanceTest` validates documents created by OpenPDF with veraPDF for PDF/A-1b, PDF/A-2b, PDF/A-2u, PDF/A-3b, PDF/A-3u and PDF/UA-1. +* **Tests:** `VeraPdfConformanceTest` validates documents created by OpenPDF with veraPDF for PDF/A-1b, PDF/A-2b, PDF/A-2u, PDF/A-3b, PDF/A-3u and PDF/UA-1 (PR #1807). +* **Code Quality:** Codacy no longer checks the changelogs, and the markdownlint rules MD013, MD032 and MD043 are turned off (PR #1803). + +## 👥 Contributors + +Thanks to everyone who contributed to this release: Amal Saidov, Andreas Røsdal, Lucian Chiriță and Yucheng Du.