How to embed files in a PDF document

Manipulate PDF
6/18/2014

This code sample shows how to add embedded files (attachments) to a PDF document.

Embedded documents

PDF specification enables to embed arbitrary files in a PDF document as an attachment. The following code snippet shows how to add such attachments to your document using PDFKit. The resulting files can then be viewed in your PDF application such as Adobe Reader:

addEmbeddedFiles.PNG

C# code sample

1 // A Document created freshly or from an existing PDF file 2 Document doc = ... 3 4 // Create an EmbeddedFile object from a stream 5 using (FileStream stream = File.Open(@"path\to\the\attachment", FileMode.Open)) 6 { 7 // Create an embedded file by from stream and file name to be appear in the PDF document 8 EmbeddedFile ef = new EmbeddedFile(stream, "file name"); 9 10 // set optional properties 11 ef.MimeType = "application/octet-stream"; 12 ef.Description = "description of the attachment"; 13 14 // add the file to the document 15 doc.EmbeddedFiles.Add(ef); 16 }

VB.NET code sample

1 Using inputstream As New FileStream("..\../input.pdf", FileMode.Open, FileAccess.Read) 2 Dim doc As New Document(inputstream) 3 ' Create an EmbeddedFile object from a stream 4 Using stream As FileStream = File.Open("..\../embedded.pdf", FileMode.Open) 5 ' Create an embedded file by from stream and file name to be appear in the PDF document 6 Dim ef As New EmbeddedFile(stream, "file name") 7 8 ' set optional properties 9 ef.MimeType = "application/octet-stream" 10 ef.Description = "description of the attachment" 11 12 ' add the file to the document 13 doc.EmbeddedFiles.Add(ef) 14 15 Using outputstream As New FileStream("..\../output.pdf", FileMode.Create, FileAccess.Write) 16 doc.Write(outputstream) 17 End Using 18 End Using 19 End Using