Merging PDFs in memory with C# and .NET

Combining PDF files in memory is a powerful feature that can be easily implemented in C# using the SautinSoft.SautinSoft.Pdf library. This approach is effective and safe because it does not require writing intermediate files to disk. Regardless of whether you are working with a desktop, web, or cloud application, this method makes it easy to combine PDF documents programmatically. This can be especially useful when creating a single document from multiple reports or receipts.

To merge PDF files in memory using C# and .NET, follow these steps:

  1. Add SautinSoft.Pdf from NuGet.
  2. Read PDF files to a Memory.
  3. Merge PDF documents using MemoryStream.
  4. Save the document to show the result.

Output result:

Полный код

using System;
using System.IO;
using System.Collections.Generic;
using SautinSoft;
using SautinSoft.Pdf;
using SautinSoft.Pdf.Content;
using SautinSoft.Pdf.Facades;

namespace Sample
{
    class Sample
    {
        /// <summary>
        /// Merge PDF documents in memory using C# and .NET.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/merge-pdf-documents-in-memory-using-csharp-and-dotnet.php
        /// </remarks>
        static void Main(string[] args)
        {
            // Before starting this example, please get a free 100-day trial key:
            // https://sautinsoft.com/start-for-free/

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

            MergePdfInMemory();
        }
        static void MergePdfInMemory()
        {
            // In this example we are using files only to get input data and show the result.
            string resultPath = "Result.pdf";
            // The whole merge process will be done completely in memory. 

            // The list with PDFs. The each document stored as bytes array.
            List<byte[]> pdfDocs = new List<byte[]>();
            foreach (var f in Directory.GetFiles(@"..\..\..\", "*.pdf"))
                pdfDocs.Add(File.ReadAllBytes(f));

            // Create a PDF merger.
            var merger = new PdfMerger();

            // Iterate by documents and append them.
            foreach (var pdfDoc in pdfDocs)
                using (var ms = new MemoryStream(pdfDoc))
                    merger.Append(ms);

            // Save the merged PDF to a MemoryStream.
            using (var msMerged = new MemoryStream())
            {
                merger.Save(msMerged);
                // Save the result to a file to show.
                File.WriteAllBytes(resultPath, msMerged.ToArray());
            }

            // Show the result.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(resultPath) { UseShellExecute = true });
        }
    }
}

Download

Option Infer On

Imports System
Imports System.IO
Imports System.Collections.Generic
Imports SautinSoft
Imports SautinSoft.Pdf
Imports SautinSoft.Pdf.Content
Imports SautinSoft.Pdf.Facades

Namespace Sample
	Friend Class Sample
		''' <summary>
		''' Merge PDF documents in memory using C# and .NET.
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/merge-pdf-documents-in-memory-using-csharp-and-dotnet.php
		''' </remarks>
		Shared Sub Main(ByVal args() As String)
			' Before starting this example, please get a free license:
			' https://sautinsoft.com/start-for-free/

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

			MergePdfInMemory()
		End Sub
		Private Shared Sub MergePdfInMemory()
			' In this example we are using files only to get input data and show the result.
			Dim resultPath As String = "Result.pdf"
			' The whole merge process will be done completely in memory. 

			' The list with PDFs. The each document stored as bytes array.
			Dim pdfDocs As New List(Of Byte())()
			For Each f In Directory.GetFiles("..\..\..\", "*.pdf")
				pdfDocs.Add(File.ReadAllBytes(f))
			Next f

			' Create a PDF merger.
			Dim merger = New PdfMerger()

			' Iterate by documents and append them.
			For Each pdfDoc In pdfDocs
				Using ms = New MemoryStream(pdfDoc)
					merger.Append(ms)
				End Using
			Next pdfDoc

			' Save the merged PDF to a MemoryStream.
			Using msMerged = New MemoryStream()
				merger.Save(msMerged)
				' Save the result to a file to show.
				File.WriteAllBytes(resultPath, msMerged.ToArray())
			End Using

			' Show the result.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(resultPath) With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download

In the example above, you can see that the source PDF file is combined and the pages cloned into a new PDF.Net, which is then saved to a PDF file.


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.