Skip to content

fix(pdf): keep attachments when merging and rebuilding - #2085

Open
SeoJCalive wants to merge 1 commit into
mainfrom
fix/965-attachments
Open

SeoJCalive wants to merge 1 commit into
mainfrom
fix/965-attachments

Conversation

@SeoJCalive

@SeoJCalive SeoJCalive commented Dec 5, 2026 •

Copy link
Copy Markdown
Collaborator

What does this change?

Merged PDFs and PDFs rebuilt by the page editor now keep document attachments: the embedded files listed at document level, including their filenames and metadata. Closes #965 by completing its final attachment-preservation item, after push-button page jumps in #1801 and page labels in #1831.

Type of change

  • Bug fix
  • New feature or improvement
  • New format or engine
  • Translation
  • Documentation
  • Build, CI or dependencies

How was it tested?

  • dotnet format --verify-no-changes
  • dotnet test
  • Tried it in the app (what you converted or clicked, and on which OS):

Local verification ran on Linux. The full-test checkbox remains unchecked because the complete App and Engines suites are deferred to PR CI. The app checkbox remains unchecked because the page editor's Save path was exercised through the production PdfPageTools.Save API, without operating the app window. No independent desktop viewer UI was exercised; the independent viewer-engine check used pdf.js APIs.

Local results and when they were recorded:

Check Result Timing
Release solution build Exit 0; 0 errors, 31 existing warnings matching the baseline warning set Before the last three test methods were added
Format verification Exit 0, no changes required After those tests were added
Related PDF tests 640 passed, 0 failed, 0 skipped After those tests were added
Core tests 2,031 passed, 0 failed, 4 Windows mark-of-the-web cases skipped Before those tests were added

The last three test methods added five cases without changing product code. The earlier solution-build and Core results were reused; related PDF tests and format verification were rerun afterward. The 640 related cases comprise 280 structure, 142 paper-fitting, 140 attachment, 60 page-label, and 18 page-tool cases.

Commands for these checks:

dotnet build Filee.slnx --no-restore -c Release -m:1 --disable-build-servers
dotnet format Filee.slnx --verify-no-changes --no-restore --severity warn
dotnet test tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj -c Release \
  --filter 'FullyQualifiedName~PdfMergeAttachmentTests|FullyQualifiedName~PdfMergeStructureTests|FullyQualifiedName~PdfMergePageLabelTests|FullyQualifiedName~PdfMergePaperTests|FullyQualifiedName~PdfPageToolsTests'
dotnet test tests/Filee.Core.Tests/Filee.Core.Tests.csproj -c Release --no-build

Attachment tests cover merge and rebuild preservation, aliases and shared annotation objects, collisions, malformed graphs and non-finite reals, individual limit boundaries, repeated rejected inputs, role-validation caches, cancellation, and encrypted inputs.

Mutation checks covered 48 deliberate changes in 53 runs. Each of the 48 changes made a related test fail at runtime; compile errors and empty test selections were not counted. Source and binary restoration was checked after each run.

End-to-end checks compared the branch with unchanged main at d21b83af03517e15f6567d4b83a696c976546d9d:

  • The actual CLI merge-pdf preset and production page-editor Save API produced 27 outputs across main, branch, and repeat controls: 11 merge and 16 Save outputs. Cases included key collisions, Korean filenames, annotation/document sharing, page removal, reorder/interleave/repeat, Modify rotation, and an openable encrypted source.
  • Poppler pdfdetach -list and numbered -save extraction checked the six inputs and 27 outputs. All 37 extraction occurrences matched the five original payload hashes.
  • pdf.js 6.5.438 on Node 24.16.0 passed 33/33 PDF checks, including document attachments, attachment-annotation payloads, and page text/order. This was an independent engine API check.
  • The three attachment-free cases (merge, reorder Save, and page-removal Save) matched main byte-for-byte after masking timestamps and document IDs. Three main-versus-main repeat controls also matched; this is not a claim of identical unmodified bytes.

Screenshots (UI changes)

No UI changes.

Checklist

  • New UI strings are in all src/Filee.App/Assets/i18n/*.json files
  • New third-party code or binaries are listed in THIRD-PARTY-NOTICES.md
  • The PR does one thing (unrelated changes go in a separate PR)

The first two checklist items are not applicable: this change adds no UI strings, third-party code, or binaries.

Notes for review

Attachments are the last item in the maintainer's remaining-work list. The scope described in my claim comment is to collect each source's /Names /EmbeddedFiles, combine the entries, and resolve key collisions as for named destinations.

Detailed behaviour:

  • Collect attachments once per used source. Keep aliases and share their file specifications and payload objects within that source, including objects already imported with page annotations. Do not deduplicate payloads across different sources.
  • Rename only a colliding name-tree key, using -2, -3, etc.; for example, report.csv becomes report.csv-2. Keep filenames inside the file specification unchanged.
  • When rebuilding, retain all document attachments from any source with at least one output page, even if the page containing an attachment annotation was removed. Keep destinations and attachments together in one output /Names dictionary.
  • After a source opens, omit invalid or over-limit entries individually and as whole entries, without truncating payloads or discarding valid pages. Later smaller entries can still fit; exhausting the shared traversal-work budget stops further attachment collection.
  • Preserve attachments from ordinary encrypted sources that the existing Import path can open without a password prompt, using PDFsharp's decrypted stored bytes. Password-required sources retain the existing error. Entries with explicit /Crypt filters are excluded.
  • Sources containing a stream dictionary with /F still fail while opening in PDFsharp 6.2.4, before entry-level handling. This is the same whole-conversion error as on main: NotImplementedException("File streams are not yet implemented."). A file specification's filename /F is a different, supported field.

I would like your view on these additional choices:

  • Proposed limits: 256 MiB of stored stream bytes, 4 MiB of keys/string/name metadata, 100,000 accepted name-tree entries including aliases, 100,000 charged graph objects, graph depth 64, and 1,000,000 inspected slots/entries of work. Existing per-source name-tree limits remain 100,000 nodes and depth 64. Are these suitable starting defaults, including whole-entry omission when a limit is exceeded? They are proposals, not product policy derived from measured attachment sizes. They bound the added collection/copy work, not PDFsharp's source-opening or existing page-annotation import allocations.
  • Conservative accounting: each file-specification graph is costed once; acceptance charges that cached total. An alias of the same already-accepted specification pays only its entry/key cost. Overlap between different specifications may be charged again, although the output still shares the actual objects. This can reach a limit earlier. Would you keep this conservative rule?
  • Catalog scope: /AF links files to a document or its parts and is used by PDF/A-3; /PageMode selects which side panel a viewer opens first. Would you keep both outside this change? Their existing behaviour remains unchanged: this PR does not reconstruct catalog /AF arrays or change the initial-panel policy. Preserving a file specification's /AFRelationship metadata does not preserve its catalog relationships.
  • Displayed filenames: should /F and /UF remain unchanged when a name-tree key gets a suffix? This preserves the original filename, but viewers may show duplicate display names even though lookup keys are unique.
  • Test naming: is it appropriate to include the cleanup requested in the fix(pdf): keep page labels when merging and rebuilding #1831 review here? The 21 methods with T1_ through T9_ prefixes in PdfMergePageLabelTests.cs now have sentence-style names, with unchanged bodies/data and the same 60 discovered cases.

Keep document attachments from each source in merged and rebuilt PDFs.
Preserve shared objects and rename only colliding attachment keys.

Closes #965
@SeoJCalive
SeoJCalive marked this pull request as ready for review December 5, 2026 16:54

@KnifeLemon KnifeLemon left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

#965의 마지막 항목까지 마무리해 주셔서 고마워요. 검증 표와 질문 정리 덕분에 리뷰하기 편했어요. 2.6.0은 이미 마감이라, 이 PR은 다음 버전에 들어가요.

전체적으로 잘 짜여 있어요. 특히 아래는 확인해 보고 좋다고 생각했어요.

  • 페이지 주석과 함께 이미 들어온 객체는 Imported()로 다시 쓰고, 소스별 Copies로 공유를 유지해서 출력에 소스 객체가 섞이지 않아요.
  • 출력 이름 트리를 바이트 순서로 정렬하고, /Dests와 /EmbeddedFiles를 한 /Names에 함께 넣어요.
  • 순환 참조는 방문 집합이 막고, 작업 예산과 깊이 제한, /Crypt·비정상 실수 거부도 일관돼요.
  • WalkTree가 /Kids를 한꺼번에 쌓지 않고 하나씩 읽게 바뀐 것도 좋아요.

고쳐 주셨으면 하는 것 (1개)

PdfMergeStructure.cs의 이름 충돌 접미사(renamed = key.Bytes + "-" + ...)가 UTF-16 키를 깨뜨려요. 키가 FE FF로 시작하면 "-2"가 1바이트 문자로 붙어서, 두 파일에 모두 한글.txt 키가 있으면 두 번째 키 끝에 -2 대신 U+2D32 같은 엉뚱한 글자가 생겨요. -10부터는 바이트 수가 홀수가 돼서 UTF-16으로 읽을 수도 없어요. 조회 키는 여전히 겹치지 않고, 뷰어는 보통 /UF·/F를 보여 줘서 영향은 작아요. 하지만 한국어 파일 이름이 키인 경우가 흔하니, FE FF로 시작하는 키에는 접미사도 UTF-16BE로 붙여 주세요. 충돌하는 유니코드 키 테스트도 하나 있으면 좋겠어요. 이름 붙은 대상(named destinations)에도 같은 문제가 원래 있는데, 그건 이 PR 범위 밖이니 그대로 두셔도 돼요.

참고 (막는 것 아님)

  • /EF에 있는 키마다 파일 사양에 같은 이름의 파일 이름 문자열을 요구해서, /EF /UF는 있는데 /UF 문자열이 없는 파일은 첨부 전체가 빠져요. 파일 이름이 하나라도 있으면 받아 주는 쪽이 더 너그러울 것 같아요.
  • 제품 코드가 590줄 정도로 꽤 커요. 줄일 수 있는 곳이 있으면 이번에 같이 정리해 주셔도 좋아요.
    • 테스트 전용 훅 네 개(BeforeEmbeddedFileItem, Copy, RoleItem, CostItem).
    • state.Keys와 같은 일을 하는 AttachmentSuffix.Sources.
    • 파일의 다른 부분과 결이 다른 AttachmentIdentityComparer.
  • PdfMergeStructureTests의 theory가 new PdfMergeAttachmentTests(fx).CheckStress/CheckLimit를 부르는데, 두 클래스가 엮이지 않게 첨부 테스트 쪽에 theory를 두는 게 더 깔끔해요.

질문에 대한 답

  1. 제한값: 처음 기본값으로 좋아요. 넘치는 항목을 통째로 빼는 것도 괜찮아요. 지금은 첨부가 전부 빠지니까 그것보다 확실히 나아요.
  2. 보수적인 계산: 그대로 두세요. 단순하고, 틀려도 일찍 멈추는 쪽이라 안전해요.
  3. /AF와 /PageMode: 둘 다 이번 범위 밖에 두세요. 합친 결과가 PDF/A-3이 되는 것도 아니고, 소스가 섞이면 처음 열 패널을 하나로 정할 수 없어요.
  4. 표시 이름: /F와 /UF는 그대로 두세요. 사용자는 파일 이름으로 꺼내고, 이름이 겹쳐 보이는 건 실제로 두 소스에서 왔다는 뜻이에요. 위의 UTF-16 수정만 있으면 키는 고유해요.
  5. 테스트 이름 정리: 이 PR에 포함해도 좋아요. #1831 리뷰에서 부탁드린 내용이고, 본문은 그대로라 문제없어요.

UTF-16 접미사만 고쳐 주시면 승인할게요.

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.

[Feature]: Preserve bookmarks, forms and internal destinations when merging PDFs

2 participants