Attaching Files to PDFs using C# and .NET

Embedding files into a PDF document is a powerful feature that allows users to include additional resources, such as images, documents, or other file types, directly within a PDF. This functionality is particularly useful for creating comprehensive and interactive documents. Using C# and .NET, developers can easily implement this feature with the help of Sautinsoft PDF.NET library.

Embedding files in a PDF document offers several advantages:

  • Centralized Information. All related files are stored in one document, making it easier to share and access.
  • Enhanced Interactivity. Users can interact with the embedded files directly from the PDF.
  • Professional Presentation. Embedding files adds a layer of professionalism to reports, manuals, and presentations.

Below is an example of how this can be done:

  1. Add SautinSoft.PDF from NuGet.
  2. Load a PDF document.
  3. Make the attachment panel visible.
  4. Extract all files from the zip archive to the file system directory.
  5. Paste all the files extracted from the zip archive into the PDF document.
  6. Specify the relative path to the file in the zip archive in the description of the embedded file.
  7. Delete the directory where the zip archive files were extracted.
  8. Save the document.

Input file:

Embed from files input

Output result:

Embed from files output

Complete code

using System;
using System.IO;
using System.IO.Compression;
using SautinSoft;
using SautinSoft.Pdf;
using SautinSoft.Pdf.Content;

namespace Sample
{
    class Sample
    {
        /// <summary>
        /// Embed files to PDF document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/embed-files-to-pdf-document.php
        /// </remarks>
        static void Main(string[] args)
        {
            string pdfFile = Path.GetFullPath(@"..\..\..\simple text.pdf");

            using (var document = PdfDocument.Load(pdfFile))
            {
                // Make Attachments panel visible.
                document.PageMode = PdfPageMode.UseAttachments;

                // Extract all the files in the zip archive to a directory on the file system.
                ZipFile.ExtractToDirectory(@"..\..\..\Attachments.zip", "Attachments");

                // Embed in the PDF document all the files extracted from the zip archive.
                foreach (var filePath in Directory.GetFiles("Attachments", "*", SearchOption.AllDirectories))
                {
                    var fileSpecification = document.EmbeddedFiles.Add(filePath).Value;

                    // Set embedded file description to the relative path of the file in the zip archive.
                    fileSpecification.Description = filePath.Substring(filePath.IndexOf('\\') + 1).Replace('\\', '/');
                }

                // Delete the directory where zip archive files were extracted to.
                Directory.Delete("Attachments", recursive: true);

                document.Save("Embedded Files from file system.pdf");
            }

            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("Embedded Files from file system.pdf") { UseShellExecute = true });
        }
    }
}

Download

Option Infer On

Imports System
Imports System.IO
Imports System.IO.Compression
Imports SautinSoft
Imports SautinSoft.Pdf
Imports SautinSoft.Pdf.Content

Namespace Sample
	Friend Class Sample
		''' <summary>
		''' Embed files to PDF document.
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/embed-files-to-pdf-document.php
		''' </remarks>
		Shared Sub Main(ByVal args() As String)
			Dim pdfFile As String = Path.GetFullPath("..\..\..\simple text.pdf")

			Using document = PdfDocument.Load(pdfFile)
				' Make Attachments panel visible.
				document.PageMode = PdfPageMode.UseAttachments

				' Extract all the files in the zip archive to a directory on the file system.
				ZipFile.ExtractToDirectory("..\..\..\Attachments.zip", "Attachments")

				' Embed in the PDF document all the files extracted from the zip archive.
				For Each filePath In Directory.GetFiles("Attachments", "*", SearchOption.AllDirectories)
					Dim fileSpecification = document.EmbeddedFiles.Add(filePath).Value

					' Set embedded file description to the relative path of the file in the zip archive.
					fileSpecification.Description = filePath.Substring(filePath.IndexOf("\"c) + 1).Replace("\"c, "/"c)
				Next filePath

				' Delete the directory where zip archive files were extracted to.
				Directory.Delete("Attachments", recursive:= True)

				document.Save("Embedded Files from file system.pdf")
			End Using

			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo("Embedded Files from file system.pdf") With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.