Embed Files into PDF files using C# and VB.NET

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


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.