Merge Pdf using C#

Step 1-Add PDFsharp dll in your project and use the below code to merge PDF.

using System;
using System.IO;
using System.Linq;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;


namespace TestFire
{
   public class MergePdf
    {
        public static void Main()
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(@"Directory path");
            if (directoryInfo.Exists)
            {
                FileInfo[] allPdFs = directoryInfo.GetFiles("*.pdf");
                var targetpath = "Target PDF file path where you want to merge";
                var result = allPdFs.OrderBy(x => x.Name).Select(x => x.FullName);
                MergePdFFiles(targetpath, result.ToArray());
            }
            else
            {
                Console.WriteLine("No such directory found");
            }
            
           
        }
        public static void MergePdFFiles(string targetPath, string[] pdfsFilePath)
        {
            using (PdfDocument targetDoc = new PdfDocument())
            {
                foreach (string pdf in pdfsFilePath)
                {
                   using (PdfDocument pdfDoc = PdfReader.Open(pdf,PdfDocumentOpenMode.Import))
                    {
                        for (int i = 0; i < pdfDoc.PageCount; i++)
                        {
                            targetDoc.AddPage(pdfDoc.Pages[i]);
                        }
                    }
                }
                targetDoc.Save(targetPath);
            }
        }


    }
    
}

To view or add a comment, sign in

More articles by Ankit Panwar

Others also viewed

Explore content categories