![]() | Get access, create and manipulate attachments |
This topic contains the following sections:
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.
You can add a text file attachment to a PDF document using PdfAttachment class. The following code example illustrates this.
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); }
Patagames PDF allows you to remove the attachments from the existing document by using Remove method, as shown in the following code example.
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); }
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); }
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); }
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.
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); } }