Merge PDF files in C# and VB.NET

With GemBox.Pdf, you can merge PDF files into one PDF file in your C# or VB.NET application.

Since PDF pages are self-contained entities (their appearance is fully defined by their content stream and the associated resources, and their interactivity is mostly defined by their annotations), they can be easily cloned to other PDF files.

To merge PDF files, you simply need to clone all of their pages into a destination PDF file.

The following example demonstrates how to merge (concatenate) PDF files.

Screenshot of PDF files merged with GemBox.Pdf library
PDF files merged with GemBox.Pdf C#/VB.NET library
using GemBox.Pdf;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        // List of source file names.
        var fileNames = new string[]
        {
            "%#MergeFile01.pdf%",
            "%#MergeFile02.pdf%",
            "%#MergeFile03.pdf%"
        };

        using (var document = new PdfDocument())
        {
            foreach (var fileName in fileNames)
                // Load a source document from the specified path.
                using (var source = PdfDocument.Load(fileName))
                    // Clone all pages from the source document and add them to the destination document.
                    foreach (var page in source.Pages)
                        document.Pages.AddClone(page);

            document.Save("Merge Files.pdf");
        }
    }
}
Imports GemBox.Pdf

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        ' List of source file names.
        Dim fileNames = New String() _
        {
            "%#MergeFile01.pdf%",
            "%#MergeFile02.pdf%",
            "%#MergeFile03.pdf%"
        }

        Using document = New PdfDocument()

            For Each fileName In fileNames
                ' Load a source document from the specified path.
                Using source = PdfDocument.Load(fileName)
                    ' Clone all pages from the source document and add them to the destination document.
                    For Each page In source.Pages
                        document.Pages.AddClone(page)
                    Next
                End Using
            Next

            document.Save("Merge Files.pdf")
        End Using
    End Sub
End Module

In the above example, the source PDF files are combined so that their pages are cloned to a new PdfDocument, which is then saved to a PDF file.

If you want to clone a PDF page to an existing PdfDocument, then see this Cloning example.

Check next example or download examples from GitHub.