Repository navigation
Render form fields/annotations, strip catalog data, and embed JPEG in FlattenMode.FULL #303
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
6cf3576
4f3d4af
5aea45f
6356845
878dc34
2770585
71e52d7
509c74c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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,55 +1063,103 @@ 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) { | ||
| case ANNOTATIONS -> { | ||
| // 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<byte[]> 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); | ||
|
balazs-szucs marked this conversation as resolved.
Resolved
|
||
| BufferedImage img = | ||
| p.renderAtFlags(dpi, renderFlags).toBufferedImage(); | ||
| jpegs.add(encodeJpeg(img, 0.85f)); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do not retain every page JPEG on the Java heap. The first pass stores all encoded pages before replacement starts. Heap retention therefore grows with the complete rasterized document, in addition to each active render and RGB image. A per-page render limit does not bound this list. Spool prepared JPEGs to owned temporary storage, or prepare a separate destination incrementally with bounded page buffers. Preserve preparation-before-publication and failure cleanup. As per coding guidelines, “Flag unbounded Source: Coding guidelines |
||
| } | ||
| } | ||
| for (int i = 0; i < count; i++) { | ||
| JpdfiumLib.pageReplaceWithJpeg(handle, i, jpegs.get(i), widths[i], heights[i]); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reconcile Java state after a partial replacement failure. If page 0 replacement succeeds and page 1 replacement fails, page 0 remains replaced and native generation has advanced. The exception skips Track completed replacements and reconcile state in As per coding guidelines, “Preserve stable public behavior” for ownership and exception semantics. Source: Coding guidelines
Comment on lines
+1123
to
+1124
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Keep the destructive replacement phase inside one admission. If another thread calls Keep JPEG encoding outside the domain. Run the replacement loop, rebuild, and state reconciliation inside one As per coding guidelines, “accepted batches must follow their documented continuation contract.” Source: Coding guidelines |
||
| } | ||
| 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); | ||
| } | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -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); | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||||||
| byte[] jpegBytes = PdfDocument.encodeJpeg(renderAt(dpi).toBufferedImage(), 0.85f); | |
| byte[] jpegBytes = PdfDocument.encodeJpeg(renderImage(dpi), 0.85f); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
Repository: Stirling-Tools/JPDFium
Length of output: 29286
Use the display-only annotation bake for FULL flattening.
docFlattenAnnotationsbakes no-view markup into page content as well. FULL mode rasterizes each page immediately after this bake. Any no-view annotation therefore appears in the JPEG output, though viewers hide it. CalldocFlattenAnnotationsDisplayinstead. It excludes no-view markup and still bakes visible annotations, which matches its documented use before rasterization.Suggested fix
Committable suggestion
Source: Coding guidelines