DEV Community

Gia
Gia

Posted on

How to Merge Multiple PDF Files into One with C# Code

Merging multiple PDF files into a single file offers significant benefits in organizing and managing related documents, reports, or materials. It not only improves readability but also facilitates seamless sharing of information. By combining PDF files together, the need to repeatedly open and close multiple files is eliminated, resulting in time and effort savings. Furthermore, this process reduces the overall number of files, simplifying file storage and backup procedures. Additionally, apart from utilizing software for merging files, performing this operation programmatically is also a good approach. In this article, I will provide a comprehensive guide on merging multiple PDF files into a single file using C#.

Step 1 Download

Download Free Spire.PDF for .NET from this link and install it to local.
This free library not only supports merging PDFs, but also compressing and converting PDF, including images and Word documents.

Step 2 Import the DLL File into Project

Take Visual Studio 2022 for example.

  • Create a new C# project and open it.
  • Right-click " References " in the " Solution Explorer ", and then select " Add Reference " > " Browse ".
  • Find the DLL file in the BIN folder under the installation path and click " OK " to add it as a reference to the program.

Step 3 Write code

Write code or you can also refer to the following code.

using System;
using Spire.Pdf;

namespace MergePDFs
{
    class Program
    {
        static void Main(string[] args)
        {

            //Get the paths of the documents to be merged
            String[] files = new String[] {
                "sample-1.pdf",
                "sample-2.pdf",
                "sample-3.pdf"};

            //Merge these documents and return an object of PdfDocumentBase
            PdfDocumentBase doc = PdfDocument.MergeFiles(files);

            //Save the result to a PDF file
            doc.Save("result.pdf", FileFormat.PDF);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

With this short code, you can merger desired PDF files into one file effortlessly. Please specify the input path first. And merge these files by calling PdfDocument.MergeFiles() method. Finally, save the result to a PDF document using PdfDocumentBase.Save() method.

Image description

Else

Free Spire.PDF for .NET offers a completely free method without the need for installing any third-party software. It also allows easy creation and editing of PDF files on .NET platforms.
However, please note that there might be a page limitation in this free version. If you wish to remove it, you would need to use the commercial version.
Spire.PDF for .NET

Top comments (0)