diff --git a/jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfxMetadataSafetyTest.java b/jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfxMetadataSafetyTest.java
index b25353428..f8dd94083 100644
--- a/jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfxMetadataSafetyTest.java
+++ b/jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfxMetadataSafetyTest.java
@@ -16,6 +16,7 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
@@ -257,4 +258,81 @@ void hugeHostileXmpPacketIsReplacedWithoutParsing() throws Exception {
assertTrue(xmp.contains(PdfXStandard.PDF_X_4.gtsVersion()), "version was not updated");
}
}
+
+ @Test
+ void handlesMalformedInfoTypesPdfx1aVersionAndDuplicateDcTitle() throws Exception {
+ assumeTrue(PdfOutputIntent.isSupported(), "QPDF output-intent support unavailable");
+
+ String xmp = ""
+ + ""
+ + ""
+ + "First"
+ + ""
+ + ""
+ + ""
+ + "Stale Title"
+ + ""
+ + "";
+
+ byte[] malformedInput;
+ try (PDDocument document = new PDDocument()) {
+ document.addPage(new PDPage());
+ document.setVersion(1.7f);
+ document.getDocumentCatalog().getCOSObject().setName(COSName.VERSION, "1.7");
+ var info = document.getDocumentInformation().getCOSObject();
+ info.setInt(COSName.TITLE, 12345);
+ info.setString(COSName.TRAPPED, "False");
+ info.setInt(COSName.MOD_DATE, 999);
+ info.setName(COSName.CREATION_DATE, "NotAString");
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ document.save(out);
+ malformedInput = out.toByteArray();
+ }
+
+ byte[] x1a = PdfOutputIntent.applyPdfxMetadata(malformedInput, CMYK,
+ PdfOutputIntent.Spec.pdfx("FOGRA39", "FOGRA39"),
+ PdfXStandard.PDF_X_1A.gtsVersion(), PdfXStandard.PDF_X_1A.gtsConformance());
+ assertNotNull(x1a);
+ assertTrue(new String(x1a, StandardCharsets.ISO_8859_1).startsWith("%PDF-1.3"),
+ "PDF/X-1a must force PDF 1.3 header");
+ try (PDDocument loaded = Loader.loadPDF(x1a)) {
+ assertNull(loaded.getDocumentCatalog().getVersion(),
+ "PDF/X-1a must strip conflicting Catalog /Version");
+ }
+
+ byte[] x6 = PdfOutputIntent.applyPdfxMetadata(malformedInput, CMYK,
+ PdfOutputIntent.Spec.pdfx("FOGRA39", "FOGRA39"),
+ PdfXStandard.PDF_X_6.gtsVersion(), PdfXStandard.PDF_X_6.gtsConformance());
+ assertNotNull(x6);
+ assertTrue(new String(x6, StandardCharsets.ISO_8859_1).startsWith("%PDF-2.0"),
+ "PDF/X-6 must force PDF 2.0 header");
+
+ byte[] titleInput;
+ try (PDDocument document = new PDDocument()) {
+ document.addPage(new PDPage());
+ document.getDocumentInformation().setTitle("Authoritative Title");
+ PDMetadata metadata = new PDMetadata(document);
+ metadata.importXMPMetadata(xmp.getBytes(StandardCharsets.UTF_8));
+ document.getDocumentCatalog().setMetadata(metadata);
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ document.save(out);
+ titleInput = out.toByteArray();
+ }
+ byte[] cleaned = PdfOutputIntent.applyPdfxMetadata(titleInput, CMYK,
+ PdfOutputIntent.Spec.pdfx("FOGRA39", "FOGRA39"),
+ PdfXStandard.PDF_X_4.gtsVersion(), PdfXStandard.PDF_X_4.gtsConformance());
+ try (PDDocument loaded = Loader.loadPDF(cleaned)) {
+ String outXmp = new String(
+ loaded.getDocumentCatalog().getMetadata().exportXMPMetadata().readAllBytes(),
+ StandardCharsets.UTF_8);
+ assertTrue(outXmp.contains("Authoritative Title"));
+ assertTrue(!outXmp.contains("Stale Title"),
+ "secondary rdf:Description must not keep stale dc:title");
+ }
+ }
}
diff --git a/jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java b/jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java
index 367ffbff1..e2f79d268 100644
--- a/jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java
+++ b/jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java
@@ -19,6 +19,7 @@
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
+import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.encoding.WinAnsiEncoding;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.text.PDFTextStripper;
@@ -41,6 +42,7 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.util.Arrays;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
@@ -1606,4 +1608,543 @@ void resubsettingOpenTypeCffUpdatesCharSetToRetainedGlyphs() throws Exception {
private static ByteBuffer tableBuffer(byte[] font) {
return ByteBuffer.wrap(font).order(ByteOrder.BIG_ENDIAN);
}
+
+ @Test
+ void subsetPreservesFormat12NonBmpCmapAlongsideFormat4() throws IOException {
+ assumeTrue(NativeRuntime.isFull(), "needs real native library");
+ byte[] baseTtf = liberationSansBytes();
+ byte[] patched = injectFormat12Subtable(baseTtf, 0x1F600, 43);
+
+ byte[] subset = FontNormalizer.subset(patched, new int[] {'H', 0x1F600}, false);
+ assertTrue(subset != null && subset.length > 0, "non-BMP subset returned empty");
+
+ int[] cmapLoc = findSfntTable(subset, "cmap");
+ assertNotNull(cmapLoc, "subset missing cmap table");
+ ByteBuffer buf = tableBuffer(subset);
+ int cmapBase = cmapLoc[0];
+ int numSubtables = buf.getShort(cmapBase + 2) & 0xFFFF;
+ boolean foundFmt4 = false;
+ boolean foundFmt12WithNonBmp = false;
+ for (int i = 0; i < numSubtables; i++) {
+ int rec = cmapBase + 4 + i * 8;
+ int pid = buf.getShort(rec) & 0xFFFF;
+ int eid = buf.getShort(rec + 2) & 0xFFFF;
+ int subOff = cmapBase + buf.getInt(rec + 4);
+ int fmt = buf.getShort(subOff) & 0xFFFF;
+ if (pid == 3 && eid == 1 && fmt == 4) {
+ foundFmt4 = true;
+ } else if (pid == 3 && eid == 10 && fmt == 12) {
+ int numGroups = buf.getInt(subOff + 12);
+ for (int g = 0; g < numGroups; g++) {
+ int grp = subOff + 16 + g * 12;
+ int start = buf.getInt(grp);
+ int end = buf.getInt(grp + 4);
+ if (0x1F600 >= start && 0x1F600 <= end) {
+ foundFmt12WithNonBmp = true;
+ }
+ }
+ }
+ }
+ assertTrue(foundFmt4, "subset must preserve (3,1) Format 4 BMP cmap");
+ assertTrue(foundFmt12WithNonBmp,
+ "subset must preserve (3,10) Format 12 cmap mapping U+1F600");
+ }
+
+ @Test
+ void subsetRepairsScanSoftPostVersionAndOutOfRangeIndexToLocFormat() throws IOException {
+ assumeTrue(NativeRuntime.isFull(), "needs real native library");
+ byte[] corrupted = liberationSansBytes().clone();
+ int[] postLoc = findSfntTable(corrupted, "post");
+ int[] headLoc = findSfntTable(corrupted, "head");
+ assertNotNull(postLoc);
+ assertNotNull(headLoc);
+
+ ByteBuffer w = ByteBuffer.wrap(corrupted).order(ByteOrder.BIG_ENDIAN);
+ w.putInt(postLoc[0], 0x00000003);
+ w.putShort(headLoc[0] + 50, (short) 5);
+
+ byte[] subset = FontNormalizer.subset(corrupted, new int[] {'H', 'e', 'l', 'o'}, false);
+ assertTrue(subset != null && subset.length > 0, "subset failed on ScanSoft post/head");
+ assertTrue(FontNormalizer.classify(subset).hasCmap());
+
+ int[] subPost = findSfntTable(subset, "post");
+ int[] subHead = findSfntTable(subset, "head");
+ assertNotNull(subHead);
+ ByteBuffer r = tableBuffer(subset);
+ if (subPost != null) {
+ int postVer = r.getInt(subPost[0]);
+ assertFalse(postVer == 0x00000003,
+ "ScanSoft post version 0x00000003 must be normalized");
+ }
+ short locaFmt = r.getShort(subHead[0] + 50);
+ assertTrue(locaFmt == 0 || locaFmt == 1,
+ "out-of-range indexToLocFormat must be repaired, got " + locaFmt);
+ }
+
+ @Test
+ void repairWidthsSynthesizesIdentityVDw2AndW2() throws Exception {
+ assumeTrue(NativeRuntime.isFull(), "needs real native library");
+ byte[] pdf = cidVerticalTrueTypePdf(null, null);
+
+ try (PdfDocument doc = PdfDocument.open(pdf)) {
+ assertEquals(1, FontNormalizer.repairWidths(doc, 0),
+ "vertical CID font without /DW2 must be repaired");
+ byte[] repaired = doc.saveBytes();
+ try (PDDocument loaded = Loader.loadPDF(repaired)) {
+ COSDictionary descendant = cidDescendant(loaded);
+ assertNotNull(descendant);
+ COSBase dw2Obj = descendant.getDictionaryObject(COSName.getPDFName("DW2"));
+ assertTrue(dw2Obj instanceof COSArray dw2 && dw2.size() == 2,
+ "expected synthesized /DW2 [v, w1y], got " + dw2Obj);
+ }
+ }
+
+ // With explicit non-default /DW2 [880 -500] and no /W2, /W2 entries must be emitted.
+ byte[] pdfCustomDw2 = cidVerticalTrueTypePdf(new int[] {880, -500}, null);
+ try (PdfDocument doc = PdfDocument.open(pdfCustomDw2)) {
+ assertEquals(1, FontNormalizer.repairWidths(doc, 0));
+ byte[] repaired = doc.saveBytes();
+ try (PDDocument loaded = Loader.loadPDF(repaired)) {
+ COSDictionary descendant = cidDescendant(loaded);
+ assertNotNull(descendant);
+ assertNotNull(descendant.getDictionaryObject(COSName.getPDFName("W2")),
+ "expected /W2 entries when vertical metric differs from custom /DW2");
+ }
+ }
+ }
+
+ @Test
+ void fixToUnicodeEmitsBeginBfRangeAndReplacesInvalidBegincidrange() throws Exception {
+ assumeTrue(NativeRuntime.isFull(), "needs real native library");
+ byte[] ttf = liberationSansBytes();
+ byte[] pdf;
+ try (PDDocument doc = new PDDocument()) {
+ PDPage page = new PDPage(PDRectangle.LETTER);
+ doc.addPage(page);
+ PDType0Font cidFont = PDType0Font.load(doc, new ByteArrayInputStream(ttf), false);
+ try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
+ cs.beginText();
+ cs.setFont(cidFont, 12);
+ cs.newLineAtOffset(72, 700);
+ cs.showText("ABCD");
+ cs.endText();
+ }
+ ByteArrayOutputStream first = new ByteArrayOutputStream();
+ doc.save(first);
+ pdf = first.toByteArray();
+ }
+ try (PDDocument doc = Loader.loadPDF(pdf)) {
+ COSDictionary font = firstFontDictionary(doc);
+ assertNotNull(font);
+ String badCmap = "/CIDInit /ProcSet findresource begin\n"
+ + "12 dict begin begincmap\n"
+ + "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n"
+ + "/CMapName /Adobe-Identity-UCS def\n"
+ + "/CMapType 2 def\n"
+ + "1 begincodespacerange <0000> endcodespacerange\n"
+ + "1 begincidrange\n<0024> <0027> 65\nendcidrange\n"
+ + "endcmap CMapName currentdict /CMap defineresource pop end end\n";
+ font.setItem(COSName.TO_UNICODE, new PDStream(doc,
+ new ByteArrayInputStream(badCmap.getBytes(StandardCharsets.US_ASCII)))
+ .getCOSObject());
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ doc.save(out);
+ pdf = out.toByteArray();
+ }
+
+ try (PdfDocument doc = PdfDocument.open(pdf)) {
+ assertEquals(1, FontNormalizer.fixToUnicode(doc, 0));
+ byte[] repaired = doc.saveBytes();
+ try (PDDocument loaded = Loader.loadPDF(repaired)) {
+ COSDictionary font = firstFontDictionary(loaded);
+ assertNotNull(font);
+ byte[] cmapBytes = streamBytes(font, COSName.TO_UNICODE);
+ String cmapText = new String(cmapBytes, StandardCharsets.US_ASCII);
+ assertTrue(cmapText.contains("beginbfrange"),
+ "contiguous mapping must emit beginbfrange:\n" + cmapText);
+ assertFalse(cmapText.contains("begincidrange"),
+ "synthesized ToUnicode must not emit begincidrange:\n" + cmapText);
+ assertEquals("ABCD", new PDFTextStripper().getText(loaded).trim());
+ }
+ }
+ }
+
+ private static int[] findSfntTable(byte[] sfnt, String tag) {
+ if (sfnt.length < 12) {
+ return null;
+ }
+ ByteBuffer buf = tableBuffer(sfnt);
+ int numTables = buf.getShort(4) & 0xFFFF;
+ for (int i = 0; i < numTables; i++) {
+ int off = 12 + i * 16;
+ if (off + 16 > sfnt.length) {
+ break;
+ }
+ String entryTag = new String(sfnt, off, 4, StandardCharsets.US_ASCII);
+ if (tag.equals(entryTag)) {
+ int tblOff = buf.getInt(off + 8);
+ int tblLen = buf.getInt(off + 12);
+ return new int[] {tblOff, tblLen, off};
+ }
+ }
+ return null;
+ }
+
+ private static byte[] injectFormat12Subtable(byte[] sfnt, int cp, int gid) {
+ int[] cmapLoc = findSfntTable(sfnt, "cmap");
+ assertNotNull(cmapLoc);
+ ByteBuffer src = tableBuffer(sfnt);
+ int cmapOff = cmapLoc[0];
+ int numSub = src.getShort(cmapOff + 2) & 0xFFFF;
+ byte[] fmt4Bytes = null;
+ for (int i = 0; i < numSub; i++) {
+ int rec = cmapOff + 4 + i * 8;
+ int pid = src.getShort(rec) & 0xFFFF;
+ int eid = src.getShort(rec + 2) & 0xFFFF;
+ int subOff = cmapOff + src.getInt(rec + 4);
+ if (pid == 3 && eid == 1 && (src.getShort(subOff) & 0xFFFF) == 4) {
+ int len = src.getShort(subOff + 2) & 0xFFFF;
+ fmt4Bytes = Arrays.copyOfRange(sfnt, subOff, subOff + len);
+ break;
+ }
+ }
+ assertNotNull(fmt4Bytes, "expected (3,1) Format 4 subtable in base font");
+
+ int headerSize = 4 + 2 * 8;
+ int fmt4Off = headerSize;
+ int fmt12Off = (fmt4Off + fmt4Bytes.length + 3) & ~3;
+ int fmt12Len = 16 + 2 * 12;
+ int newCmapLen = fmt12Off + fmt12Len;
+ byte[] newCmap = new byte[newCmapLen];
+ ByteBuffer cb = ByteBuffer.wrap(newCmap).order(ByteOrder.BIG_ENDIAN);
+ cb.putShort((short) 0);
+ cb.putShort((short) 2);
+ // Record 0: (3, 1) Format 4
+ cb.putShort((short) 3);
+ cb.putShort((short) 1);
+ cb.putInt(fmt4Off);
+ // Record 1: (3, 10) Format 12
+ cb.putShort((short) 3);
+ cb.putShort((short) 10);
+ cb.putInt(fmt12Off);
+ System.arraycopy(fmt4Bytes, 0, newCmap, fmt4Off, fmt4Bytes.length);
+ // Format 12 header + 2 groups sorted ascending: BMP 'H' and non-BMP cp
+ cb.position(fmt12Off);
+ cb.putShort((short) 12);
+ cb.putShort((short) 0);
+ cb.putInt(fmt12Len);
+ cb.putInt(0);
+ cb.putInt(2);
+ cb.putInt('H');
+ cb.putInt('H');
+ cb.putInt(gid);
+ cb.putInt(cp);
+ cb.putInt(cp);
+ cb.putInt(gid);
+
+ int alignedEnd = (sfnt.length + 3) & ~3;
+ byte[] out = new byte[alignedEnd + newCmapLen];
+ System.arraycopy(sfnt, 0, out, 0, sfnt.length);
+ System.arraycopy(newCmap, 0, out, alignedEnd, newCmapLen);
+ ByteBuffer ob = ByteBuffer.wrap(out).order(ByteOrder.BIG_ENDIAN);
+ ob.putInt(cmapLoc[2] + 8, alignedEnd);
+ ob.putInt(cmapLoc[2] + 12, newCmapLen);
+ return out;
+ }
+
+ private static byte[] injectVerticalTables(byte[] sfnt, int advanceHeight, int topSideBearing) {
+ ByteBuffer in = tableBuffer(sfnt);
+ int numTables = in.getShort(4) & 0xFFFF;
+ int[] maxpLoc = findSfntTable(sfnt, "maxp");
+ assertNotNull(maxpLoc, "expected maxp table");
+ int numGlyphs = in.getShort(maxpLoc[0] + 4) & 0xFFFF;
+
+ byte[] vhea = new byte[36];
+ ByteBuffer vb = ByteBuffer.wrap(vhea).order(ByteOrder.BIG_ENDIAN);
+ vb.putInt(0x00010000);
+ vb.putShort((short) 1024);
+ vb.putShort((short) -1024);
+ vb.putShort((short) 0);
+ vb.putShort((short) advanceHeight);
+ vb.putShort((short) topSideBearing);
+ vb.putShort((short) 0);
+ vb.putShort((short) 1500);
+ vb.putShort((short) 0);
+ vb.putShort((short) 1);
+ vb.position(34);
+ vb.putShort((short) numGlyphs);
+
+ byte[] vmtx = new byte[numGlyphs * 4];
+ ByteBuffer mb = ByteBuffer.wrap(vmtx).order(ByteOrder.BIG_ENDIAN);
+ for (int g = 0; g < numGlyphs; g++) {
+ mb.putShort((short) advanceHeight);
+ mb.putShort((short) topSideBearing);
+ }
+
+ java.util.TreeMap tables = new java.util.TreeMap<>();
+ for (int i = 0; i < numTables; i++) {
+ int recOff = 12 + i * 16;
+ String tag = new String(sfnt, recOff, 4, StandardCharsets.US_ASCII);
+ int off = in.getInt(recOff + 8);
+ int len = in.getInt(recOff + 12);
+ tables.put(tag, Arrays.copyOfRange(sfnt, off, off + len));
+ }
+ tables.put("vhea", vhea);
+ tables.put("vmtx", vmtx);
+
+ int count = tables.size();
+ int dataOffset = 12 + count * 16;
+ int totalSize = dataOffset;
+ for (byte[] t : tables.values()) {
+ totalSize += (t.length + 3) & ~3;
+ }
+ byte[] out = new byte[totalSize];
+ ByteBuffer ob = ByteBuffer.wrap(out).order(ByteOrder.BIG_ENDIAN);
+ ob.putInt(in.getInt(0));
+ ob.putShort((short) count);
+ int sr = Integer.highestOneBit(count);
+ int es = Integer.numberOfTrailingZeros(sr);
+ ob.putShort((short) (sr * 16));
+ ob.putShort((short) es);
+ ob.putShort((short) ((count - sr) * 16));
+
+ int idx = 0;
+ int cursor = dataOffset;
+ for (var entry : tables.entrySet()) {
+ byte[] data = entry.getValue();
+ int recOff = 12 + idx * 16;
+ byte[] tagBytes = entry.getKey().getBytes(StandardCharsets.US_ASCII);
+ System.arraycopy(tagBytes, 0, out, recOff, 4);
+ ob.putInt(recOff + 4, 0);
+ ob.putInt(recOff + 8, cursor);
+ ob.putInt(recOff + 12, data.length);
+ System.arraycopy(data, 0, out, cursor, data.length);
+ cursor += (data.length + 3) & ~3;
+ idx++;
+ }
+ return out;
+ }
+
+ private static byte[] cidVerticalTrueTypePdf(int[] dw2Values, COSArray w2Array)
+ throws IOException {
+ byte[] program = injectVerticalTables(liberationSansBytes(), 1800, 100);
+ try (PDDocument doc = new PDDocument()) {
+ PDPage page = new PDPage(PDRectangle.LETTER);
+ doc.addPage(page);
+
+ COSDictionary descriptor = new COSDictionary();
+ descriptor.setItem(COSName.TYPE, COSName.FONT_DESC);
+ descriptor.setName(COSName.FONT_NAME, "LiberationSans");
+ descriptor.setInt(COSName.FLAGS, 32);
+ descriptor.setItem(COSName.FONT_BBOX, new COSArray());
+ descriptor.setInt(COSName.ITALIC_ANGLE, 0);
+ descriptor.setInt(COSName.ASCENT, 900);
+ descriptor.setInt(COSName.DESCENT, -200);
+ descriptor.setInt(COSName.CAP_HEIGHT, 700);
+ descriptor.setInt(COSName.STEM_V, 80);
+ COSStream fontFile = new PDStream(doc, new ByteArrayInputStream(program))
+ .getCOSObject();
+ fontFile.setInt(COSName.LENGTH1, program.length);
+ descriptor.setItem(COSName.FONT_FILE2, fontFile);
+
+ COSDictionary cidSystemInfo = new COSDictionary();
+ cidSystemInfo.setString(COSName.REGISTRY, "Adobe");
+ cidSystemInfo.setString(COSName.ORDERING, "Identity");
+ cidSystemInfo.setInt(COSName.SUPPLEMENT, 0);
+ COSDictionary descendant = new COSDictionary();
+ descendant.setItem(COSName.TYPE, COSName.FONT);
+ descendant.setItem(COSName.SUBTYPE, COSName.CID_FONT_TYPE2);
+ descendant.setName(COSName.BASE_FONT, "LiberationSans");
+ descendant.setItem(COSName.CIDSYSTEMINFO, cidSystemInfo);
+ descendant.setInt(COSName.DW, 1000);
+ if (dw2Values != null) {
+ COSArray dw2 = new COSArray();
+ dw2.add(COSInteger.get(dw2Values[0]));
+ dw2.add(COSInteger.get(dw2Values[1]));
+ descendant.setItem(COSName.getPDFName("DW2"), dw2);
+ }
+ if (w2Array != null) {
+ descendant.setItem(COSName.getPDFName("W2"), w2Array);
+ }
+ descendant.setItem(COSName.FONT_DESC, descriptor);
+
+ COSArray descendants = new COSArray();
+ descendants.add(descendant);
+ COSDictionary font = new COSDictionary();
+ font.setItem(COSName.TYPE, COSName.FONT);
+ font.setItem(COSName.SUBTYPE, COSName.TYPE0);
+ font.setName(COSName.BASE_FONT, "LiberationSans");
+ font.setItem(COSName.ENCODING, COSName.IDENTITY_V);
+ font.setItem(COSName.DESCENDANT_FONTS, descendants);
+
+ COSDictionary fonts = new COSDictionary();
+ fonts.setItem(COSName.getPDFName("F1"), font);
+ COSDictionary resources = new COSDictionary();
+ resources.setItem(COSName.FONT, fonts);
+ page.setResources(new PDResources(resources));
+ page.setContents(new PDStream(doc, new ByteArrayInputStream(
+ "BT /F1 12 Tf 72 700 Td <0024> Tj ET"
+ .getBytes(StandardCharsets.US_ASCII))));
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ doc.save(out);
+ return out.toByteArray();
+ }
+ }
+
+ @Test
+ void normalizingNonSymbolicTrueTypeNameStandardEncodingConvertsToWinAnsi() throws Exception {
+ assumeTrue(NativeRuntime.isFull(), "needs real native library");
+ byte[] pdf;
+ try (PDDocument doc = Loader.loadPDF(embeddedTrueTypePdf(true, false))) {
+ COSDictionary font = firstFontDictionary(doc);
+ assertNotNull(font);
+ font.setItem(COSName.ENCODING, COSName.STANDARD_ENCODING);
+
+ PDPage page = doc.getPage(0);
+ COSName fontKey = page.getResources().getFontNames().iterator().next();
+ String stream = "BT /" + fontKey.getName() + " 12 Tf 72 700 Td (a'b) Tj ET";
+ page.setContents(new PDStream(doc, new ByteArrayInputStream(
+ stream.getBytes(StandardCharsets.US_ASCII))));
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ doc.save(out);
+ pdf = out.toByteArray();
+ }
+
+ try (PdfDocument doc = PdfDocument.open(pdf)) {
+ FontNormalizer.Result res = FontNormalizer.normalizePage(doc, 0);
+ assertTrue(res.fontsProcessed() >= 1);
+ byte[] normalized = doc.saveBytes();
+ try (PDDocument loaded = Loader.loadPDF(normalized)) {
+ COSDictionary font = firstFontDictionary(loaded);
+ COSDictionary enc = font.getCOSDictionary(COSName.ENCODING);
+ assertNotNull(enc, "direct /StandardEncoding must become WinAnsi + /Differences");
+ assertEquals(COSName.WIN_ANSI_ENCODING,
+ enc.getDictionaryObject(COSName.BASE_ENCODING));
+ COSArray diffs = enc.getCOSArray(COSName.DIFFERENCES);
+ assertNotNull(diffs);
+ String extracted = new PDFTextStripper().getText(loaded).trim();
+ assertEquals("a\u2019b", extracted);
+ }
+ // Second pass on clean encoding dictionary must be idempotent.
+ FontNormalizer.Result second = FontNormalizer.normalizePage(doc, 0);
+ assertEquals(0, second.toUnicodeFixed());
+ assertEquals(0, second.widthsRepaired());
+ }
+ }
+
+ @Test
+ void normalizingSymbolicTrueTypeWithoutMsOrMacRomanKeepsSymbolicFlag() throws Exception {
+ assumeTrue(NativeRuntime.isFull(), "needs real native library");
+ byte[] appleUnicodeOnlySfnt = keepOnlyAppleUnicodeCmap(liberationSansBytes());
+ byte[] pdf;
+ try (PDDocument doc = new PDDocument()) {
+ PDPage page = new PDPage();
+ doc.addPage(page);
+
+ COSDictionary descriptor = new COSDictionary();
+ descriptor.setItem(COSName.TYPE, COSName.FONT_DESC);
+ descriptor.setName(COSName.FONT_NAME, "LiberationSans");
+ descriptor.setInt(COSName.FLAGS, 4);
+ descriptor.setItem(COSName.FONT_BBOX, new COSArray());
+ COSStream fontFile = new PDStream(doc, new ByteArrayInputStream(appleUnicodeOnlySfnt))
+ .getCOSObject();
+ fontFile.setInt(COSName.LENGTH1, appleUnicodeOnlySfnt.length);
+ descriptor.setItem(COSName.FONT_FILE2, fontFile);
+
+ COSDictionary font = new COSDictionary();
+ font.setItem(COSName.TYPE, COSName.FONT);
+ font.setItem(COSName.SUBTYPE, COSName.TRUE_TYPE);
+ font.setName(COSName.BASE_FONT, "LiberationSans");
+ font.setInt(COSName.FIRST_CHAR, 65);
+ font.setInt(COSName.LAST_CHAR, 65);
+ COSArray widths = new COSArray();
+ widths.add(COSInteger.get(667));
+ font.setItem(COSName.WIDTHS, widths);
+ font.setItem(COSName.ENCODING, COSName.WIN_ANSI_ENCODING);
+ font.setItem(COSName.FONT_DESC, descriptor);
+
+ COSDictionary fonts = new COSDictionary();
+ fonts.setItem(COSName.getPDFName("F1"), font);
+ COSDictionary res = new COSDictionary();
+ res.setItem(COSName.FONT, fonts);
+ page.setResources(new PDResources(res));
+ page.setContents(new PDStream(doc, new ByteArrayInputStream(
+ "BT /F1 12 Tf 72 700 Td (A) Tj ET".getBytes(StandardCharsets.US_ASCII))));
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ doc.save(out);
+ pdf = out.toByteArray();
+ }
+
+ try (PdfDocument doc = PdfDocument.open(pdf)) {
+ FontNormalizer.normalizePage(doc, 0);
+ try (PDDocument loaded = Loader.loadPDF(doc.saveBytes())) {
+ COSDictionary font = firstFontDictionary(loaded);
+ COSDictionary desc = font.getCOSDictionary(COSName.FONT_DESC);
+ assertNotNull(desc);
+ int flags = desc.getInt(COSName.FLAGS);
+ assertTrue((flags & 4) != 0,
+ "font lacking (3,1)/(1,0) cmap must remain Symbolic, flags=" + flags);
+ assertNull(font.getDictionaryObject(COSName.ENCODING),
+ "symbolic TrueType font must not keep /Encoding");
+ }
+ }
+ }
+
+ @Test
+ void normalizingNegativeCidWidthRangeDoesNotWrapAround() throws Exception {
+ assumeTrue(NativeRuntime.isFull(), "needs real native library");
+ byte[] pdf;
+ try (PDDocument doc = Loader.loadPDF(cidTrueTypePdf("LiberationSans", null))) {
+ COSDictionary font = firstFontDictionary(doc);
+ assertNotNull(font);
+ COSDictionary descendant = (COSDictionary) font.getCOSArray(COSName.DESCENDANT_FONTS)
+ .getObject(0);
+ COSArray badW = new COSArray();
+ badW.add(COSInteger.get(-1));
+ COSArray run = new COSArray();
+ run.add(COSInteger.get(500));
+ run.add(COSInteger.get(600));
+ badW.add(run);
+ descendant.setItem(COSName.W, badW);
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ doc.save(out);
+ pdf = out.toByteArray();
+ }
+
+ try (PdfDocument doc = PdfDocument.open(pdf)) {
+ FontNormalizer.normalizePage(doc, 0);
+ byte[] normalized = doc.saveBytes();
+ assertNotNull(normalized);
+ assertTrue(normalized.length > 0);
+ }
+ }
+
+ private static byte[] keepOnlyAppleUnicodeCmap(byte[] sfnt) {
+ int[] cmapLoc = findSfntTable(sfnt, "cmap");
+ assertNotNull(cmapLoc, "font missing cmap table");
+ int cmapOff = cmapLoc[0];
+ int cmapLen = cmapLoc[1];
+ byte[] out = sfnt.clone();
+ ByteBuffer cb = ByteBuffer.wrap(out, cmapOff, cmapLen).slice().order(ByteOrder.BIG_ENDIAN);
+ int numSub = cb.getShort(2) & 0xFFFF;
+ int pickedRelOff = -1;
+ for (int i = 0; i < numSub; i++) {
+ int rec = 4 + i * 8;
+ int plat = cb.getShort(rec) & 0xFFFF;
+ int enc = cb.getShort(rec + 2) & 0xFFFF;
+ if ((plat == 3 && enc == 1) || (plat == 0 && enc == 3)) {
+ pickedRelOff = cb.getInt(rec + 4);
+ break;
+ }
+ }
+ assertTrue(pickedRelOff > 0, "expected Unicode cmap subtable");
+ cb.putShort(2, (short) 1);
+ cb.putShort(4, (short) 0);
+ cb.putShort(6, (short) 3);
+ cb.putInt(8, pickedRelOff);
+ return out;
+ }
}
diff --git a/native/bridge/tests/smoke.cpp b/native/bridge/tests/smoke.cpp
index ee451cc4d..872287dba 100644
--- a/native/bridge/tests/smoke.cpp
+++ b/native/bridge/tests/smoke.cpp
@@ -1,5 +1,6 @@
// native_smoke - CTest smoke test for the bridge ABI.
+#include
#include
#include
#include
@@ -554,6 +555,416 @@ void runRepairEdgeChecks() {
}
}
+void appendU16BE(std::vector& out, uint16_t v) {
+ out.push_back(static_cast((v >> 8) & 0xFF));
+ out.push_back(static_cast(v & 0xFF));
+}
+
+void appendU32BE(std::vector& out, uint32_t v) {
+ out.push_back(static_cast((v >> 24) & 0xFF));
+ out.push_back(static_cast((v >> 16) & 0xFF));
+ out.push_back(static_cast((v >> 8) & 0xFF));
+ out.push_back(static_cast(v & 0xFF));
+}
+
+// Build a minimal valid TrueType binary with 1 + glyphCount glyphs (GID 0 = .notdef,
+// GID 1..glyphCount mapped non-contiguously at Unicode U+0402, U+0404, ... so ToUnicode
+// repair cannot fold them into beginbfrange and must split >100 beginbfchar entries).
+std::vector buildMinimalSparseTtf(uint16_t glyphCount) {
+ const uint16_t numGlyphs = static_cast(glyphCount + 1);
+
+ // Build format 4 cmap subtable (one singleton segment per glyph + 0xFFFF sentinel).
+ const uint16_t segCount = static_cast(glyphCount + 1);
+ const uint16_t segCountX2 = static_cast(segCount * 2);
+ uint16_t searchRange = 2;
+ uint16_t entrySelector = 0;
+ while (searchRange * 2 <= segCountX2) {
+ searchRange *= 2;
+ ++entrySelector;
+ }
+ const uint16_t rangeShift = static_cast(segCountX2 - searchRange);
+ const uint16_t subLen = static_cast(16 + segCount * 8);
+
+ std::vector cmap;
+ appendU16BE(cmap, 0);
+ appendU16BE(cmap, 1);
+ appendU16BE(cmap, 3);
+ appendU16BE(cmap, 1);
+ appendU32BE(cmap, 12);
+ appendU16BE(cmap, 4);
+ appendU16BE(cmap, subLen);
+ appendU16BE(cmap, 0);
+ appendU16BE(cmap, segCountX2);
+ appendU16BE(cmap, searchRange);
+ appendU16BE(cmap, entrySelector);
+ appendU16BE(cmap, rangeShift);
+ for (uint16_t g = 1; g <= glyphCount; ++g)
+ appendU16BE(cmap, static_cast(0x0400 + g * 2));
+ appendU16BE(cmap, 0xFFFF);
+ appendU16BE(cmap, 0);
+ for (uint16_t g = 1; g <= glyphCount; ++g)
+ appendU16BE(cmap, static_cast(0x0400 + g * 2));
+ appendU16BE(cmap, 0xFFFF);
+ for (uint16_t g = 1; g <= glyphCount; ++g) {
+ const uint16_t code = static_cast(0x0400 + g * 2);
+ appendU16BE(cmap, static_cast((static_cast(g) - code) & 0xFFFF));
+ }
+ appendU16BE(cmap, 1);
+ for (uint16_t i = 0; i < segCount; ++i) appendU16BE(cmap, 0);
+
+ std::vector head(54, 0);
+ head[2] = 1;
+ head[12] = 0x5F;
+ head[13] = 0x0F;
+ head[14] = 0x3C;
+ head[15] = 0xF5;
+ head[18] = 0x03;
+ head[19] = 0xE8; // unitsPerEm = 1000
+
+ std::vector hhea(36, 0);
+ hhea[2] = 1;
+ hhea[4] = 0x03;
+ hhea[5] = 0x20;
+ hhea[34] = static_cast(numGlyphs >> 8);
+ hhea[35] = static_cast(numGlyphs & 0xFF);
+
+ std::vector hmtx;
+ for (uint16_t i = 0; i < numGlyphs; ++i) {
+ appendU16BE(hmtx, 500);
+ appendU16BE(hmtx, 0);
+ }
+
+ std::vector maxp(32, 0);
+ maxp[1] = 1;
+ maxp[4] = static_cast(numGlyphs >> 8);
+ maxp[5] = static_cast(numGlyphs & 0xFF);
+
+ std::vector loca((static_cast(numGlyphs) + 1) * 2, 0);
+ std::vector glyf(4, 0);
+ std::vector post(32, 0);
+ post[1] = 3; // format 3.0 (no PostScript names)
+
+ struct TableEntry {
+ const char* tag = nullptr;
+ std::vector data;
+ };
+ std::vector tables = {
+ {"cmap", std::move(cmap)}, {"glyf", std::move(glyf)}, {"head", std::move(head)},
+ {"hhea", std::move(hhea)}, {"hmtx", std::move(hmtx)}, {"loca", std::move(loca)},
+ {"maxp", std::move(maxp)}, {"post", std::move(post)},
+ };
+ std::sort(tables.begin(), tables.end(),
+ [](auto const& a, auto const& b) { return std::strcmp(a.tag, b.tag) < 0; });
+
+ const uint16_t numTables = static_cast(tables.size());
+ std::vector sfnt;
+ appendU32BE(sfnt, 0x00010000);
+ appendU16BE(sfnt, numTables);
+ appendU16BE(sfnt, 128);
+ appendU16BE(sfnt, 3);
+ appendU16BE(sfnt, static_cast(numTables * 16 - 128));
+
+ size_t offset = 12 + numTables * 16;
+ for (auto const& t : tables) {
+ for (int i = 0; i < 4; ++i) sfnt.push_back(static_cast(t.tag[i]));
+ appendU32BE(sfnt, 0);
+ appendU32BE(sfnt, static_cast(offset));
+ appendU32BE(sfnt, static_cast(t.data.size()));
+ offset += (t.data.size() + 3) & ~size_t(3);
+ }
+ for (auto const& t : tables) {
+ sfnt.insert(sfnt.end(), t.data.begin(), t.data.end());
+ while (sfnt.size() & 3) sfnt.push_back(0);
+ }
+ return sfnt;
+}
+
+std::vector assemblePdf(const char* header, std::vector const& objs,
+ int rootObj, int infoObj = 0) {
+ std::string out = header;
+ out += '\n';
+ std::vector offsets(objs.size() + 1, 0);
+ for (size_t i = 0; i < objs.size(); ++i) {
+ offsets[i + 1] = out.size();
+ out += std::to_string(i + 1) + " 0 obj\n" + objs[i] + "\nendobj\n";
+ }
+ size_t xrefOff = out.size();
+ char buf[128];
+ std::snprintf(buf, sizeof(buf), "xref\n0 %zu\n0000000000 65535 f \n", objs.size() + 1);
+ out += buf;
+ for (size_t i = 1; i <= objs.size(); ++i) {
+ std::snprintf(buf, sizeof(buf), "%010zu 00000 n \n", offsets[i]);
+ out += buf;
+ }
+ out += "trailer\n<< /Size " + std::to_string(objs.size() + 1) + " /Root " +
+ std::to_string(rootObj) + " 0 R";
+ if (infoObj > 0) out += " /Info " + std::to_string(infoObj) + " 0 R";
+ std::snprintf(buf, sizeof(buf), " >>\nstartxref\n%zu\n%%%%EOF\n", xrefOff);
+ out += buf;
+ return std::vector(out.begin(), out.end());
+}
+
+void checkSignatureNullSafety() {
+ int32_t cnt = 77;
+ CHECK(jpdfium_signature_count(0, &cnt) != JPDFIUM_OK && cnt == 0,
+ "signature_count(0) zeros out-param");
+ char* sjson = const_cast("sentinel");
+ CHECK(jpdfium_signature_info(0, 0, &sjson) != JPDFIUM_OK && sjson == nullptr,
+ "signature_info(0) nulls out-param");
+ uint8_t sentinelByte = 1;
+ uint8_t* dig = &sentinelByte;
+ int64_t dlen = 42;
+ CHECK(
+ jpdfium_signature_digest(0, 0, 1, &dig, &dlen) != JPDFIUM_OK && dig == nullptr && dlen == 0,
+ "signature_digest(0) clears out-params");
+
+ int64_t doc = 0;
+ CHECK(
+ jpdfium_doc_open_bytes(reinterpret_cast(kMinimalPdf),
+ static_cast(std::strlen(kMinimalPdf)), &doc) == JPDFIUM_OK,
+ "open minimal doc for signature checks");
+ if (doc != 0) {
+ CHECK(jpdfium_signature_count(doc, nullptr) == JPDFIUM_ERR_INVALID,
+ "signature_count rejects null out-param");
+ CHECK(jpdfium_signature_info(doc, 0, nullptr) == JPDFIUM_ERR_INVALID,
+ "signature_info rejects null out-param");
+ jpdfium_doc_close(doc);
+ }
+}
+
+void checkPatternJsonEscaping() {
+ int64_t pat = 0;
+ int32_t prc = jpdfium_pcre2_compile("(?s)longprefix_.*_end", 0, &pat);
+ if (prc != JPDFIUM_ERR_NOT_FOUND) {
+ CHECK(prc == JPDFIUM_OK && pat != 0, "pcre2 compile long pattern");
+ if (prc == JPDFIUM_OK && pat != 0) {
+ std::string text = "head longprefix_\t\n\"\x01\\";
+ text.append(300, 'x');
+ text += "_end tail";
+ char* json = nullptr;
+ CHECK(jpdfium_pcre2_match_all(pat, text.c_str(), &json) == JPDFIUM_OK && json,
+ "pcre2 match long control payload");
+ if (json) {
+ std::string s(json);
+ CHECK(s.find("\\t\\n\\\"\\u0001\\\\") != std::string::npos,
+ "pcre2 JSON escapes control chars and quotes");
+ bool rawCtrl = false;
+ for (unsigned char c : s) {
+ if (c < 0x20) rawCtrl = true;
+ }
+ CHECK(!rawCtrl, "pcre2 JSON emits no raw control bytes");
+ jpdfium_free_string(json);
+ }
+ jpdfium_pcre2_free(pat);
+ }
+ }
+
+ int64_t ft = 0;
+ int32_t frc = jpdfium_flashtext_create(&ft);
+ if (frc != JPDFIUM_ERR_NOT_FOUND) {
+ CHECK(frc == JPDFIUM_OK && ft != 0, "flashtext create");
+ if (frc == JPDFIUM_OK && ft != 0) {
+ const char* kwJson =
+ "[{\"keyword\":\"nolabel\"},{\"keyword\":\"second\",\"label\":\"L1\\\"\\\\\"}]";
+ CHECK(jpdfium_flashtext_add_keywords_json(ft, kwJson) == JPDFIUM_OK,
+ "flashtext add_keywords_json with optional label");
+ CHECK(jpdfium_flashtext_add_keyword(ft, "k1\t\"a", "L\n2") == JPDFIUM_OK,
+ "flashtext add_keyword with control chars");
+ char* fjson = nullptr;
+ CHECK(
+ jpdfium_flashtext_find(ft, "nolabel second k1\t\"a", &fjson) == JPDFIUM_OK && fjson,
+ "flashtext find object-scoped matches");
+ if (fjson) {
+ std::string fs(fjson);
+ CHECK(fs.find("\"keyword\":\"nolabel\",\"label\":\"\"") != std::string::npos,
+ "flashtext scopes omitted label per JSON object");
+ CHECK(fs.find("L1\\\"\\\\") != std::string::npos &&
+ fs.find("k1\\t\\\"a") != std::string::npos &&
+ fs.find("L\\n2") != std::string::npos,
+ "flashtext escapes keyword and label controls in JSON");
+ jpdfium_free_string(fjson);
+ }
+ jpdfium_flashtext_free(ft);
+ }
+ }
+}
+
+void checkPdfxPartialDates() {
+ // Minimal 152-byte CMYK ICC profile with 1 valid tag entry ('desc') so IccComponentCount
+ // validates it even in builds without lcms2.
+ std::vector icc(152, 0);
+ icc[3] = 152;
+ icc[16] = 'C';
+ icc[17] = 'M';
+ icc[18] = 'Y';
+ icc[19] = 'K';
+ icc[36] = 'a';
+ icc[37] = 'c';
+ icc[38] = 's';
+ icc[39] = 'p';
+ icc[131] = 1; // tag_count = 1
+ icc[132] = 'd'; // tag signature 'desc'
+ icc[133] = 'e';
+ icc[134] = 's';
+ icc[135] = 'c';
+ icc[139] = 144; // tag offset = 144
+ icc[143] = 8; // tag size = 8
+ auto datePdf = assemblePdf("%PDF-1.4",
+ {
+ "<< /Type /Catalog /Pages 2 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >>",
+ "<< /CreationDate (D:2024) /ModDate (D:202405) >>",
+ },
+ 1, 4);
+ uint8_t* out = nullptr;
+ int64_t outLen = 0;
+ CHECK(jpdfium_color_pdfx_bytes(datePdf.data(), static_cast(datePdf.size()), icc.data(),
+ static_cast(icc.size()), "PDF/X-4", "PDF/X-4",
+ "FOGRA39", "Test", &out, &outLen) == JPDFIUM_OK &&
+ out && outLen > 0,
+ "pdfx_bytes converts partial Info dates");
+ if (out && outLen > 0) {
+ uint8_t* v14 = nullptr;
+ int64_t v14Len = 0;
+ if (jpdfium_qpdf_force_version(out, outLen, "1.4", &v14, &v14Len) == JPDFIUM_OK && v14 &&
+ v14Len > 0) {
+ std::string raw(reinterpret_cast(v14), static_cast(v14Len));
+ CHECK(raw.find("2024-01-01T00:00:00") != std::string::npos,
+ "partial PDF year date D:2024 expands to 2024-01-01T00:00:00");
+ CHECK(raw.find("2024-05-01T00:00:00") != std::string::npos,
+ "partial PDF month date D:202405 expands to 2024-05-01T00:00:00");
+ jpdfium_free_buffer(v14);
+ }
+ jpdfium_free_buffer(out);
+ }
+}
+
+void checkSparseToUnicodeAndStructSanitize() {
+ std::vector ttf = buildMinimalSparseTtf(108);
+ std::string fontStream = "<< /Length " + std::to_string(ttf.size()) + " /Length1 " +
+ std::to_string(ttf.size()) + " >>\nstream\n" +
+ std::string(ttf.begin(), ttf.end()) + "\nendstream";
+ std::string content = "BT /F1 12 Tf 72 700 Td <0001006C> Tj ET";
+ std::string pageStream =
+ "<< /Length " + std::to_string(content.size()) + " >>\nstream\n" + content + "\nendstream";
+ const std::string pageObj =
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] "
+ "/Resources << /Font << /F1 4 0 R >> >> /Contents 8 0 R >>";
+ const std::string type0Obj =
+ "<< /Type /Font /Subtype /Type0 /BaseFont /SparseSmoke "
+ "/Encoding /Identity-H /DescendantFonts [5 0 R] >>";
+ const std::string cidFontObj =
+ "<< /Type /Font /Subtype /CIDFontType2 /BaseFont /SparseSmoke "
+ "/CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> "
+ "/CIDToGIDMap /Identity /DW 500 /FontDescriptor 6 0 R >>";
+ const std::string fdObj =
+ "<< /Type /FontDescriptor /FontName /SparseSmoke /Flags 4 "
+ "/FontBBox [0 0 500 500] /ItalicAngle 0 /Ascent 800 /Descent -200 "
+ "/CapHeight 700 /StemV 80 /FontFile2 9 0 R >>";
+ auto fontPdf = assemblePdf("%PDF-1.4",
+ {
+ "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 7 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ pageObj,
+ type0Obj,
+ cidFontObj,
+ fdObj,
+ "<< /Type /StructTreeRoot >>",
+ pageStream,
+ fontStream,
+ },
+ 1);
+
+ int64_t doc = 0;
+ CHECK(jpdfium_doc_open_bytes(fontPdf.data(), static_cast(fontPdf.size()), &doc) ==
+ JPDFIUM_OK,
+ "open sparse >100-glyph PDF");
+ if (doc == 0) return;
+
+ int32_t fixed = 0;
+ CHECK(jpdfium_font_fix_tounicode(doc, 0, &fixed) == JPDFIUM_OK && fixed == 1,
+ "font_fix_tounicode repairs >100-glyph ToUnicode");
+ uint8_t* saved = nullptr;
+ int64_t savedLen = 0;
+ CHECK(jpdfium_doc_save_bytes(doc, &saved, &savedLen) == JPDFIUM_OK && saved && savedLen > 0,
+ "save repaired >100-glyph PDF");
+ jpdfium_doc_close(doc);
+ if (!saved || savedLen <= 0) return;
+
+ int64_t reopened = 0;
+ if (jpdfium_doc_open_bytes(saved, savedLen, &reopened) == JPDFIUM_OK && reopened) {
+ int64_t page = 0;
+ if (jpdfium_page_open(reopened, 0, &page) == JPDFIUM_OK && page) {
+ char* charsJson = nullptr;
+ CHECK(jpdfium_text_get_chars(page, &charsJson) == JPDFIUM_OK && charsJson,
+ "extract text across >100 beginbfchar chunks");
+ if (charsJson) {
+ std::string cj(charsJson);
+ CHECK(cj.find("1026") != std::string::npos && cj.find("1240") != std::string::npos,
+ "decoded chars span GID 1 (0x0402) and GID 108 (0x04D8)");
+ jpdfium_free_string(charsJson);
+ }
+ jpdfium_page_close(page);
+ }
+ jpdfium_doc_close(reopened);
+ }
+
+ uint8_t* san = nullptr;
+ int64_t sanLen = 0;
+ CHECK(jpdfium_qpdf_sanitize(saved, savedLen, &san, &sanLen, JPDFIUM_SANITIZE_STRUCTURE) ==
+ JPDFIUM_OK &&
+ san && sanLen > 0,
+ "qpdf_sanitize removes /StructTreeRoot");
+ if (san && sanLen > 0) {
+ std::string raw(reinterpret_cast(san), static_cast(sanLen));
+ CHECK(raw.find("/StructTreeRoot") == std::string::npos,
+ "sanitized output omits /StructTreeRoot");
+ jpdfium_free_buffer(san);
+ }
+ jpdfium_free_buffer(saved);
+}
+
+void checkForceVersion14Metadata() {
+ const std::string xmp =
+ ""
+ ""
+ "";
+ std::string metaStream = "<< /Type /Metadata /Subtype /XML /Length " +
+ std::to_string(xmp.size()) + " >>\nstream\n" + xmp + "\nendstream";
+ auto v17Pdf = assemblePdf("%PDF-1.7",
+ {
+ "<< /Type /Catalog /Pages 2 0 R /Metadata 4 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >>",
+ metaStream,
+ },
+ 1);
+ uint8_t* out = nullptr;
+ int64_t outLen = 0;
+ CHECK(jpdfium_qpdf_force_version(v17Pdf.data(), static_cast(v17Pdf.size()), "1.4",
+ &out, &outLen) == JPDFIUM_OK &&
+ out && outLen > 8,
+ "qpdf_force_version 1.4 succeeds");
+ if (out && outLen > 8) {
+ std::string raw(reinterpret_cast(out), static_cast(outLen));
+ CHECK(raw.rfind("%PDF-1.4", 0) == 0, "force_version writes %PDF-1.4 header");
+ CHECK(raw.find("/ObjStm") == std::string::npos, "force_version 1.4 avoids /ObjStm");
+ CHECK(raw.find("