Attachments in PDF document

A PDF can carry embedded file attachments. Watermarker.get_content() returns a PdfContent whose attachments collection lets you add, extract, and remove them — and you can even open an attachment in its own Watermarker to watermark it.

Add an attachment

The example embeds a Word document into the PDF as an attachment.

from groupdocs.watermark import Watermarker
from groupdocs.watermark.options.pdf import PdfLoadOptions

def add_attachment():
    with Watermarker("./document.pdf", PdfLoadOptions()) as watermarker:
        content = watermarker.get_content()
        with open("./sample.docx", "rb") as f:
            data = f.read()
        content.attachments.add(data, "sample.docx", "Attached Word document")
        watermarker.save("./output.pdf")

if __name__ == "__main__":
    add_attachment()

document.pdf and sample.docx are the sample files used in this example. Download document.pdf and sample.docx.

Binary file (PDF, 512 KB)

Download full output

Extract attachments

Iterate the attachments collection to read each attachment’s metadata and content.

from groupdocs.watermark import Watermarker
from groupdocs.watermark.options.pdf import PdfLoadOptions

with Watermarker("./document.pdf", PdfLoadOptions()) as watermarker:
    content = watermarker.get_content()
    print("Attachments:", len(content.attachments))
    for attachment in content.attachments:
        info = attachment.get_document_info()
        print(f"- name={attachment.name!r} type={info.file_type} size={len(attachment.content)} bytes")
        # Save the attachment's bytes to disk
        with open(f"./{attachment.name}", "wb") as f:
            f.write(attachment.content)

For the example PDF produced above, this prints:

Attachments: 1
- name='sample.docx' type=Docx (.docx) - WordProcessing size=14752 bytes

Use content.attachments.remove_at(index) or content.attachments.remove(attachment) to delete an attachment, and open an attachment in its own Watermarker (from its content bytes) to add a watermark to the attached document itself.

Close
Loading

Analyzing your prompt, please hold on...

An error occurred while retrieving the results. Please refresh the page and try again.