How to embed files in a PDF document

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

// A Document created freshly or from an existing PDF file
Document doc = ...

// Create an EmbeddedFile object from a stream
using (FileStream stream = File.Open(@"path\to\the\attachment", FileMode.Open))
{
   // Create an embedded file by from stream and file name to be appear in the PDF document 
   EmbeddedFile ef = new EmbeddedFile(stream, "file name"); 

   // set optional properties
   ef.MimeType = "application/octet-stream";
   ef.Description = "description of the attachment";

   // add the file to the document
   doc.EmbeddedFiles.Add(ef);
}
Using inputstream As New FileStream("..\../input.pdf", FileMode.Open, FileAccess.Read)
    Dim doc As New Document(inputstream)
    ' Create an EmbeddedFile object from a stream
    Using stream As FileStream = File.Open("..\../embedded.pdf", FileMode.Open)
        ' Create an embedded file by from stream and file name to be appear in the PDF document 
        Dim ef As New EmbeddedFile(stream, "file name")

        ' set optional properties
        ef.MimeType = "application/octet-stream"
        ef.Description = "description of the attachment"

        ' add the file to the document
        doc.EmbeddedFiles.Add(ef)

        Using outputstream As New FileStream("..\../output.pdf", FileMode.Create, FileAccess.Write)
            doc.Write(outputstream)
        End Using
    End Using
End Using
Download PDFKit.NET 5.0
We will send you a download link
Why do we ask your email address?
We send tips that speed up your evaluation
We let you know about bug fixes
You can always unsubscribe with one click
We never share your address with a 3rd party
Thank you for your download

We have sent an email with a download link. Alternatively, you may want to use the NuGet package manager to install our library.

Nuget ID

Use the NugetID and start right away, or download the package and install it handmatically