PDF Attachments: Don't Miss Embedded Files Before Delivery

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, assi

Anyone who extracts or forwards PDFs with embedded files can lose attachments without seeing an error. This guide shows why that happens and how to keep every attachment, even when names clash or look suspicious.

The method below uses synthetic samples. Keep the original copies and check your output against the acceptance criteria before you process important documents.

You will learn how same-name attachments get overwritten, how to assign each attachment a stable ID, and which anomalies you can handle in code and which need a person to review them.

How do you keep every attachment before delivery? The short answer

Give every extracted attachment its own ID in extraction order, keep the original name as metadata, and send unusual cases to manual review.

Your situationWhat to doWhy
Two attachments share a nameAssign each one an independent ID in extraction order, and keep the original name as metadataSame-name attachments are stored as a list, and writing them by name overwrites earlier files
The filename contains ../ or reserved charactersStrip the directory structure and keep only the filenameSuch names can make writes fail or create security risks
The attachment is empty or extremely smallLog it and keep the file, then check whether it is a placeholder or corruptedAutomation can record the problem, but only a person can judge its purpose
The attachment type does not match its extensionSniff the content or keep the original, then have a domain expert decideExtension and content can disagree for legitimate reasons
There are more than 20 attachments, or encryption or digital signatures are involvedPause the automated process and hand it to a dedicated reviewerAutomated extraction cannot replace manual verification before delivery

Why does your attachment extraction script silently drop files?

The most dangerous failure in PDF attachment handling does not raise an error. Instead, files disappear after a run that looks successful.

This happens when you iterate through reader.attachments and write each file to disk under its original name:

  • Same-name collisions: If the PDF embeds two entries called report.xlsx, the second write overwrites the first.
  • Unsafe filenames: A name containing ../ or system-reserved characters can make the write fail or create a security risk.
  • Unreliable batch logic: The official pypdf documentation warns that attachment names can contain any characters, and that attachments with the same name are stored as a list. Batch extraction that does not account for this is unreliable with non-standard PDFs.

How should you assign keys to attachments?

Do not use local sequence numbers or cleaned-up names as global keys. Instead:

  1. Assign each attachment an independent ID based on the extraction order.
  2. Keep the original name as metadata.
  3. Do not write attachments to disk or run them during the inspection step.

How do you test extraction with a synthetic sample?

To check that your extraction logic is robust, build a controlled sample rather than relying on production files of unknown origin.

For example, build a PDF with three attachments:

  • A normal file, data.csv.
  • A second file with the same name, data.csv, but different content.
  • A file whose name contains path-traversal characters, ..\secret.txt.

The dependencies are listed in the import section. The code builds its inputs in memory.

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)

How does the secure extraction code work?

This code is for demonstrating the logic only. It does not cover every attachment feature of pypdf. In a production environment, you also need to consider:

  • Streaming large files
  • Handling encoding exceptions

What are the acceptance criteria and the manual review boundary?

Automated extraction cannot replace manual verification before delivery. The table below lists common anomalies and how to handle each one. It separates cases that code can resolve from cases that need a person.

Observation of the phenomenonautomatically processesmanual review
Multiple attachments with the same nameadds a sequential prefix, preserving all contentverifies whether it is a version iteration or an erroneous embedding of
filename contains the path separatorstrips the directory structure, retaining only the filenamechecks whether the intent is to conceal a malicious payload
The attached content is empty or extremely smallLog recording, file still saveddetermines whether it is a placeholder or corrupted
filename contains garbled characters or non-printable charactersReplace with underscores, preserving the indices.traces back to the original PDF metadata to confirm semantics
Attachment type does not match the file extensioneither performs content sniffing or preserves the originalis determined by domain experts to have the purpose

Keep these limits in mind:

  • This table applies to validation at the code-demonstration level. Check end-to-end results against your business needs. For example, a missing contract attachment may matter more than a file-name error.
  • When the number of attachments exceeds 20, or when encryption or digital signatures are involved, pause the automated process and hand it to a dedicated reviewer.

How does this checklist apply to document translation?

File splitting, encryption, and attachment processing are part of delivery preparation, and translation cannot replace these checks. Keep the original documents and your processing checklist. Then check the translated document's page order, hyperlinks, and content integrity.

OmniDoc translates PDF, Word, PowerPoint and Excel files: scanned pages are recognized first, table cells are translated one by one so tables keep their rows and columns, and a PDF comes back as both a bilingual and a translation-only file. Paid translation adds a glossary and context translation. Use real files that you have permission to upload, and check the results against the checklist in this guide.

References and next steps

Next steps:

  1. Add synthetic attachment test cases to your CI pipeline.
  2. Run the cleansing and extraction script on a sample of historical delivery documents to set an attachment integrity baseline.
  3. If you find systematic losses, investigate naming conflicts before you look at network or permission issues.

🎯 Which approach fits you?

If you process PDFs in batches

Use independent IDs and keep original names as metadata, so same-name attachments never overwrite each other.

If you handle PDFs from unknown sources

Treat unusual filenames and suspicious content as manual review items, and never run attachments during inspection.

If you prepare translated deliverables

Run the attachment checks first, then compare the translated document's page order, hyperlinks, and content against the originals.

❓ FAQ

1. Why does my script lose attachments with the same name?

Same-name attachments are stored as a list, so writing each one under its original name overwrites the previous file.

2. Should I use the original filenames as keys?

No. Assign each attachment an independent ID in extraction order, and keep the original name as metadata.

3. Can automation handle attachments before delivery on its own?

No. Automated extraction cannot replace manual verification before delivery. Pause the process and involve a reviewer when there are more than 20 attachments or when encryption or digital signatures are involved.

4. Does translation replace these attachment checks?

No. Keep the originals and your checklist, then check the translated document's page order, hyperlinks, and content integrity.

📝 Summary

Same-name and unsafe attachments are the most common reasons files go missing before delivery. Assign stable IDs, keep original names as metadata, and route unusual cases to a person. Test the process with synthetic samples before you rely on it.

Try it now: upload a document and get it translated with the layout intact

Updated 2026-11-29