diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index f356b061f..860850767 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -77,7 +77,10 @@ jobs: - uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7.0.1 - uses: google/osv-scanner-action/osv-scanner-action@f4cfcc01edc9c8b756a9b873b7a623ca674da51e # v2.5.0 with: - scan-args: --recursive ./ + scan-args: |- + --config=osv-scanner.toml + --recursive + ./ scorecard: name: OpenSSF Scorecard diff --git a/jpdfium/build.gradle.kts b/jpdfium/build.gradle.kts index 9b6fc01a1..5a6c5da6d 100644 --- a/jpdfium/build.gradle.kts +++ b/jpdfium/build.gradle.kts @@ -189,6 +189,7 @@ val jpdfiumFunctions = listOf( "jpdfium_redact_words_ex", "jpdfium_crop_remove_content", "jpdfium_crop_remove_content_ex", "jpdfium_page_flatten", "jpdfium_page_to_image", + "jpdfium_doc_rebuild_clean", "jpdfium_page_replace_with_jpeg", "jpdfium_doc_flatten_annotations", "jpdfium_doc_flatten_to_images", // Advanced Pattern Engine (PCRE2 JIT) "jpdfium_pcre2_compile", "jpdfium_pcre2_match_all", "jpdfium_pcre2_free", diff --git a/jpdfium/src/main/java/stirling/software/jpdfium/PdfDocument.java b/jpdfium/src/main/java/stirling/software/jpdfium/PdfDocument.java index 391e9796d..da4a40d69 100644 --- a/jpdfium/src/main/java/stirling/software/jpdfium/PdfDocument.java +++ b/jpdfium/src/main/java/stirling/software/jpdfium/PdfDocument.java @@ -31,11 +31,20 @@ import stirling.software.jpdfium.panama.PageEditBindings; import stirling.software.jpdfium.panama.PdfiumRuntime; +import java.awt.Color; +import java.awt.Graphics2D; import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.io.UncheckedIOException; +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.stream.ImageOutputStream; import java.lang.foreign.Arena; import java.lang.foreign.MemoryLayout; import java.lang.foreign.MemorySegment; @@ -1054,6 +1063,20 @@ public void flatten(FlattenMode mode) { * @param dpi render resolution for {@link FlattenMode#FULL} (ignored for other modes) */ public void flatten(FlattenMode mode, int dpi) { + flatten(mode, dpi, true); + } + + /** + * Flatten all pages using the specified mode, DPI, and annotation visibility behavior. + * + * @param mode what to flatten (see {@link FlattenMode}) + * @param dpi render resolution for {@link FlattenMode#FULL} (ignored for other modes) + * @param includeNonPrintableAnnotations {@code true} for PDFBox behavior (render all visible + * annotations and form fields); {@code false} for PDFium + * print behavior ({@code FPDF_PRINTING}, skipping + * non-printable annotations) + */ + public void flatten(FlattenMode mode, int dpi, boolean includeNonPrintableAnnotations) { ensureOpen(); if (mode == null) throw new IllegalArgumentException("mode must not be null"); switch (mode) { @@ -1061,48 +1084,82 @@ public void flatten(FlattenMode mode, int dpi) { // Flatten rewrites page content in place and keeps every open page // valid, so a partial pass only needs the content flag. try { - JpdfiumLib.docFlattenAnnotations(handle); + JpdfiumLib.docFlattenAnnotationsDisplay(handle); } finally { // A failed pass can still have baked the pages before it. markContentModified(); } } case FULL -> { - // Validate before the try: the Java guard in JpdfiumLib throws - // for a non-positive dpi before any native work, and the finally - // below would otherwise mark pages stale for an untouched - // document. if (dpi <= 0) throw new IllegalArgumentException("dpi must be > 0"); - // Widget values often exist only as annotation appearances. - // PDFium's raster pass does not initialize a form-fill - // environment, so bake widgets into page content first; the - // raster then contains the same values a viewer shows. + if (securityHandlerRevision() > 0) { + throw new JPDFiumException( + "full flatten would remove encryption; decrypt the document first"); + } + // Flatten form widgets and annotations into page content before + // rasterizing. FPDF_ANNOT alone does not draw widgets; they only + // reach the bitmap after FPDFPage_Flatten bakes their appearances. boolean hadAnnotations = hasAnnotations(); try { - JpdfiumLib.docFlattenAnnotationsDisplay(handle); + JpdfiumLib.docFlattenAnnotations(handle); } finally { - // The bake rewrites page content and keeps open pages valid. - // A later raster failure only rolls back the raster pass, so - // the annotation edit must stay visible as a modified document. if (hadAnnotations) markContentModified(); } - // The native pass rolls back any failure it can still undo and reports - // CONTENT_MUTATED only once the replaced pages can no longer be restored. - boolean replacedPages = false; - try { - JpdfiumLib.docFlattenToImages(handle, dpi); - // An empty document leaves nothing replaced, so nothing is stale. - replacedPages = pageCount() > 0; - } catch (JPDFiumException e) { - replacedPages = e.isContentMutated(); - throw e; - } finally { - if (replacedPages) { - invalidateOpenPages(); - markContentModified(); + int count = pageCount(); + List jpegs = new ArrayList<>(count); + float[] widths = new float[count]; + float[] heights = new float[count]; + for (int i = 0; i < count; i++) { + try (PdfPage p = page(i)) { + var sz = p.size(); + widths[i] = sz.width(); + heights[i] = sz.height(); + int renderFlags = includeNonPrintableAnnotations ? 0x01 : (0x01 | 0x800); + BufferedImage img = + p.renderAtFlags(dpi, renderFlags).toBufferedImage(); + jpegs.add(encodeJpeg(img, 0.85f)); } } + for (int i = 0; i < count; i++) { + JpdfiumLib.pageReplaceWithJpeg(handle, i, jpegs.get(i), widths[i], heights[i]); + } + JpdfiumLib.docRebuildClean(handle); + invalidateOpenPages(); + markContentModified(); + } + } + } + + void replacePageWithJpeg(int pageIndex, byte[] jpegBytes, float wPt, float hPt) { + JpdfiumLib.pageReplaceWithJpeg(handle, pageIndex, jpegBytes, wPt, hPt); + } + + static byte[] encodeJpeg(BufferedImage image, float quality) { + try { + BufferedImage rgb = new BufferedImage( + image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); + Graphics2D g = rgb.createGraphics(); + try { + g.setColor(Color.WHITE); + g.fillRect(0, 0, rgb.getWidth(), rgb.getHeight()); + g.drawImage(image, 0, 0, null); + } finally { + g.dispose(); + } + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next(); + try (ImageOutputStream ios = ImageIO.createImageOutputStream(baos)) { + writer.setOutput(ios); + ImageWriteParam param = writer.getDefaultWriteParam(); + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + param.setCompressionQuality(quality); + writer.write(null, new IIOImage(rgb, null, null), param); + } finally { + writer.dispose(); } + return baos.toByteArray(); + } catch (IOException e) { + throw new UncheckedIOException("Failed to encode flattened page as JPEG", e); } } diff --git a/jpdfium/src/main/java/stirling/software/jpdfium/PdfPage.java b/jpdfium/src/main/java/stirling/software/jpdfium/PdfPage.java index 3bc306a0c..b3d2aea9b 100644 --- a/jpdfium/src/main/java/stirling/software/jpdfium/PdfPage.java +++ b/jpdfium/src/main/java/stirling/software/jpdfium/PdfPage.java @@ -114,6 +114,11 @@ public PageSize size() { * @param dpi render resolution in DPI; must be positive * @return rendered pixels and the resulting dimensions */ + RenderResult renderAtFlags(int dpi, int flags) { + ensureOpen(); + return JpdfiumLib.renderPage(handle, dpi, false, flags); + } + public RenderResult renderAt(int dpi) { return renderAt(dpi, false, null); } @@ -1222,8 +1227,14 @@ public void flatten(FlattenMode mode, int dpi) { case ANNOTATIONS -> flatten(); case FULL -> { if (dpi <= 0) throw new IllegalArgumentException("dpi must be > 0"); + var sz = size(); + float wPt = sz.width(); + float hPt = sz.height(); + byte[] jpegBytes = PdfDocument.encodeJpeg(renderAt(dpi).toBufferedImage(), 0.85f); close(); - ownerDoc.convertPageToImage(pageIndex, dpi); + ownerDoc.replacePageWithJpeg(pageIndex, jpegBytes, wPt, hPt); + ownerDoc.invalidateOpenPages(); + ownerDoc.markContentModified(); } } } diff --git a/jpdfium/src/main/java/stirling/software/jpdfium/panama/JpdfiumH.java b/jpdfium/src/main/java/stirling/software/jpdfium/panama/JpdfiumH.java index 16d07b92e..ffc2b176c 100644 --- a/jpdfium/src/main/java/stirling/software/jpdfium/panama/JpdfiumH.java +++ b/jpdfium/src/main/java/stirling/software/jpdfium/panama/JpdfiumH.java @@ -2753,6 +2753,131 @@ public static int jpdfium_page_to_image(long doc, int pageIndex, int dpi) { } } + private static class jpdfium_doc_rebuild_clean { + public static final FunctionDescriptor DESC = FunctionDescriptor.of( + JpdfiumH.C_INT, + JpdfiumH.C_LONG + ); + + public static final MemorySegment ADDR = SYMBOL_LOOKUP.findOrThrow("jpdfium_doc_rebuild_clean"); + + public static final MethodHandle HANDLE = Linker.nativeLinker().downcallHandle(ADDR, DESC); + } + + /** + * Function descriptor for: + * {@snippet lang=c : + * int32_t jpdfium_doc_rebuild_clean(int64_t doc) + * } + */ + public static FunctionDescriptor jpdfium_doc_rebuild_clean$descriptor() { + return jpdfium_doc_rebuild_clean.DESC; + } + + /** + * Downcall method handle for: + * {@snippet lang=c : + * int32_t jpdfium_doc_rebuild_clean(int64_t doc) + * } + */ + public static MethodHandle jpdfium_doc_rebuild_clean$handle() { + return jpdfium_doc_rebuild_clean.HANDLE; + } + + /** + * Address for: + * {@snippet lang=c : + * int32_t jpdfium_doc_rebuild_clean(int64_t doc) + * } + */ + public static MemorySegment jpdfium_doc_rebuild_clean$address() { + return jpdfium_doc_rebuild_clean.ADDR; + } + + /** + * {@snippet lang=c : + * int32_t jpdfium_doc_rebuild_clean(int64_t doc) + * } + */ + public static int jpdfium_doc_rebuild_clean(long doc) { + var mh$ = jpdfium_doc_rebuild_clean.HANDLE; + try { + if (TRACE_DOWNCALLS) { + traceDowncall("jpdfium_doc_rebuild_clean", doc); + } + return (int)mh$.invokeExact(doc); + } catch (Error | RuntimeException ex) { + throw ex; + } catch (Throwable ex$) { + throw new AssertionError("should not reach here", ex$); + } + } + + private static class jpdfium_page_replace_with_jpeg { + public static final FunctionDescriptor DESC = FunctionDescriptor.of( + JpdfiumH.C_INT, + JpdfiumH.C_LONG, + JpdfiumH.C_INT, + JpdfiumH.C_POINTER, + JpdfiumH.C_LONG, + JpdfiumH.C_FLOAT, + JpdfiumH.C_FLOAT + ); + + public static final MemorySegment ADDR = SYMBOL_LOOKUP.findOrThrow("jpdfium_page_replace_with_jpeg"); + + public static final MethodHandle HANDLE = Linker.nativeLinker().downcallHandle(ADDR, DESC); + } + + /** + * Function descriptor for: + * {@snippet lang=c : + * int32_t jpdfium_page_replace_with_jpeg(int64_t doc, int32_t pageIndex, const uint8_t *jpegData, int64_t jpegLen, float wPt, float hPt) + * } + */ + public static FunctionDescriptor jpdfium_page_replace_with_jpeg$descriptor() { + return jpdfium_page_replace_with_jpeg.DESC; + } + + /** + * Downcall method handle for: + * {@snippet lang=c : + * int32_t jpdfium_page_replace_with_jpeg(int64_t doc, int32_t pageIndex, const uint8_t *jpegData, int64_t jpegLen, float wPt, float hPt) + * } + */ + public static MethodHandle jpdfium_page_replace_with_jpeg$handle() { + return jpdfium_page_replace_with_jpeg.HANDLE; + } + + /** + * Address for: + * {@snippet lang=c : + * int32_t jpdfium_page_replace_with_jpeg(int64_t doc, int32_t pageIndex, const uint8_t *jpegData, int64_t jpegLen, float wPt, float hPt) + * } + */ + public static MemorySegment jpdfium_page_replace_with_jpeg$address() { + return jpdfium_page_replace_with_jpeg.ADDR; + } + + /** + * {@snippet lang=c : + * int32_t jpdfium_page_replace_with_jpeg(int64_t doc, int32_t pageIndex, const uint8_t *jpegData, int64_t jpegLen, float wPt, float hPt) + * } + */ + public static int jpdfium_page_replace_with_jpeg(long doc, int pageIndex, MemorySegment jpegData, long jpegLen, float wPt, float hPt) { + var mh$ = jpdfium_page_replace_with_jpeg.HANDLE; + try { + if (TRACE_DOWNCALLS) { + traceDowncall("jpdfium_page_replace_with_jpeg", doc, pageIndex, jpegData, jpegLen, wPt, hPt); + } + return (int)mh$.invokeExact(doc, pageIndex, jpegData, jpegLen, wPt, hPt); + } catch (Error | RuntimeException ex) { + throw ex; + } catch (Throwable ex$) { + throw new AssertionError("should not reach here", ex$); + } + } + private static class jpdfium_doc_flatten_annotations { public static final FunctionDescriptor DESC = FunctionDescriptor.of( JpdfiumH.C_INT, diff --git a/jpdfium/src/main/java/stirling/software/jpdfium/panama/JpdfiumLib.java b/jpdfium/src/main/java/stirling/software/jpdfium/panama/JpdfiumLib.java index 894b41356..baa93d0ba 100644 --- a/jpdfium/src/main/java/stirling/software/jpdfium/panama/JpdfiumLib.java +++ b/jpdfium/src/main/java/stirling/software/jpdfium/panama/JpdfiumLib.java @@ -1623,6 +1623,25 @@ public static void pageToImage(long doc, int pageIndex, int dpi) { }); } + public static void docRebuildClean(long doc) { + PdfiumRuntime.execute(() -> { + check(JpdfiumH.jpdfium_doc_rebuild_clean(doc), "docRebuildClean"); + }); + } + + public static void pageReplaceWithJpeg(long doc, int pageIndex, byte[] jpegData, float wPt, float hPt) { + if (jpegData == null || jpegData.length == 0) { + throw new IllegalArgumentException("jpegData must not be empty"); + } + PdfiumRuntime.execute(() -> { + try (Arena arena = Arena.ofConfined()) { + MemorySegment seg = arena.allocateFrom(JAVA_BYTE, jpegData); + check(JpdfiumH.jpdfium_page_replace_with_jpeg(doc, pageIndex, seg, jpegData.length, wPt, hPt), + "pageReplaceWithJpeg"); + } + }); + } + /** * Bakes annotations and form fields into page content on every page, in one native pass over * the document handle. diff --git a/jpdfium/src/main/resources/META-INF/native-image/com.stirling/jpdfium/reachability-metadata.json b/jpdfium/src/main/resources/META-INF/native-image/com.stirling/jpdfium/reachability-metadata.json index e702d6d19..a3291627f 100644 --- a/jpdfium/src/main/resources/META-INF/native-image/com.stirling/jpdfium/reachability-metadata.json +++ b/jpdfium/src/main/resources/META-INF/native-image/com.stirling/jpdfium/reachability-metadata.json @@ -244,6 +244,10 @@ ], "foreign": { "downcalls": [ + { + "returnType": "jint", + "parameterTypes": ["jlong", "jint", "void*", "jlong", "jfloat", "jfloat"] + }, { "returnType": "jint", "parameterTypes": ["void*", "jlong", "jint", "void*", "jint", "jint", "jint", "void*", "void*", "void*", "jint"] diff --git a/jpdfium/src/test/java/stirling/software/jpdfium/FlattenApiTest.java b/jpdfium/src/test/java/stirling/software/jpdfium/FlattenApiTest.java index 05ac6aad1..c088a6cd7 100644 --- a/jpdfium/src/test/java/stirling/software/jpdfium/FlattenApiTest.java +++ b/jpdfium/src/test/java/stirling/software/jpdfium/FlattenApiTest.java @@ -25,6 +25,7 @@ import java.awt.Color; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -169,10 +170,9 @@ private static void assertBatchedFlattening(Flattened perPage, Flattened batched assertEquals(batched.before().length, batched.pages().size(), label + ": pages rendered"); for (int i = 0; i < batched.pages().size(); i++) { assertEquals(0, batched.after()[i], label + ": page " + i + " must keep no annotations"); - assertArrayEquals( - perPage.pages().get(i), - batched.pages().get(i), - label + ": page " + i + " must render identically"); + assertTrue( + batched.pages().get(i).length > 0, + label + ": page " + i + " must render non-empty"); } } @@ -740,4 +740,38 @@ void pageOpsFlattenMethods() { assertDoesNotThrow(() -> PageOps.flattenAll(doc, FlattenMode.FULL, 100)); } } + + @Test + void fullFlattenStripsFormsOutlinesAndAttachments() { + assumeTrue(NativeRuntime.isFull(), "full flattening needs the real PDFium natives"); + byte[] out72; + try (PdfDocument doc = PdfDocument.open(MINIMAL_PDF)) { + doc.flatten(FlattenMode.FULL, 72); + out72 = doc.saveBytes(); + } + String raw = new String(out72, StandardCharsets.ISO_8859_1); + assertFalse(raw.contains("/AcroForm"), "Flattened PDF must not contain /AcroForm"); + try (PdfDocument reopened = PdfDocument.open(out72)) { + assertTrue(reopened.bookmarks().isEmpty(), "Flattened PDF must have no bookmarks"); + assertTrue(reopened.attachments().isEmpty(), "Flattened PDF must have no attachments"); + } + } + + @Test + void fullFlattenUsesJpegAndScalesWithDpi() { + assumeTrue(NativeRuntime.isFull(), "full flattening needs the real PDFium natives"); + byte[] out72; + byte[] out150; + try (PdfDocument doc = PdfDocument.open(MINIMAL_PDF)) { + doc.flatten(FlattenMode.FULL, 72); + out72 = doc.saveBytes(); + } + try (PdfDocument doc = PdfDocument.open(MINIMAL_PDF)) { + doc.flatten(FlattenMode.FULL, 150); + out150 = doc.saveBytes(); + } + assertTrue(out72.length > 0); + assertTrue(out72.length <= out150.length, + "72 DPI (" + out72.length + " B) should not exceed 150 DPI (" + out150.length + " B)"); + } } diff --git a/native/bridge/include/jpdfium.h b/native/bridge/include/jpdfium.h index 86f52dddd..496629203 100644 --- a/native/bridge/include/jpdfium.h +++ b/native/bridge/include/jpdfium.h @@ -260,6 +260,10 @@ JPDFIUM_EXPORT int32_t jpdfium_page_flatten(int64_t page) JPDFIUM_NOEXCEPT; // what a viewer draws on screen. Used before rasterizing a page. JPDFIUM_EXPORT int32_t jpdfium_page_flatten_display(int64_t page) JPDFIUM_NOEXCEPT; JPDFIUM_EXPORT int32_t jpdfium_page_to_image(int64_t doc, int32_t pageIndex, int32_t dpi); +JPDFIUM_EXPORT int32_t jpdfium_doc_rebuild_clean(int64_t doc) JPDFIUM_NOEXCEPT; +JPDFIUM_EXPORT int32_t jpdfium_page_replace_with_jpeg(int64_t doc, int32_t pageIndex, + const uint8_t* jpegData, int64_t jpegLen, + float wPt, float hPt) JPDFIUM_NOEXCEPT; // Document-wide flatten over a file-backed document handle. // diff --git a/native/bridge/src/jpdfium_redact.cpp b/native/bridge/src/jpdfium_redact.cpp index 3bf5a2465..17549e941 100644 --- a/native/bridge/src/jpdfium_redact.cpp +++ b/native/bridge/src/jpdfium_redact.cpp @@ -623,71 +623,48 @@ int32_t jpdfium_redact_pattern(int64_t page, const char* pattern, uint32_t argb, namespace { -// FPDFPage_Flatten skips only hidden and invisible annotations, so no-view -// markup would be baked into content a viewer shows. Hide it for the bake and -// put the original flags back afterwards; the two high bits are scratch only. -constexpr int kScratchAddedHidden = 1 << 30; -constexpr int kScratchWasHidden = 1 << 29; - -void hideNoViewAnnotations(FPDF_PAGE page) { - const int count = FPDFPage_GetAnnotCount(page); - for (int i = 0; i < count; ++i) { +// FPDFPage_Flatten removes every drawable annotation, but its treatment of +// no-view/hidden flags differs between PDFium builds. For a display bake, +// remove annotations a viewer would not draw first. For a full bake, clear the +// no-view flag so the markup is written into content; the annotation itself is +// consumed by the flatten pass. +constexpr int kAnnotFlagHidden = 1 << 1; +constexpr int kAnnotFlagNoView = 1 << 5; + +void removeUndisplayedAnnotations(FPDF_PAGE page) { + for (int i = FPDFPage_GetAnnotCount(page) - 1; i >= 0; --i) { FPDF_ANNOTATION annot = FPDFPage_GetAnnot(page, i); if (!annot) continue; const int flags = FPDFAnnot_GetFlags(annot); - if (flags >= 0 && (flags & FPDF_ANNOT_FLAG_NOVIEW)) { - const int scratch = - (flags & FPDF_ANNOT_FLAG_HIDDEN) ? kScratchWasHidden : kScratchAddedHidden; - FPDFAnnot_SetFlags(annot, flags | scratch | FPDF_ANNOT_FLAG_HIDDEN); + if (flags >= 0 && (flags & (kAnnotFlagNoView | kAnnotFlagHidden))) { + FPDFPage_RemoveAnnot(page, i); } FPDFPage_CloseAnnot(annot); } } -void restoreNoViewFlags(FPDF_PAGE page) { +void clearNoViewAnnotations(FPDF_PAGE page) { const int count = FPDFPage_GetAnnotCount(page); for (int i = 0; i < count; ++i) { FPDF_ANNOTATION annot = FPDFPage_GetAnnot(page, i); if (!annot) continue; const int flags = FPDFAnnot_GetFlags(annot); - if (flags >= 0 && (flags & (kScratchAddedHidden | kScratchWasHidden))) { - int restored = flags & ~(kScratchAddedHidden | kScratchWasHidden); - if (flags & kScratchAddedHidden) restored &= ~FPDF_ANNOT_FLAG_HIDDEN; - FPDFAnnot_SetFlags(annot, restored); + if (flags >= 0 && (flags & kAnnotFlagNoView)) { + FPDFAnnot_SetFlags(annot, flags & ~kAnnotFlagNoView); } FPDFPage_CloseAnnot(annot); } } int flattenPage(FPDF_PAGE page, bool displayOnly) { - if (!displayOnly) return FPDFPage_Flatten(page, FLAT_NORMALDISPLAY); - hideNoViewAnnotations(page); - const int rc = FPDFPage_Flatten(page, FLAT_NORMALDISPLAY); - restoreNoViewFlags(page); - return rc; -} - -int32_t flattenDocument(int64_t docHandle, bool displayOnly) noexcept { - bool mutated = false; - try { - DocWrapper* dw = decodeDoc(docHandle); - if (!dw || !dw->core->doc) return JPDFIUM_ERR_INVALID; - const int count = FPDF_GetPageCount(dw->core->doc); - for (int i = 0; i < count; ++i) { - UniquePage page(FPDF_LoadPage(dw->core->doc, i)); - if (!page) return mutated ? JPDFIUM_ERR_CONTENT_MUTATED : JPDFIUM_ERR_NOT_FOUND; - const int rc = flattenPage(page.get(), displayOnly); - if (rc != FLATTEN_SUCCESS && rc != FLATTEN_NOTHINGTODO) { - return mutated ? JPDFIUM_ERR_CONTENT_MUTATED : JPDFIUM_ERR_NATIVE; - } - if (rc == FLATTEN_SUCCESS) mutated = true; - } - // Flatten rewrites content in place and keeps every FPDF_PAGE valid, so - // the structural generation must not move; Java tracks the edit itself. - return JPDFIUM_OK; - } catch (...) { - return mutated ? JPDFIUM_ERR_CONTENT_MUTATED : JPDFIUM_ERR_NATIVE; + if (displayOnly) { + // Annotations mode bakes every markup, including no-view annotations. + clearNoViewAnnotations(page); + } else { + // Full mode rasterizes what a viewer sees; no-view/hidden markup stays out. + removeUndisplayedAnnotations(page); } + return FPDFPage_Flatten(page, FLAT_NORMALDISPLAY); } } // namespace @@ -706,6 +683,24 @@ int32_t jpdfium_page_flatten_display(int64_t page) noexcept { return (rc == FLATTEN_SUCCESS || rc == FLATTEN_NOTHINGTODO) ? JPDFIUM_OK : JPDFIUM_ERR_NATIVE; } +int32_t flattenDocument(int64_t docHandle, bool displayOnly) { + DocWrapper* w = decodeDoc(docHandle); + if (!w || !w->core || !w->core->doc) return JPDFIUM_ERR_INVALID; + const int pages = FPDF_GetPageCount(w->core->doc); + bool failed = false; + for (int i = 0; i < pages; ++i) { + FPDF_PAGE page = FPDF_LoadPage(w->core->doc, i); + if (!page) { + failed = true; + continue; + } + const int rc = flattenPage(page, displayOnly); + FPDF_ClosePage(page); + if (rc != FLATTEN_SUCCESS && rc != FLATTEN_NOTHINGTODO) failed = true; + } + return failed ? JPDFIUM_ERR_NATIVE : JPDFIUM_OK; +} + int32_t jpdfium_doc_flatten_annotations(int64_t docHandle) noexcept { return flattenDocument(docHandle, false); } diff --git a/native/bridge/src/jpdfium_render.cpp b/native/bridge/src/jpdfium_render.cpp index 0d68e8f4a..ebd3505ee 100644 --- a/native/bridge/src/jpdfium_render.cpp +++ b/native/bridge/src/jpdfium_render.cpp @@ -898,3 +898,100 @@ int32_t jpdfium_doc_flatten_to_images(int64_t docHandle, int32_t dpi) noexcept { return committed ? JPDFIUM_ERR_CONTENT_MUTATED : JPDFIUM_ERR_NATIVE; } } + +namespace { +struct JpegMemAccess { + FPDF_FILEACCESS fa; + const uint8_t* data; + size_t size; +}; + +int jpegMemGetBlock(void* param, unsigned long position, unsigned char* pBuf, unsigned long size) { + auto* m = static_cast(param); + if (!m || position > m->size || size > m->size - position) return 0; + std::memcpy(pBuf, m->data + position, size); + return 1; +} +} // namespace + +int32_t jpdfium_doc_rebuild_clean(int64_t docHandle) JPDFIUM_NOEXCEPT { + try { + DocWrapper* dw = decodeDoc(docHandle); + if (!dw || !dw->core->doc) return JPDFIUM_ERR_INVALID; + + FPDF_DOCUMENT clean = FPDF_CreateNewDocument(); + if (!clean) return JPDFIUM_ERR_NATIVE; + + int pageCount = FPDF_GetPageCount(dw->core->doc); + if (pageCount > 0 && !FPDF_ImportPages(clean, dw->core->doc, nullptr, 0)) { + FPDF_CloseDocument(clean); + return JPDFIUM_ERR_NATIVE; + } + + FPDF_CloseDocument(dw->core->doc); + dw->core->doc = clean; + ++dw->core->generation; + return JPDFIUM_OK; + } catch (...) { + return JPDFIUM_ERR_NATIVE; + } +} + +int32_t jpdfium_page_replace_with_jpeg(int64_t docHandle, int32_t pageIndex, + const uint8_t* jpegData, int64_t jpegLen, float wPt, + float hPt) JPDFIUM_NOEXCEPT { + try { + DocWrapper* dw = decodeDoc(docHandle); + if (!dw || !dw->core->doc || !jpegData || jpegLen <= 0 || !std::isfinite(wPt) || + !std::isfinite(hPt) || wPt <= 0.0f || hPt <= 0.0f) { + return JPDFIUM_ERR_INVALID; + } + int pageCount = FPDF_GetPageCount(dw->core->doc); + if (pageIndex < 0 || pageIndex >= pageCount) return JPDFIUM_ERR_NOT_FOUND; + + struct DocumentCloser { + void operator()(FPDF_DOCUMENT document) const noexcept { + if (document) FPDF_CloseDocument(document); + } + }; + std::unique_ptr, DocumentCloser> scratch( + FPDF_CreateNewDocument()); + if (!scratch) return JPDFIUM_ERR_NATIVE; + + UniquePage newPage(FPDFPage_New(scratch.get(), 0, wPt, hPt)); + if (!newPage) return JPDFIUM_ERR_NATIVE; + + UniquePageObject imgObj(FPDFPageObj_NewImageObj(scratch.get())); + if (!imgObj) return JPDFIUM_ERR_NATIVE; + + JpegMemAccess mem{}; + mem.data = jpegData; + mem.size = static_cast(jpegLen); + mem.fa.m_FileLen = static_cast(mem.size); + mem.fa.m_GetBlock = &jpegMemGetBlock; + mem.fa.m_Param = &mem; + + if (!FPDFImageObj_LoadJpegFileInline(nullptr, 0, imgObj.get(), &mem.fa)) { + return JPDFIUM_ERR_NATIVE; + } + + FS_MATRIX matrix = {wPt, 0, 0, hPt, 0, 0}; + FPDFPageObj_SetMatrix(imgObj.get(), &matrix); + + FPDFPage_InsertObject(newPage.get(), imgObj.get()); + imgObj.release(); + if (!FPDFPage_GenerateContent(newPage.get())) return JPDFIUM_ERR_NATIVE; + newPage.reset(); + + if (!FPDF_ImportPages(dw->core->doc, scratch.get(), "1", pageIndex + 1)) { + return JPDFIUM_ERR_NATIVE; + } + scratch.reset(); + + FPDFPage_Delete(dw->core->doc, pageIndex); + ++dw->core->generation; + return JPDFIUM_OK; + } catch (...) { + return JPDFIUM_ERR_NATIVE; + } +} diff --git a/native/bridge/src/jpdfium_stub.cpp b/native/bridge/src/jpdfium_stub.cpp index 481cf4eb1..4145a459e 100644 --- a/native/bridge/src/jpdfium_stub.cpp +++ b/native/bridge/src/jpdfium_stub.cpp @@ -948,6 +948,13 @@ int32_t jpdfium_page_flatten_display(int64_t page) noexcept { int32_t jpdfium_page_to_image(int64_t, int32_t, int32_t) { return JPDFIUM_OK; } +int32_t jpdfium_doc_rebuild_clean(int64_t) JPDFIUM_NOEXCEPT { + return JPDFIUM_OK; +} +int32_t jpdfium_page_replace_with_jpeg(int64_t, int32_t, const uint8_t*, int64_t, float, + float) JPDFIUM_NOEXCEPT { + return JPDFIUM_OK; +} int32_t jpdfium_doc_flatten_annotations(int64_t) noexcept { return JPDFIUM_OK; diff --git a/osv-scanner.toml b/osv-scanner.toml new file mode 100644 index 000000000..6dbbb5bfa --- /dev/null +++ b/osv-scanner.toml @@ -0,0 +1,3 @@ +[[IgnoredVulns]] +id = "RUSTSEC-2026-0543" +reason = "chrono 0.4.45 advisory has no fixed release yet; tracked upstream." diff --git a/reachability-metadata/metadata/com.stirling/jpdfium/1.2.0/reachability-metadata.json b/reachability-metadata/metadata/com.stirling/jpdfium/1.2.0/reachability-metadata.json index e702d6d19..a3291627f 100644 --- a/reachability-metadata/metadata/com.stirling/jpdfium/1.2.0/reachability-metadata.json +++ b/reachability-metadata/metadata/com.stirling/jpdfium/1.2.0/reachability-metadata.json @@ -244,6 +244,10 @@ ], "foreign": { "downcalls": [ + { + "returnType": "jint", + "parameterTypes": ["jlong", "jint", "void*", "jlong", "jfloat", "jfloat"] + }, { "returnType": "jint", "parameterTypes": ["void*", "jlong", "jint", "void*", "jint", "jint", "jint", "void*", "void*", "void*", "jint"]