Skip to content

PDF: write each sheet's page as it is plotted, holding one display list at a time (part of #1068) - #1587

Open
graficaeusebio-cloud wants to merge 2 commits into
storytold:mainfrom
belchiordameao-cmd:pdf-stream-sheets
Open

graficaeusebio-cloud wants to merge 2 commits into
storytold:mainfrom
belchiordameao-cmd:pdf-stream-sheets

Conversation

@graficaeusebio-cloud

@graficaeusebio-cloud graficaeusebio-cloud commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Multi-sheet PDF export kept every sheet's display list alive until the whole document was written. This writes each page right after it is plotted and drops its display list before the next sheet; fonts are tracked incrementally.

Measured on a synthetic 20-sheet / 200k-line drawing (release build, same 32.3 MB output): peak RSS delta 447 MB on main vs 134 MB with this change (~-70%).

Existing cadcraft-io tests pass; pdf_text tests extended.

Part of #1068.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Improvements
    • PDF export processes sheets as they are generated, reducing the amount of page data held in memory.
    • Text rendered as geometry is exported as outlines. If font data exceeds the available limit, export uses a fallback that keeps text rendering consistent across sheets.
    • Eligible fonts used across multiple sheets are embedded once in the PDF.
    • PDF export maintains page metadata and shared layer references across sheets.

@coderabbitai

coderabbitai Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 226a9b99-6c5f-45a0-a1a0-3a5f8536d35c
📥 Commits

Reviewing files that changed from the base of the PR and between 28dacbb and 5c0de15.

📒 Files selected for processing: 4
  • crates/io/src/pdf.rs
  • crates/io/src/pdf/fonts.rs
  • crates/io/tests/pdf_text.rs
  • crates/io/tests/support/ttf.rs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

📝 Walkthrough

PDF generation now writes sheets incrementally and gathers font information across pages. If font gathering exceeds its byte cap, the code replots the sheets and uses a held-sheet fallback. Tests cover streamed and held output, multi-sheet font indexing, and PDF content.

Changes: PDF generation

Layer / File(s) Summary
Cross-sheet font gathering
crates/io/src/pdf/fonts.rs
Gather accumulates glyphs across sheets and creates per-sheet font plans. It builds fonts only when the final mapping matches those plans and the byte cap allows the subsets.
Stateful PDF writer
crates/io/src/pdf.rs
Writer writes page content as pages are produced and retains page metadata. Writer::finish writes fonts, completes page dictionaries and the page tree, and assembles the PDF.
Incremental page generation and fallback
crates/io/src/pdf.rs, crates/io/tests/pdf_text.rs, crates/io/tests/support/ttf.rs
pdf_items writes sheets through Writer and gathers fonts as it proceeds. If gathering exceeds the cap, it replots and holds the sheets before collecting fonts. Tests cover streamed and held output, multi-sheet font indexing, and a shared test font builder.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant pdf_items
  participant Gather
  participant Writer
  participant Fonts
  pdf_items->>Gather: add each sheet display list
  pdf_items->>Writer: write each plotted page
  pdf_items->>Gather: finish font gathering
  Gather-->>pdf_items: return fonts or no matching plan
  pdf_items->>Fonts: collect fonts after replotted sheets
  pdf_items->>Writer: finish PDF with fonts
Loading

Suggested reviewers: vangel76

Merge Risk: ⚪ Minimal · up to 5c0de

No actionable issue remains identified for the incremental PDF export change; it is ready to merge after normal checks.

Security architecture risk: 🔵 Low · up to 5c0de

The reviewed flow preserves complete-output publication and validates font mappings before returning a PDF. No introduced security concern was established. Memory use is reduced on the normal path, but fallback still holds every plotted sheet, and total export memory remains unbounded by the font-data limit.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — Caller-supplied drawing content and export options influence rendering, font subsetting, and allocations within the exporting process. The inspected change adds no external publication step or shared mutable export state. Deployment evidence does not establish whether resource exhaustion could affect other users sharing that process.

Trust Boundaries and Controls

  • observed — The new planning probe uses the existing subset function, which checks embedding permission and rejects unsupported or malformed fonts. Final construction still enforces font-count and aggregate-data limits, with non-embedded text represented as outlines.

Resilience and Maintainability Implications

  • observed — A font-plan mismatch discards the buffered first attempt and replots all requested sheets into a fresh held-page assembly. Plotting errors return without partial output. Fallback preserves the base's all-sheets memory behavior rather than providing a hard memory bound, and adds another rendering pass.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 79.31% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 29 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly describes the main change: writing each PDF sheet during plotting while retaining only one display list at a time. It is specific and related to the changeset.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@FredApps FredApps left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea is sound, and I like the fallback: if the fonts at the end differ from the plan the pages were written with, it plots again. The measured gain is clear (447 MB → 134 MB). Two gaps in the tests keep me from approving a refactor of PDF output.

  • Nothing shows the output is unchanged. The new test sheets_written_one_by_one_share_the_fonts_of_the_file (crates/io/tests/pdf_text.rs) checks one font file, font indices and the text operators for one drawing. The old path (assemble over all pages) is still in the code. A test that builds a multi-sheet drawing, plots it both ways and compares the bytes would pin that the incremental writer gives the same file, including layers, page labels and annotations, which Writer::page now writes per page.
  • The fallback is not run by any test. Gather::add plans only against MAX_FONTS and an empty subset (fonts.rs:120), while Fonts::build also applies MAX_FONT_BYTES (line 67) and subsets with the real glyphs. A drawing that goes over the 64 MB font data cap, or whose subset fails, reaches the None branch in pdf_items, which re-plots and calls assemble. That branch is the one place the output could diverge, and it has no test. A small test that forces it (for example with a face whose subset fails once it has glyphs) would cover it.

With those two I'd approve. Hosted CI: only CodeRabbit has run on this head, so I would also ask for a local run of the cadcraft-io tests.

…cap fallback

- tests/support/ttf.rs: the synthetic TrueType font, shared by tests/pdf_text.rs and the
  unit tests of src/pdf.rs.
- pdf_items splits into write_items (pages written as plotted) and write_held (every
  sheet held, then assemble); the cap on font data is a parameter so a test can reach it.
- A two-sheet drawing with real text, layers shared across pages (one off), page labels
  and link annotations gives the same bytes both ways, compressed or not.
- With the font data cap at 1 byte the plan made while writing does not hold, and the
  output is the held file with the text drawn as outlines.
@belchiordameao-cmd

Copy link
Copy Markdown

Thanks for the review, @FredApps. #2029 has since replaced the PDF writer with craft-pdf's krilla writer, so this branch no longer applies as it stands. I'll redo the page-by-page writing on top of the new writer and carry over the two tests you asked for: pages written as they are plotted match the file assembled from every sheet, and fonts over the data cap are planned as text and then plotted again as outlines.

(Written by Claude Code, an AI agent, on behalf of belchiordameao-cmd.)

@belchiordameao-cmd

belchiordameao-cmd commented Oct 24, 2026 •

Copy link
Copy Markdown

Correction to my comment above: having read #2029 properly, there is nothing left to redo here. In main, write_pdf (crates/io/src/pdf.rs:422-467) already builds each sheet's display list, writes it as its page and drops it before the next, and Fonts (crates/io/src/pdf/fonts.rs:28-63) decides each face when its first glyph is written, applying the font-count and font-data caps on the spot. That was the goal of this PR.

The two tests you asked for, @FredApps, pinned this PR's mechanism: the incremental writer against the assemble path, and the re-plot when the final fonts differ from the plan. Neither exists in main: there is one writing path and no font plan to diverge from. The one retry left (pdf.rs:377-380: write again with text as outlines when the writer fails on a font) is #2029's own.

So this PR is superseded by #2029 and can be closed. Thanks for the review.

(Written by Claude Code, an AI agent, on behalf of belchiordameao-cmd.)

@FredApps FredApps left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 5c0de15 (my last review was on 28dacbb).

Earlier findings: both fixed in this head.

  • Same output both ways: pages_written_as_plotted_match_the_file_assembled_from_every_sheet in crates/io/src/pdf.rs plots a two-sheet drawing with real text, shared and off layers, page labels and links through write_items and write_held, compressed and not, and compares the bytes.
  • Fallback is tested: fonts_over_the_data_cap_are_planned_as_text_then_plotted_again_as_outlines makes the font-data cap a parameter, sets it to 1 byte, checks that the plan does not hold, and checks that the result is the held file with the text drawn as outlines.

Thanks, that is what I asked for.

Still open: main already does this, and the PR conflicts in all three files.
The day after this commit, #2029 (merged 24 Oct, "PDF: plot with craft-pdf's krilla writer") replaced the hand-written PDF writer. Writer, assemble, Gather, the hand-written subsetter and the 64 MB MAX_FONT_BYTES this PR changes are gone from main. On main (11d66cc), write_pdf in crates/io/src/pdf.rs (lines 429-480) builds each sheet's display list, writes it as its page and drops it before the next sheet (line 464 loop, write_page at line 474). Fonts are now picked one face at a time as glyphs are written (Fonts::font in crates/io/src/pdf/fonts.rs), and krilla subsets them when the file is finished. So no plan is made early and no re-plot is needed. The only retry left is the text-as-outlines one for a font krilla refuses. #2029's description lists this PR as "Covered: pages are written one at a time".

git merge-tree with current main conflicts in crates/io/src/pdf.rs, crates/io/src/pdf/fonts.rs and crates/io/tests/pdf_text.rs, and GitHub reports the PR as CONFLICTING. A rebase would remove the whole change, because the code it edits no longer exists. The new tests can't carry over either: they compare two writer paths that main no longer has.

I suggest closing this PR as superseded by #2029. #1068 stays open for the rest of the plot memory work (PNG and Plot Preview). If you think the PDF path on main still holds more than one sheet's display list somewhere, please open a new PR against the krilla writer with a test that shows it.

CI: only CodeRabbit has reported on this head. The CI and SonarCloud runs are waiting for approval, and I have not approved them because the PR conflicts with main.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants