Merging Multiple PDF Documents in C# and .NET

Programmatically merging PDF files is a common requirement in various business scenarios, such as consolidating reports, merging scanned documents, or combining multiple PDF files into a single file for distribution. In C# and .NET this can be achieved using the SautinSoft.SautinSoft.Pdf library.

To combine PDF files using C# and .NET, follow these steps:

  1. Add SautinSoft.Pdf from NuGet.
  2. Prepare a list with PDFs to merge.
  3. Use PdfMerger to combine PDFs.
  4. Save the document.

Output result:

Combining PDF files in C# and .NET is a simple task using the SautinSoft.SautinSoft.Pdf library. By following the steps described above, you can combine multiple PDF documents into a single file with minimal effort. This functionality is necessary for applications that need to perform document management tasks.

Полный код

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 files.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/merge-pdf-files.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("...");

            MergePdfFiles();
        }

        static void MergePdfFiles()
        {
            var inpFiles = new List<string>(Directory.GetFiles(Path.GetFullPath(@"..\..\..\"), "*.pdf"));
            string outFile = Path.GetFullPath(@"Merged.pdf");

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

            // Merge multiple PDF documents to the one.
            foreach (var inpFile in inpFiles)
                merger.Append(inpFile);

            merger.Save(outFile);

            // Show the result.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { 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 files.
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/merge-pdf-files.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("...");

			MergePdfFiles()
		End Sub

		Private Shared Sub MergePdfFiles()
			Dim inpFiles = New List(Of String)(Directory.GetFiles(Path.GetFullPath("..\..\..\"), "*.pdf"))
			Dim outFile As String = Path.GetFullPath("Merged.pdf")

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

			' Merge multiple PDF documents to the one.
			For Each inpFile In inpFiles
				merger.Append(inpFile)
			Next inpFile

			merger.Save(outFile)

			' Show the result.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) 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.


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.com или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



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

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