Merge two PDF files in C# using iText7

To merge two PDF documents using iText7 in C#, you can follow these steps:

 

First, we must install the required iText7 packages for our project using the NuGet Package Manager in Visual Studio. Install itext7, itext7.bouncy-castle-adapter, itext7.pdfhtml packages through the NuGet package manager.

 

Add the required namespaces to the project, as shown below. Open Microsoft Visual Studio 2022 and add the below namespaces.

using iText.Kernel.Pdf;

using iText.Kernel.Utils;

Create a method to merge PDFs: You can create a method that takes the paths of the PDF files to be merged in C# and the output file path as parameters. Here is an example:

namespace ConvertHtmlToPdf

{

    public class PdfService

    {

        public static void MergePdfs(string[] pdfFiles, string outputFile)

        {

            using PdfWriter writer = new (outputFile);

            using PdfDocument mergedPdf = new(writer);

            PdfMerger merger = new(mergedPdf);

 

            foreach (string file in pdfFiles)

            {

                using PdfReader reader = new(file);

                using PdfDocument pdf = new(reader);

               merger.Merge(pdf, 1, pdf.GetNumberOfPages());

            }

        }

    }

}

// Call MergePdfs method

string[] pdfFiles = { "C:\\Pdf\\output1.pdf", "C:\\Pdf\\output2.pdf" };

string outputFile = "C:\\Pdf\\Merged.pdf";

PdfService.MergePdfs(pdfFiles, outputFile);

Console.WriteLine("Given Pdf files merged and new pdf file Merged.pdf created at C:\\Pdf.");

This code will merge the two PDF files (output1.pdf and output2.pdf) into a single PDF file, Merged.pdf.

                                                                                                                                                                        Download Source Code at Github