Incorporating File Streams in C# & .NET PDFs

Embedding streams in PDF documents is a powerful feature that allows developers to include additional data, such as files, images, or other resources, directly into a PDF. This approach is particularly useful when working with dynamic content or when the data to be embedded is not stored as a physical file but exists as a stream in memory. Using C# and .NET, this functionality can be implemented efficiently with the help of the SautinSoft PDF.NET library.

Embedding streams in PDFs offers several advantages:
  • Dynamic Content. Streams allow embedding data that is generated or modified at runtime.
  • Memory Efficiency. Streams eliminate the need to save temporary files to disk, improving performance.
  • Enhanced Functionality. Embedding streams can be used for adding metadata, attachments, or other resources directly into the PDF.

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. Insert all files from the zip archive into the PDF document.
  5. Add an empty file.
  6. Specify the relative path to the file in the zip archive in the description of the embedded file.
  7. Set the size of the embedded file and the modification date.
  8. Copy the contents of the embedded file from the zip archive entry.
  9. Save the document.

Input file:

Embed from stream input

Output result:

Embed from stream output

Complete code

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

class Program
{
    /// <summary>
    /// Embed files to PDF document.
    /// </summary>
    /// <remarks>
    /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/embed-files-from-stream-to-pdf-document.php
    /// </remarks>
    static void Main()
    {
        // Before starting this example, please get a free trial key:
        // https://sautinsoft.com/start-for-free/

        // Apply the key here:
        // PdfDocument.SetLicense("...");

        using (var document = PdfDocument.Load(Path.GetFullPath(@"..\..\..\simple text.pdf")))
        {
            // Make Attachments panel visible.
            document.PageMode = PdfPageMode.UseAttachments;

            // Embed in the PDF document all the files from the zip archive.
            using (var archiveStream = File.OpenRead(@"..\..\..\Attachments.zip"))
            using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Read, leaveOpen: true))
                foreach (var entry in archive.Entries)
                    if (!string.IsNullOrEmpty(entry.Name))
                    {
                        var fileSpecification = document.EmbeddedFiles.AddEmpty(entry.Name).Value;

                        // Set embedded file description to the relative path of the file in the zip archive.
                        fileSpecification.Description = entry.FullName;

                        var embeddedFile = fileSpecification.EmbeddedFile;

                        // Set the embedded file size and modification date.
                        if (entry.Length < int.MaxValue)
                            embeddedFile.Size = (int)entry.Length;
                        embeddedFile.ModificationDate = entry.LastWriteTime;

                        // Copy embedded file contents from the zip archive entry.
                        // Embedded file is compressed if its compressed size in the zip archive is less than its uncompressed size.
                        using (var entryStream = entry.Open())
                        using (var embeddedFileStream = embeddedFile.OpenWrite(compress: entry.CompressedLength < entry.Length))
                            entryStream.CopyTo(embeddedFileStream);
                    }

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

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

Download

Option Infer On

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

Friend Class Program
	''' <summary>
	''' Embed files to PDF document.
	''' </summary>
	''' <remarks>
	''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/embed-files-from-stream-to-pdf-document.php
	''' </remarks>
	Shared Sub Main()
		' Before starting this example, please get a free trial key:
		' https://sautinsoft.com/start-for-free/

		' Apply the key here:
		' PdfDocument.SetLicense("...");

		Using document = PdfDocument.Load(Path.GetFullPath("..\..\..\simple text.pdf"))
			' Make Attachments panel visible.
			document.PageMode = PdfPageMode.UseAttachments

			' Embed in the PDF document all the files from the zip archive.
			Using archiveStream = File.OpenRead("..\..\..\Attachments.zip")
			Using archive = New ZipArchive(archiveStream, ZipArchiveMode.Read, leaveOpen:= True)
				For Each entry In archive.Entries
					If Not String.IsNullOrEmpty(entry.Name) Then
						Dim fileSpecification = document.EmbeddedFiles.AddEmpty(entry.Name).Value

						' Set embedded file description to the relative path of the file in the zip archive.
						fileSpecification.Description = entry.FullName

						Dim embeddedFile = fileSpecification.EmbeddedFile

						' Set the embedded file size and modification date.
						If entry.Length < Integer.MaxValue Then
							embeddedFile.Size = CInt(entry.Length)
						End If
						embeddedFile.ModificationDate = entry.LastWriteTime

						' Copy embedded file contents from the zip archive entry.
						' Embedded file is compressed if its compressed size in the zip archive is less than its uncompressed size.
						Using entryStream = entry.Open()
						Using embeddedFileStream = embeddedFile.OpenWrite(compress:= entry.CompressedLength < entry.Length)
							entryStream.CopyTo(embeddedFileStream)
						End Using
						End Using
					End If
				Next entry
			End Using
			End Using

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

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

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.