You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Subset already-embedded fonts during PDF compression - #253
Adds opt-in subsetting of already-embedded TrueType and OpenType fonts to PdfCompressor while keeping default compression behavior unchanged (subsetFonts=false). Subsetting verifies glyph mappings and advance widths before mutating any font stream and skips signed PDFs and shared descriptors.
Changed:
Export jpdfium_qpdf_subset_fonts in jpdfium.h and jpdfium_qpdf.cpp and wire QpdfLib FFM bindings.
Thread subsetFonts opt-in configuration through CompressOptions, CompressPreset, PdfCompressor, and PdfOptimizer.
Skip signed documents, shared font descriptors, and unknown encodings; verify subset outputs in PdfCompressorTest and PdfFontEmbedderRoundTripTest.
Added an option to reduce PDF file sizes by subsetting embedded fonts during compression. Font subsetting can be controlled through compression presets and optimizer options, and is applied only when supported and safe for the document.
Bug Fixes
Font audits now continue past pages that cannot be opened, and font checks handle empty PDF input without attempting to open a document.
Font embedding now handles additional font formats and matching cases more reliably.
Compression options now control embedded-font subsetting through a native qpdf operation. Font embedding and mapping behavior, font auditing, and round-trip validation also change.
Changes: PDF Font Processing
Layer / File(s)
Summary
Subsetting options and API contract jpdfium/src/main/java/stirling/software/jpdfium/doc/CompressOptions.java, .../CompressPreset.java, .../PdfOptimizer.java, native/bridge/include/jpdfium.h
Compression options and presets expose font subsetting. The Java optimizer and native header define the flag and operation contract.
Font selection, mapping, and auditing jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java, .../PdfFontAuditor.java, jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfFontEmbedderRoundTripTest.java, native/bridge/src/jpdfium_qpdf.cpp
Java font embedding selects embeddable matches and normalizes font programs. Native font handling updates cmap, symbolic-font, and width processing. Auditing and round-trip checks change their handling of empty input, page-open failures, and font comparisons.
Native font subsetting native/bridge/src/jpdfium_qpdf.cpp
The native qpdf path selects eligible embedded fonts, verifies and applies smaller subsets, and updates font data. The exported operation returns rewritten output and a subset count.
Compression integration and subset result jpdfium/src/main/java/stirling/software/jpdfium/panama/QpdfLib.java, jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfCompressor.java, jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfCompressorTest.java
QpdfLib binds the native operation. PdfCompressor invokes it under configured conditions and adopts a smaller result. A test checks the subset count, output size, and extracted text.
Possibly related PRs
Stirling-Tools/JPDFium#233: It uses PdfFontEmbedder.programsFor and native font embedding behavior that this PR also changes.
Change: Feature
Merge Risk: High · previous review d40e6
Font subsetting is on by default in the builder and presets, and it can remove glyphs that pages still draw, so text can render blank after compression. A subsetting failure can also abort the whole compress call. Several of these defects, and the weakened tests that should catch them, need fixing before merge.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names the main change: opt-in subsetting of already-embedded fonts during PDF compression. The raw summary shows this is the core of the changeset, touching PdfCompressor, CompressOptions, C…
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description check
The description states the PR adds opt-in font subsetting to PdfCompressor with subsetFonts=false by default, and lists the changed areas (QpdfLib FFM wiring, CompressOptions/CompressPreset/PdfOptimiz…
Full details: Title check
Explanation
The title names the main change: opt-in subsetting of already-embedded fonts during PDF compression. The raw summary shows this is the core of the changeset, touching PdfCompressor, CompressOptions, CompressPreset, QpdfLib, and the native bridge.
Full details: Description check
Explanation
The description states the PR adds opt-in font subsetting to PdfCompressor with subsetFonts=false by default, and lists the changed areas (QpdfLib FFM wiring, CompressOptions/CompressPreset/PdfOptimizer options, tests) and safety checks (signed PDFs, shared descriptors, unknown encodings). It follows the template sections and most checklist items are ticked. Two gaps: the CHANGELOG item is unchecked, and the description does not link an issue ('Closes #(issue number)' is missing). Also, the raw summary shows CompressPreset sets subsetFonts=true for presets, which conflicts with the described default of false for compression behavior, and the description's test claim ('./gradlew :jpdfium:integrationTest passes') is not matched by the ./gradlew test checkbox being left unticked.
Resolution
Consider the following before merge: (1) Tick or resolve the unchecked CHANGELOG.md item, or explain why no user-facing entry is needed. (2) Add the linked issue reference in the 'Closes #(issue number)' line, or remove that line if no issue exists. (3) Clarify in the description whether CompressPreset presets (WEB, SCREEN, PRINT, LOSSLESS, MAXIMUM) enable subsetFonts=true, since this differs from the stated default of subsetFonts=false and may change default compression behavior for preset users. (4) Confirm whether ./gradlew test was run, since the checklist lists only integrationTest.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 16
Additional comments: 1
native/bridge/src/jpdfium_qpdf.cpp-2806-2810: 1
2806-2810: Minor · Stability & Availability · Quick win
Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.
Isolate failures per font.
subsetEmbeddedFontResource has no exception guard. Malformed objects can make qpdf throw from getKey, getArrayItem or newStream. One damaged font then aborts the whole pass. jpdfium_qpdf_subset_fonts returns JPDFIUM_ERR_NATIVE in that case. In the applyDocumentOptions path, the same exception fails an optimize that would otherwise succeed.
Catch std::exception around each font and skip that font. The per-font operations replace keys only after verification, so a skipped font keeps its original program.
Proposed fix
for (auto& font : uniqueFonts) {
- if (subsetEmbeddedFontResource(qpdf, lib, font, descriptorUseCount, streamUseCount))- ++subsetCount;+ try {+ if (subsetEmbeddedFontResource(qpdf, lib, font, descriptorUseCount, streamUseCount))+ ++subsetCount;+ } catch (std::exception const&) {+ // Leave this font unchanged.+ }
}
Files not fully reviewed because they exceed a per-file size limit: 1
native/bridge/src/adobe_glyph_names.inc
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
Review details
Context from checks skipped due to timeout: 31
GitHub Check: Native bridge libFuzzer (ASan/UBSan, real PDFium)
GitHub Check: Samples E2E Suite (All 88 Feature Samples)
GitHub Check: JMH Benchmarks (advisory)
GitHub Check: Unit & Integration E2E Tests (Linux x64)
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
⚠️ Outside diff range comments (1)
Minor · Reject empty PDF input instead of reporting success. · PdfFontEmbedder.java:228-230
jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java:228-230 Minor · Functional Correctness · Quick win
Reject empty PDF input instead of reporting success.
If pdf is null or empty, embedMissing now returns a result with no unresolved fonts and no valid PDF. A caller cannot distinguish that result from a completed no-op by inspecting its status lists. Reject the input, as embed(byte[], Map) does, before returning a result. As per coding guidelines: “Preserve stable public behavior. Flag incompatible ownership, exception, thread-access, output-format, or save semantics.”
877-878: Major · Data Integrity & Integration · Heavy lift
Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.
Update the whole-font checksum after changing cmap.
When sanitization changes a standalone TrueType font, the code updates the cmap directory checksum but leaves head.checkSumAdjustment unchanged. The returned font therefore fails the OpenType whole-font checksum requirement; a reader that validates it can reject the embedded program. Recalculate the adjustment after the table edit, and add a regression that validates the resulting font. (learn.microsoft.com) As per coding guidelines: “Validate semantic preservation through reopen, independent structural checks, and representative rendering/text properties.”
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
Review details
Additional context used
Code guidelines: 1
.github/CODERABBIT_REVIEW.md — configured
Path-based instructions: 4
Apply the native ownership, C ABI, C++23, engine integration, memory, and SIMD rules from .github/CODERABBIT_REVIEW.md.
Learnt from: CR
Repo: Stirling-Tools/JPDFium PR: 0
File: .github/CODERABBIT_REVIEW.md:0-0
Timestamp: 2026-10-31T10:47:27.879Z
Learning: Source excerpt:
# JPDFium review standards
## Java 25 style
- Do not catch `Throwable` merely to swallow or log it. Catch broadly only at a justified boundary or cleanup guard, preserving fatal-error policy and cleanup ordering.
148-148: Capability reporting still accepts the no-qpdf stub.
The supplied no-qpdf export resolves this handle but always returns -1. This method reports support, and subsetFonts then throws. The earlier capability finding remains applicable.
LOSSLESS enables subsetting, and this condition permits replacement despite preserve == true. Use the preservation guard and retain a regression with subsetting explicitly enabled. This repeats the earlier finding.
360-360: Subsetting failures still abort compression.
QpdfLib.subsetFonts throws for native failures, and this call has no recovery branch. The previous image-pass recovery and subsequent size fallback do not handle this exception. This repeats the earlier optional-pass failure finding.
361-363: Data Integrity & Integration
The native glyph collector scans annotation appearance streams (/AP with /N, /R, and /D). Both simple-font and CID-font subsetting use this collector, so the reported glyph-omission path does not occur.
scanContentStream handles Tf, but ignores this change. For /F1 12 Tf (A) Tj /F2 12 Tf /GS1 gs (B) Tj, where /GS1 selects /F1, the scan records only A for /F1. The new subset pass can then remove the independent B glyph while scan.complete remains true.
Resolve ExtGState /Font during scanning, or mark the scan incomplete when this entry occurs. Add a regression that checks the rendered B after subsetting.
Major · Reject unsupported encodings before destructive subsetting. · jpdfium_qpdf.cpp:1375-1376
native/bridge/src/jpdfium_qpdf.cpp:1375-1376 Major · Data Integrity & Integration · Quick win
Reject unsupported encodings before destructive subsetting.
MacExpertEncoding has mappings distinct from the three encodings collected by the new subset path. (opensource.adobe.com)
parseEncoding silently interprets it as Standard. Consequently, subsetEmbeddedSimpleFont can retain the wrong glyphs, and subsetKeepsSimpleGlyphs validates the same wrong interpretation. A used expert glyph outside the collected glyph set can disappear from the output.
Reject /MacExpertEncoding, including dictionary /BaseEncoding, before subsetting. The embedding path already has this guard at Line 2954. Reject other unsupported encodings rather than defaulting them to Standard.
Reviewing files that changed from the base of the PR and between eb16d3b and d40e6e1.
Files selected for processing: 1
native/bridge/src/jpdfium_qpdf.cpp
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description of Changes
Adds opt-in subsetting of already-embedded TrueType and OpenType fonts to
PdfCompressorwhile keeping default compression behavior unchanged (subsetFonts=false). Subsetting verifies glyph mappings and advance widths before mutating any font stream and skips signed PDFs and shared descriptors.Changed:
jpdfium_qpdf_subset_fontsinjpdfium.handjpdfium_qpdf.cppand wireQpdfLibFFM bindings.subsetFontsopt-in configuration throughCompressOptions,CompressPreset,PdfCompressor, andPdfOptimizer.PdfCompressorTestandPdfFontEmbedderRoundTripTest.Checklist
General
## [Unreleased]inCHANGELOG.mdLibrary changes
.github/workflows/compatibility.ymlexcludes the break with a reasondocs/installation.md, and the POMsNative or FFM changes
bash native/build-real.sh)./gradlew :jpdfium:integrationTestnative/bridge/include/jpdfium.hand the ABI notes for any ABI changeTesting
./gradlew :jpdfium:integrationTestpasses