Click or drag to resize

Get access, create and manipulate attachments

This topic contains the following sections:

Overview

The attachments are only referred to attachments of documents rather than file attachment annotation, which allow whole files to be encapsulated in a document, much like email attachments. PDF SDK provides applications APIs to access attachments such as loading attachments, getting attachments, inserting/removing attachments, and accessing properties of attachments.

Open in full size

Attachments
Adding attachment to a PDF document

You can add a text file attachment to a PDF document using PdfAttachment class. The following code example illustrates this.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{

    string fileName = "sample.txt";
    byte[] fileContent = System.IO.File.ReadAllBytes(@"sample.txt");
    string modificationDate = System.IO.File.GetLastWriteTime(@"sample.txt").ToString();

    var attachment = new PdfAttachment(doc, fileName, fileContent);
    attachment.FileSpecification.EmbeddedFile.ModificationDate = modificationDate;
    attachment.FileSpecification.Description = "File description";

    doc.Attachments.Add(attachment);

    //Save a copy of PDF document
    doc.Save("sample_modified.pdf", SaveFlags.NoIncremental);
}
Removing attachment from an existing PDF

Patagames PDF allows you to remove the attachments from the existing document by using Remove method, as shown in the following code example.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{

    PdfAttachment attachment = doc.Attachments[0];
    doc.Attachments.Remove(attachment);

    //Save a copy of PDF document
    doc.Save("sample_modified.pdf", SaveFlags.NoIncremental);
}
C#
using (var doc = PdfDocument.Load("sample.pdf"))
{

    int attachmentIndex = 0;
    doc.Attachments.RemoveAt(attachmentIndex);

    //Save a copy of PDF document
    doc.Save("sample_modified.pdf", SaveFlags.NoIncremental);
}
C#
using (var doc = PdfDocument.Load("sample.pdf"))
{

    PdfAttachment attachment = doc.Attachments["sample.txt"];
    if(attachment!= null)
        doc.Attachments.Remove(attachment);

    //Save a copy of PDF document
    doc.Save("sample_modified.pdf", SaveFlags.NoIncremental);
}
Extracting and saving an attachment to the disk

Patagames PDF provides support for extracting the attachments and saving them to the disk. The following code example explains how to extract and save an attachment.

C#
using (var doc = PdfDocument.Load("sample.pdf"))
{
    foreach(var attachment in doc.Attachments)
    {
        string name = attachment.Name;
        byte[] content = attachment.Content;

        string path = System.IO.Path.Combine(@"your_path", name);
        System.IO.File.WriteAllBytes(path, content);
    }
}
See Also