Add Attachments to PDF in C#

How to Add Attachments in PDF programmatically with C#

How to Manage Attachments Using .NET Library

In order to add Attachments in PDF file, we’ll use Aspose.PDF for .NET API which is a feature-rich, powerful and easy to use document manipulation API for net platform. Open NuGet package manager, search for Aspose.PDF and install. You may also use the following command from the Package Manager Console.

Package Manager Console

PM > Install-Package Aspose.PDF

Add Attachments in PDF File via C#


You need Aspose.PDF for .NET to try the code in your environment.

  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
  6. Save the PDF file.

Adding Attachment to PDF document

var inputFile = Path.Combine(dataDir, "AddAttachment.pdf");
var attachmentFile = Path.Combine(dataDir, "test.txt");
var outputFile = Path.Combine(dataDir, "AddAttachment_out.pdf");
var pdfDocument = new Aspose.Pdf.Document(inputFile);

var fileSpecification =
    new Aspose.Pdf.FileSpecification(attachmentFile, "Sample text file");

pdfDocument.EmbeddedFiles.Add(fileSpecification);
pdfDocument.Save(outputFile);