diff --git a/changelogs/4.0.0.md b/changelogs/4.0.0.md
index c06833435..e12b6b5f7 100644
--- a/changelogs/4.0.0.md
+++ b/changelogs/4.0.0.md
@@ -62,6 +62,13 @@ OpenPDF 3.0.x for Java 21 is maintained in the [3.0-java21](https://github.com/L
`Dilithium2`, `Dilithium3` and `Dilithium5` as ML-DSA-44, ML-DSA-65 and ML-DSA-87. CRYSTALS-Dilithium is a different
algorithm, and its signatures were written under the OIDs of ML-DSA. Signing with a Dilithium key, or
`setExternalDigest` with a Dilithium name, now throws. Use an ML-DSA key.
+* **PDF/A refuses more content that it does not allow (PR #1814).** Both throw a `PdfXConformanceException`:
+ * `PdfWriter.addJavaScript` in a PDF/A document. PDF/A does not allow JavaScript.
+ * In PDF/A-1, a TrueType font with an encoding other than WinAnsi or MacRoman, for example `BaseFont.CP1250`.
+ PDF/A-1 does not allow the `Differences` array that such a font needs. Use `BaseFont.IDENTITY_H`.
+* **`RadioCheckField` keeps the font that is set after `setCheckType` (PR #1814).** Before, the field always went
+ back to ZapfDingbats when it was created. A check type that is drawn with a font, such as `TYPE_CHECK`, shows the
+ character of that font.
## 🔒 Security
These fixes are also in [OpenPDF 3.0.7](3.0.7.md).
@@ -99,6 +106,10 @@ These fixes are also in [OpenPDF 3.0.7](3.0.7.md).
* **Renderer:** `OpenPdfCorePageRenderer` supports the text rendering mode (`Tr`), so that invisible text layers of scanned documents are no longer drawn (PR #1603).
## 🛠 Bug Fixes
+* **PDF/A:** Annotations in PDF/A-2 and PDF/A-3 have the `F` key with the print flag, as they already had in PDF/A-1
+ (PR #1814).
+* **PDF/A:** A TrueType font with an encoding other than WinAnsi or MacRoman, such as `BaseFont.CP1250`, has the
+ base encoding `WinAnsiEncoding`, as PDF/A-2 and PDF/A-3 require (PR #1814).
* **HTML colors:** `WebColors.getRGBColor` now throws an `IllegalArgumentException`, as documented, for an
`rgb()`/`rgba()` value with fewer than three components (for example `rgb()` or `rgb(1,2)`) instead of leaking a
`NoSuchElementException`.
@@ -132,6 +143,9 @@ These fixes are also in [OpenPDF 3.0.7](3.0.7.md).
collections, and argument checks before `super(...)` in three constructors. `checkstyle.xml` allows `_` as the name
of a lambda parameter and of a pattern variable. The behaviour is not changed (PR #1790).
* **Code Quality:** Fixed a bug reported by SonarCloud in the copy constructor of `RandomAccessFileOrArray` (PR #1689), and one in the soft mask of `OpenPdfCorePageRenderer` (PR #1765).
+* **Tests:** veraPDF validates PDF/A documents with the accessible levels 1a, 2a and 3a, bookmarks, a text
+ annotation, form fields, spot colours, shadings, GIF, PNG and TIFF images, fonts with several encodings, pages of
+ different sizes with page labels, and an attached file (PR #1814).
* **Code Quality:** Removed reflective calls of the module API from `PdfGraphics2D`. They were written for Java 8 and
had no effect (PR #1785).
diff --git a/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfAnnotation.java b/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfAnnotation.java
index 602302d96..a4b541c20 100644
--- a/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfAnnotation.java
+++ b/openpdf-core/src/main/java/org/openpdf/text/pdf/PdfAnnotation.java
@@ -919,7 +919,8 @@ public void setName(String name) {
}
private void addFKey() {
- if (writer.isPdfA1()) {
+ // PDF/A requires the F key in all annotations, and the print flag in all that are not a Popup
+ if (writer != null && writer.isPdfA()) {
put(PdfName.F, new PdfNumber(FLAGS_PRINT));
}
}
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 d45f0d2de..93c6e3dc6 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
@@ -1629,8 +1629,10 @@ public void addNamedDestination(String name, int page, PdfDestination dest) {
* runs.
*
* @param js The JavaScript action
+ * @throws PdfXConformanceException if the document is PDF/A, which does not allow JavaScript
*/
public void addJavaScript(PdfAction js) {
+ checkNoJavaScriptInPdfA();
pdf.addJavaScript(js);
}
@@ -1664,11 +1666,19 @@ public void addJavaScript(String code) {
*
* @param name The name of the JS Action in the name tree
* @param js The JavaScript action
+ * @throws PdfXConformanceException if the document is PDF/A, which does not allow JavaScript
*/
public void addJavaScript(String name, PdfAction js) {
+ checkNoJavaScriptInPdfA();
pdf.addJavaScript(name, js);
}
+ private void checkNoJavaScriptInPdfA() {
+ if (isPdfA()) {
+ throw new PdfXConformanceException("JavaScript is not allowed in PDF/A.");
+ }
+ }
+
/**
* Use this method to add a JavaScript action at the document level. When the document opens, all this JavaScript
* runs.
@@ -2244,12 +2254,26 @@ FontDetails addSimple(BaseFont bf) {
FontDetails ret = documentFonts.get(bf);
if (ret == null) {
PdfXConformanceImp.checkPDFXConformance(this, PdfXConformanceImp.PDFXKEY_FONT, bf);
+ checkPdfA1Encoding(bf);
ret = new FontDetails(new PdfName("F" + (fontNumber++)), body.getPdfIndirectReference(), bf);
documentFonts.put(bf, ret);
}
return ret;
}
+ /**
+ * PDF/A-1 does not allow a non-symbolic TrueType font with a Differences array (rule 6.3.7), which OpenPDF writes
+ * for the encodings that are not WinAnsi or MacRoman.
+ */
+ private void checkPdfA1Encoding(BaseFont bf) {
+ if (isPdfA1() && bf instanceof TrueTypeFont ttf && bf.getFontType() == BaseFont.FONT_TYPE_TT && !ttf.cff
+ && !bf.isFontSpecific() && !"Cp1252".equals(bf.getEncoding())
+ && !"MacRoman".equals(bf.getEncoding())) {
+ throw new PdfXConformanceException("PDF/A-1 allows a TrueType font only with the encoding WinAnsi or "
+ + "MacRoman. Use BaseFont.IDENTITY_H for " + bf.getPostscriptFontName() + ".");
+ }
+ }
+
void eliminateFontSubset(PdfDictionary fonts) {
for (FontDetails ft : documentFonts.values()) {
if (fonts.get(ft.getFontName()) != null) {
diff --git a/openpdf-core/src/main/java/org/openpdf/text/pdf/RadioCheckField.java b/openpdf-core/src/main/java/org/openpdf/text/pdf/RadioCheckField.java
index 05cbc4078..56b733a40 100644
--- a/openpdf-core/src/main/java/org/openpdf/text/pdf/RadioCheckField.java
+++ b/openpdf-core/src/main/java/org/openpdf/text/pdf/RadioCheckField.java
@@ -519,8 +519,9 @@ protected PdfFormField getField(boolean isKid) throws IOException, DocumentExcep
}
field.setValueAsName(checked ? onValue : "Off");
- //bugfixed as setting the type wasn't working (also mentioned on the mailinglist on 5th may 2011)
- setCheckType(checkType);
+ // the caption must be the symbol of the check type, but a font that was set after the check type is kept,
+ // so that an embedded font can be used, as PDF/A requires
+ setText(typeChars[checkType - 1]);
}
if (text != null) {
field.setMKNormalCaption(text);
diff --git a/openpdf-core/src/main/java/org/openpdf/text/pdf/TrueTypeFont.java b/openpdf-core/src/main/java/org/openpdf/text/pdf/TrueTypeFont.java
index b63f1c5c9..ba174d249 100644
--- a/openpdf-core/src/main/java/org/openpdf/text/pdf/TrueTypeFont.java
+++ b/openpdf-core/src/main/java/org/openpdf/text/pdf/TrueTypeFont.java
@@ -1300,6 +1300,11 @@ protected PdfDictionary getFontBaseType(PdfIndirectReference fontDescriptor, Str
encoding.equals("Cp1252") ? PdfName.WIN_ANSI_ENCODING : PdfName.MAC_ROMAN_ENCODING);
} else {
PdfDictionary enc = new PdfDictionary(PdfName.ENCODING);
+ if (!cff) {
+ // a non-symbolic TrueType font needs a base encoding for its glyphs to be found by name, and
+ // PDF/A-2 and PDF/A-3 require it (rule 6.2.11.6). All the codes in use are in the differences.
+ enc.put(PdfName.BASEENCODING, PdfName.WIN_ANSI_ENCODING);
+ }
PdfArray dif = new PdfArray();
boolean gap = true;
for (int k = firstChar; k <= lastChar; ++k) {
diff --git a/openpdf-core/src/test/java/org/openpdf/text/pdf/FontSubsetTest.java b/openpdf-core/src/test/java/org/openpdf/text/pdf/FontSubsetTest.java
index b566ed5c8..dcd8a4297 100644
--- a/openpdf-core/src/test/java/org/openpdf/text/pdf/FontSubsetTest.java
+++ b/openpdf-core/src/test/java/org/openpdf/text/pdf/FontSubsetTest.java
@@ -22,8 +22,9 @@ class FontSubsetTest {
*/
@Test
void createSubsetPrefixTest() throws Exception {
+ // not cached: the fixed SecureRandom that is set below must not reach the fonts of other tests
BaseFont font = BaseFont.createFont("LiberationSerif-Regular.ttf", BaseFont.IDENTITY_H,
- BaseFont.EMBEDDED, true, getLiberationFontByte(), null);
+ BaseFont.EMBEDDED, false, getLiberationFontByte(), null);
assertNotEquals(font.createSubsetPrefix(), font.createSubsetPrefix());
byte[] baseSeed = new SecureRandom().generateSeed(512);
diff --git a/openpdf-core/src/test/java/org/openpdf/text/validation/VeraPdfFeatureConformanceTest.java b/openpdf-core/src/test/java/org/openpdf/text/validation/VeraPdfFeatureConformanceTest.java
new file mode 100644
index 000000000..6aaa8ddbc
--- /dev/null
+++ b/openpdf-core/src/test/java/org/openpdf/text/validation/VeraPdfFeatureConformanceTest.java
@@ -0,0 +1,355 @@
+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;
+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.nio.charset.StandardCharsets;
+import java.util.List;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+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.Rectangle;
+import org.openpdf.text.pdf.BaseFont;
+import org.openpdf.text.pdf.PdfAction;
+import org.openpdf.text.pdf.PdfAnnotation;
+import org.openpdf.text.pdf.PdfContentByte;
+import org.openpdf.text.pdf.PdfDate;
+import org.openpdf.text.pdf.PdfDestination;
+import org.openpdf.text.pdf.PdfDictionary;
+import org.openpdf.text.pdf.PdfFileSpecification;
+import org.openpdf.text.pdf.PdfName;
+import org.openpdf.text.pdf.PdfOutline;
+import org.openpdf.text.pdf.PdfPageLabels;
+import org.openpdf.text.pdf.PdfShading;
+import org.openpdf.text.pdf.PdfShadingPattern;
+import org.openpdf.text.pdf.PdfSpotColor;
+import org.openpdf.text.pdf.PdfStream;
+import org.openpdf.text.pdf.PdfString;
+import org.openpdf.text.pdf.PdfTemplate;
+import org.openpdf.text.pdf.PdfStructureElement;
+import org.openpdf.text.pdf.PdfWriter;
+import org.openpdf.text.pdf.PdfXConformanceException;
+import org.openpdf.text.pdf.RadioCheckField;
+import org.openpdf.text.pdf.ShadingColor;
+import org.openpdf.text.pdf.SpotColor;
+import org.openpdf.text.pdf.TextField;
+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 with veraPDF PDF/A documents that use features which {@link VeraPdfConformanceTest} does not cover:
+ * the accessible levels, bookmarks, annotations, form fields, colours, shadings, images, fonts, pages and
+ * attachments.
+ */
+class VeraPdfFeatureConformanceTest {
+
+ private static final String FONT = "/fonts/liberation/LiberationSerif-Regular.ttf";
+
+ @FunctionalInterface
+ private interface Content {
+
+ void write(Document document, PdfWriter writer) throws Exception;
+ }
+
+ @ParameterizedTest
+ @CsvSource({"3, PDFA_1_A", "5, PDFA_2_A", "8, PDFA_3_A"})
+ void accessibleLevelWithTaggedHeadingAndParagraph(int conformance, PDFAFlavour flavour) throws Exception {
+ byte[] pdf = createPdfA(conformance, true, (document, writer) -> {
+ BaseFont font = font(BaseFont.WINANSI);
+ PdfContentByte cb = writer.getDirectContent();
+ PdfStructureElement root = new PdfStructureElement(writer.getStructureTreeRoot(), PdfName.DOCUMENT);
+ writeTaggedText(cb, new PdfStructureElement(root, new PdfName("H1")), font, 18, 790, "Heading");
+ writeTaggedText(cb, new PdfStructureElement(root, PdfName.P), font, 12, 760, "A tagged paragraph.");
+ });
+
+ assertCompliant(pdf, flavour);
+ }
+
+ @ParameterizedTest
+ @CsvSource({"4, PDFA_1_B", "6, PDFA_2_B", "9, PDFA_3_B"})
+ void bookmarksOnSeveralPages(int conformance, PDFAFlavour flavour) throws Exception {
+ byte[] pdf = createPdfA(conformance, (document, writer) -> {
+ Font font = new Font(font(BaseFont.WINANSI), 12);
+ PdfOutline root = writer.getDirectContent().getRootOutline();
+ for (int page = 1; page <= 3; page++) {
+ document.add(new Paragraph("Chapter " + page, font));
+ PdfOutline chapter = new PdfOutline(root,
+ new PdfDestination(PdfDestination.FITH, 800), "Chapter " + page);
+ new PdfOutline(chapter, new PdfDestination(PdfDestination.FIT), "Section " + page + ".1");
+ document.newPage();
+ }
+ });
+
+ assertCompliant(pdf, flavour);
+ }
+
+ @ParameterizedTest
+ @CsvSource({"4, PDFA_1_B", "6, PDFA_2_B", "9, PDFA_3_B"})
+ void textAnnotation(int conformance, PDFAFlavour flavour) throws Exception {
+ byte[] pdf = createPdfA(conformance, (document, writer) -> {
+ document.add(new Paragraph("A page with a note.", new Font(font(BaseFont.WINANSI), 12)));
+ PdfAnnotation note = PdfAnnotation.createText(writer, new Rectangle(100, 600, 120, 620), "Note",
+ "The content of the note.", false, "Comment");
+ // PDF/A requires an appearance, which OpenPDF does not draw for a text annotation
+ PdfTemplate icon = writer.getDirectContent().createTemplate(20, 20);
+ icon.setRGBColorFill(250, 220, 60);
+ icon.rectangle(0, 0, 20, 20);
+ icon.fill();
+ note.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, icon);
+ writer.addAnnotation(note);
+ });
+
+ assertCompliant(pdf, flavour);
+ }
+
+ @ParameterizedTest
+ @CsvSource({"4, PDFA_1_B", "6, PDFA_2_B", "9, PDFA_3_B"})
+ void formWithTextFieldAndCheckBox(int conformance, PDFAFlavour flavour) throws Exception {
+ byte[] pdf = createPdfA(conformance, (document, writer) -> {
+ BaseFont font = font(BaseFont.WINANSI);
+ document.add(new Paragraph("A form.", new Font(font, 12)));
+
+ TextField name = new TextField(writer, new Rectangle(100, 700, 300, 720), "name");
+ name.setFont(font);
+ name.setText("OpenPDF");
+ writer.addAnnotation(name.getTextField());
+
+ RadioCheckField check = new RadioCheckField(writer, new Rectangle(100, 650, 115, 665), "agree", "Yes");
+ // the cross is drawn, and an embedded font replaces ZapfDingbats, which PDF/A does not allow
+ check.setCheckType(RadioCheckField.TYPE_CROSS);
+ check.setFont(font);
+ check.setChecked(true);
+ writer.addAnnotation(check.getFullField());
+ });
+
+ assertCompliant(pdf, flavour);
+ }
+
+ @ParameterizedTest
+ @CsvSource({"4, PDFA_1_B", "6, PDFA_2_B", "9, PDFA_3_B"})
+ void spotColourGrayAndAxialShading(int conformance, PDFAFlavour flavour) throws Exception {
+ byte[] pdf = createPdfA(conformance, (document, writer) -> {
+ PdfContentByte cb = writer.getDirectContent();
+ cb.setColorFill(new SpotColor(new PdfSpotColor("OpenPDF Red", new Color(200, 30, 30)), 0.8f));
+ cb.rectangle(100, 600, 200, 100);
+ cb.fill();
+
+ cb.setGrayFill(0.4f);
+ cb.rectangle(100, 450, 200, 100);
+ cb.fill();
+
+ PdfShading shading = PdfShading.simpleAxial(writer, 100, 300, 300, 300, Color.WHITE,
+ new Color(30, 120, 200));
+ cb.setColorFill(new ShadingColor(new PdfShadingPattern(shading)));
+ cb.rectangle(100, 300, 200, 100);
+ cb.fill();
+ });
+
+ assertCompliant(pdf, flavour);
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "4, PDFA_1_B, /imageTest/ImageTest.gif",
+ "4, PDFA_1_B, /H.gif",
+ "6, PDFA_2_B, /imageTest/ImageTest.gif",
+ "6, PDFA_2_B, /imageTest/ImageTest.png",
+ "6, PDFA_2_B, /gradient.tiff",
+ "6, PDFA_2_B, /H.gif",
+ "9, PDFA_3_B, /imageTest/ImageTest.png",
+ "9, PDFA_3_B, /gradient.tiff"})
+ void imageFormats(int conformance, PDFAFlavour flavour, String image) throws Exception {
+ byte[] pdf = createPdfA(conformance, (document, writer) -> {
+ Image picture = Image.getInstance(readResource(image));
+ picture.scaleToFit(300, 300);
+ document.add(picture);
+ });
+
+ assertCompliant(pdf, flavour);
+ }
+
+ @ParameterizedTest
+ @CsvSource({"4, PDFA_1_B", "6, PDFA_2_B", "9, PDFA_3_B"})
+ void fontsWithDifferentEncodings(int conformance, PDFAFlavour flavour) throws Exception {
+ byte[] pdf = createPdfA(conformance, (document, writer) -> {
+ document.add(new Paragraph("WinAnsi: Grüße, Ærø", new Font(font(BaseFont.WINANSI), 12)));
+ document.add(new Paragraph("Identity-H: Ελληνικά, Русский", new Font(font(BaseFont.IDENTITY_H), 12)));
+ BaseFont symbol = BaseFont.createFont("symbol.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, false,
+ readResource("/fonts/wine-symbol/symbol.ttf"), null);
+ document.add(new Paragraph("abc", new Font(symbol, 12)));
+ BaseFont thai = BaseFont.createFont("Sarabun-Regular.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, false,
+ readResource("/fonts/Sarabun/Sarabun-Regular.ttf"), null);
+ document.add(new Paragraph("ภาษาไทย", new Font(thai, 12)));
+ });
+
+ assertCompliant(pdf, flavour);
+ }
+
+ @ParameterizedTest
+ @CsvSource({"6, PDFA_2_B", "9, PDFA_3_B"})
+ void trueTypeFontWithEncodingThatIsNotWinAnsi(int conformance, PDFAFlavour flavour) throws Exception {
+ byte[] pdf = createPdfA(conformance, (document, writer) -> document.add(
+ new Paragraph("Cp1250: Łódź, Příliš", new Font(font(BaseFont.CP1250), 12))));
+
+ assertCompliant(pdf, flavour);
+ }
+
+ @Test
+ void pdfA1RejectsTrueTypeFontWithEncodingThatIsNotWinAnsi() {
+ assertThatThrownBy(() -> createPdfA(PdfWriter.PDFA1B, (document, writer) -> document.add(
+ new Paragraph("Cp1250: Łódź", new Font(font(BaseFont.CP1250), 12)))))
+ .hasRootCauseInstanceOf(PdfXConformanceException.class)
+ .hasMessageContaining("IDENTITY_H");
+ }
+
+ @ParameterizedTest
+ @CsvSource({"4, PDFA_1_B", "6, PDFA_2_B", "9, PDFA_3_B"})
+ void pagesWithDifferentSizesRotationAndLabels(int conformance, PDFAFlavour flavour) throws Exception {
+ byte[] pdf = createPdfA(conformance, (document, writer) -> {
+ Font font = new Font(font(BaseFont.WINANSI), 12);
+ document.add(new Paragraph("A4 portrait", font));
+ document.setPageSize(PageSize.A4.rotate());
+ document.newPage();
+ document.add(new Paragraph("A4 landscape", font));
+ document.setPageSize(PageSize.LETTER);
+ document.newPage();
+ document.add(new Paragraph("Letter", font));
+
+ PdfPageLabels labels = new PdfPageLabels();
+ labels.addPageLabel(1, PdfPageLabels.LOWERCASE_ROMAN_NUMERALS);
+ labels.addPageLabel(2, PdfPageLabels.DECIMAL_ARABIC_NUMERALS, "Page ", 1);
+ writer.setPageLabels(labels);
+ });
+
+ assertCompliant(pdf, flavour);
+ }
+
+ @Test
+ void pdfA3bWithAttachedXmlFile() throws Exception {
+ byte[] pdf = createPdfA(PdfWriter.PDFA3B, (document, writer) -> {
+ document.add(new Paragraph("A document with an attached file.", new Font(font(BaseFont.WINANSI), 12)));
+ PdfDictionary params = new PdfDictionary();
+ params.put(PdfName.MODDATE, new PdfDate());
+ PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(writer, null, "data.xml",
+ "1".getBytes(StandardCharsets.UTF_8), "application/xml", params,
+ PdfStream.BEST_COMPRESSION);
+ fs.setAFRelationship(PdfName.DATA);
+ writer.addAssociatedFile("The source data", fs);
+ });
+
+ assertCompliant(pdf, PDFAFlavour.PDFA_3_B);
+ }
+
+ @Test
+ void fontThatIsNotEmbeddedIsRejected() {
+ assertThatThrownBy(() -> createPdfA(PdfWriter.PDFA2B, (document, writer) -> document.add(
+ new Paragraph("Helvetica", new Font(BaseFont.createFont(), 12)))))
+ .hasRootCauseInstanceOf(PdfXConformanceException.class)
+ .hasMessageContaining("Helvetica");
+ }
+
+ @Test
+ void javaScriptIsRejected() {
+ assertThatThrownBy(() -> createPdfA(PdfWriter.PDFA2B, (document, writer) -> writer.addJavaScript(
+ PdfAction.javaScript("app.alert('Hello');", writer))))
+ .isInstanceOf(PdfXConformanceException.class)
+ .hasMessageContaining("JavaScript");
+ assertThatThrownBy(() -> createPdfA(PdfWriter.PDFA3B, (document, writer) -> writer.addJavaScript("hello",
+ PdfAction.javaScript("app.alert('Hello');", writer))))
+ .isInstanceOf(PdfXConformanceException.class);
+ }
+
+ private static byte[] createPdfA(int conformance, Content content) throws Exception {
+ return createPdfA(conformance, false, content);
+ }
+
+ private static byte[] createPdfA(int conformance, boolean tagged, Content content) throws Exception {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ Document document = new Document(PageSize.A4);
+ try {
+ PdfWriter writer = PdfWriter.getInstance(document, out);
+ writer.setPDFXConformance(conformance);
+ if (tagged) {
+ writer.setTagged();
+ writer.getExtraCatalog().put(PdfName.LANG, new PdfString("en-US"));
+ }
+ document.addTitle("OpenPDF PDF/A feature test");
+ document.addAuthor("OpenPDF");
+ document.open();
+ writer.setOutputIntents("sRGB IEC61966-2.1", null, "http://www.color.org", "sRGB IEC61966-2.1",
+ ICC_Profile.getInstance(ColorSpace.CS_sRGB));
+ content.write(document, writer);
+ writer.createXmpMetadata();
+ } catch (Exception | Error e) {
+ closeQuietly(document);
+ throw e;
+ }
+ // a conformance exception that is thrown while the last page is written must not be hidden
+ document.close();
+ return out.toByteArray();
+ }
+
+ private static BaseFont font(String encoding) throws IOException {
+ return BaseFont.createFont("LiberationSerif-Regular.ttf", encoding, BaseFont.EMBEDDED, false,
+ readResource(FONT), null);
+ }
+
+ 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 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 {
+ assertThat(validate(pdf, flavour)).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 = VeraPdfFeatureConformanceTest.class.getResourceAsStream(name)) {
+ assertThat(in).as(name).isNotNull();
+ return in.readAllBytes();
+ }
+ }
+}