Adding Attachment to a PDF document using Aspose.PDF for .NET

Contents
[ ]

Attachments can contain a wide variety of information and can be of a variety of file types. This article explains how to add an attachment to a PDF file.

  1. Create a new C# project.
  2. Add a reference to Aspose.PDF DLL.
  3. Create a Document object.
  4. Create a FileSpecification object with the file you are adding, and file description.
  5. Add the FileSpecification object to the Document object’s EmbeddedFiles collection, with the collection’s Add method.

The EmbeddedFiles collection contains all the attachments in the PDF file. The following code snippet shows you how to add an attachment in a PDF document.

// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Attachments();

// Open document
Document pdfDocument = new Document(dataDir + "AddAttachment.pdf");

// Setup new file to be added as attachment
FileSpecification fileSpecification = new FileSpecification(dataDir + "test.txt", "Sample text file");

// Add attachment to document's attachment collection
pdfDocument.EmbeddedFiles.Add(fileSpecification);

dataDir = dataDir + "AddAttachment_out.pdf";

// Save new output
pdfDocument.Save(dataDir);