阅读文本 / Reading text
This paper uses synthetic samples to demonstrate the processing method. The code has been verified using examples in an isolated environment; this does not guarantee effectiveness for all real files or products. Before processing important files, please retain the original copies and verify them against the boundaries and acceptance criteria outlined in this document.
Which problem does this paper address first
attachments with the same name can correspond to multiple pieces of content. Do not use local sequence numbers or cleaned-up names as global keys; instead, assign independent IDs according to the extraction order, retaining the original names as metadata, without writing the attachments to disk or executing them.
self-contained synthetic example
dependencies are listed in the import section. The code constructs inputs in memory; runtime logs are provided separately and do not constitute a guarantee for all real-world files.
from io import BytesIO
from pypdf import PdfReader, PdfWriter
writer = PdfWriter()
writer.add_blank_page(width=200, height=200)
writer.add_attachment("data.csv", b"row-one")
writer.add_attachment("data.csv", b"row-two")
writer.add_attachment("../secret.txt", b"synthetic secret")
out = BytesIO()
writer.write(out)
out.seek(0)
reader = PdfReader(out)
records = []
for name, contents in reader.attachments.items():
for content in contents:
records.append({"id": len(records), "source_name": name, "bytes": content})
assert len(records) == 3
assert len({r["id"] for r in records}) == 3
assert {r["bytes"] for r in records if r["source_name"] == "data.csv"} == {b"row-one", b"row-two"}
assert any(r["source_name"] == "../secret.txt" for r in records)
Why does your attachment extraction script silently drop files
When processing PDFs containing embedded files, the most insidious failure is not an error message, but rather the disappearance of files after what appears to be a “successful” execution. When you iterate through
reader.attachments
And when writing directly to disk using the original name, if the PDF embeds two entries named
report.xlsx
the file, which will directly overwrite the former; if the filename contains
../
or system-reserved characters may cause write operations to fail or even trigger security risks. The official pypdf documentation explicitly warns that attachment names can contain any characters, and attachments with the same name are stored as a list. This means that any uncleaned batch extraction logic is unreliable when encountering non-standard PDFs.
synthesis example: correct output and boundary input handling
To verify the robustness of the extraction logic, we need to construct a controlled synthetic sample rather than relying on production files of unknown origin. Suppose we build a PDF containing three attachments: the first is a normal file
data.csv
, the second is named the same as the first
data.csv
(content differs), the third one is a filename containing path-traversal characteristics
..\secret.txt
。
Python implementation of secure extraction and filename sanitization
This code is provided solely for logical demonstration and does not constitute a comprehensive coverage of all pypdf’s attachment features. In actual production environments, additional considerations are required, such as streaming large files and handling encoding exceptions.
Acceptance Criteria and Manual Review Boundary
automated extraction cannot replace manual verification prior to delivery. The table below lists common anomalies and the corresponding handling decisions, distinguishing between scenarios that can be resolved by code and those requiring human intervention:
Observation of the phenomenon
automatically processes
manual review
Multiple attachments with the same name
adds a sequential prefix, preserving all content
verifies whether it is a version iteration or an erroneous embedding of
filename contains the path separator
strips the directory structure, retaining only the filename
checks whether the intent is to conceal a malicious payload
The attached content is empty or extremely small
Log recording, file still saved
determines whether it is a placeholder or corrupted
filename contains garbled characters or non-printable characters
Replace with underscores, preserving the indices.
traces back to the original PDF metadata to confirm semantics
Attachment type does not match the file extension
either performs content sniffing or preserves the original
is determined by domain experts to have the purpose
Note: This table applies to validation at the code‑demonstration level. End-to-end results must also be evaluated in the context of the business, as, for example, missing contract attachments may be more serious than file‑name errors. When the number of attachments exceeds 20 or when encryption or digital signatures are involved, the automated process should be paused and handed over to a dedicated reviewer.
References and Next Steps
pypdf Handle Attachments Official Documentation
PDF 2.0 Specification Section 14.13 (Associated Files)
Next step: Add synthetic attachment test cases to your CI pipeline; run the cleansing and extraction script on a sample of historical delivery documents to establish an attachment integrity baseline; if systemic losses are detected, prioritize investigating naming conflicts over network or permission issues.
uses this checklist for document translation
File splitting, encryption, or attachment processing are part of delivery preparation; translation cannot replace these checks. Retain the original documents and the processing checklist, then assess the translated manuscript’s page order, hyperlinks, and content integrity.
OmniDoc (Product Entry)
provides an entry point for translating multi-format documents, and the official website highlights its OCR, terminology database, and bilingual comparison features. For teams that wish to start processing directly from files, this is a path worth evaluating using real-world samples. Please use de-identified files with upload permissions and verify the results against the checklist provided in this document; we do not claim that OmniDoc utilizes the open-source libraries or internal algorithms referenced herein, nor do we substitute examples for formal product performance testing.
- 1 -
Updated 2026-10-09