Merge Multiple PDF Files Into Single PDF Using Itextsharp In C#

Introduction

 
This article provides an explanation about how to merge multiple pdf files into a single pdf using Itextsharp in C#. I have also explained the use of Itextsharp library as well as how to find and delete existing files on the directory.
 
While you are working with any web/windows software application sometimes at the time of reporting you need some advanced functionality like auto export, multiple export options such as an export report with PDF, DOC, XLSX, XLS, CSV, RPT, and many other options. Sometimes it is necessary to merge multiple exported documents into a single document that you export as per the client's need.
 
Assume that you are working with a well-known reporting tool "Crystal Report Viewer" and as per your requirement you export the report in PDF Document and there is a bundle of exported PDF documents and your client gives you a requirement to merge all the PDF Files within only one single PDF Document. Then how you can achieve this kind of requirement? In this article, I will show you. 
 
Recently, a few days ago I got the same requirement from my client they said they want to print all the reports in PDF on Singal Click. At that time I didn't know the actual solution for this requirement, and for help, I also posted my requirement in the C# Corner forum, but I didn't get any solution as per my need. So I Searched on many websites but didn't find anything. 
 
Then from my current company, one of my supervisors suggested some ideas like I should export the report in PDF Document using Itextsharp library with help of looping mechanism and save these documents in any temporary folder of the project directory and finally create a method to merge all these exported PDF Documents. So, I have analyzed that solution and written a method, and using this method we can merge multiple PDF Documents into Single Documents.
 

What is the Itextsharp library?

 
itextsharp is an advanced tool library that is free and open-source which is used for creating complex pdf documents and that helps to convert page output or HTML content in a PDF file.
 
Requirement
  1. Export Multiple Crystal Report in PDF File on Singal Click and Save that documents Directory of Project.
  2. Marge All the Exported Documents in Single PDF Document.
  3. If Exists Then Remove All The Existing Exported PDF Document from The Directory.

Implementation

 
So, let's start with an example of a merge pdf document in a single document, but before that, you need to download the Itextsharp.dll file and add in your project as a reference assembly. You can download Itextsharp.dll from the internet, there are many websites available where you can find this DLL file.
 
Now, after downloading the Itextsharp.dll and as I said after adding this assembly as a reference in your project you need to add the following function in your code-behind.
 
Function To Merge Multiple PDF Document Using Itextsharp
 
C#
  1. public static void MargeMultiplePDF(string[] PDFfileNames, string OutputFile)  
  2. {  
  3.     // Create document object  
  4.     iTextSharp.text.Document PDFdoc = new iTextSharp.text.Document();  
  5.     // Create a object of FileStream which will be disposed at the end  
  6.     using (System.IO.FileStream MyFileStream = new System.IO.FileStream(OutputFile, System.IO.FileMode.Create))  
  7.     {  
  8.         // Create a PDFwriter that is listens to the Pdf document  
  9.         iTextSharp.text.pdf.PdfCopy PDFwriter = new iTextSharp.text.pdf.PdfCopy(PDFdoc, MyFileStream);  
  10.         if (PDFwriter == null)  
  11.         {  
  12.             return;  
  13.         }  
  14.         // Open the PDFdocument  
  15.         PDFdoc.Open();  
  16.         foreach (string fileName in PDFfileNames)  
  17.         {  
  18.             // Create a PDFreader for a certain PDFdocument  
  19.             iTextSharp.text.pdf.PdfReader PDFreader = new iTextSharp.text.pdf.PdfReader(fileName);  
  20.             PDFreader.ConsolidateNamedDestinations();  
  21.             // Add content  
  22.             for (int i = 1; i <= PDFreader.NumberOfPages; i++)  
  23.             {  
  24.                 iTextSharp.text.pdf.PdfImportedPage page = PDFwriter.GetImportedPage(PDFreader, i);  
  25.                 PDFwriter.AddPage(page);  
  26.             }  
  27.             iTextSharp.text.pdf.PRAcroForm form = PDFreader.AcroForm;  
  28.             if (form != null)  
  29.             {  
  30.                 PDFwriter.CopyAcroForm(PDFreader);  
  31.             }  
  32.             // Close PDFreader  
  33.             PDFreader.Close();  
  34.         }  
  35.         // Close the PDFdocument and PDFwriter  
  36.         PDFwriter.Close();  
  37.         PDFdoc.Close();  
  38.     }// Disposes the Object of FileStream  
  39. }  

How to use MargeMultiplePDF Function

 
After creating this function  I will show you how you can use this function to merge your multiple pdf documents. So, If you analyzed the above function then this function requires 2 arguments as an input parameter PDFfileNames for input files and OutputFile as output file where PDFfileNames is a string array that holds the name/path of input files.
 
Let's take an example to use this function in C#
 
C#
  1. try  
  2. {  
  3.     string FPath = "";  
  4.     // Create For loop for get/create muliple report on single click based on row of gridview control  
  5.     for (int j = 0; j < Gridview1.Rows.Count; j++)  
  6.     {  
  7.         // Return datatable for data  
  8.         DataTable dtDetail = new My_GlobalClass().GetDataTable(Convert.ToInt32(Gridview1.Rows[0]["JobId"]));  
  9.    
  10.         int i = Convert.ToInt32(Gridview1.Rows[0]["JobId"]);  
  11.         if (dtDetail.Rows.Count > 0)  
  12.         {  
  13.             // Create Object of ReportDocument  
  14.             ReportDocument cryRpt = new ReportDocument();  
  15.             //Store path of .rpt file  
  16.             string StrPath = Application.StartupPath + "\\RPT";  
  17.             StrPath = StrPath + "\\";  
  18.             StrPath = StrPath + "rptCodingvila_Articles_Report.rpt";  
  19.             cryRpt.Load(StrPath);  
  20.             // Assign Report Datasource  
  21.             cryRpt.SetDataSource(dtDetail);  
  22.             // Assign Reportsource to Report viewer  
  23.             CryViewer.ReportSource = cryRpt;  
  24.             CryViewer.Refresh();  
  25.             // Store path/name of pdf file one by one   
  26.             string StrPathN = Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report" + i.ToString() + ".Pdf";  
  27.             FPath = FPath == "" ? StrPathN : FPath + "," + StrPathN;  
  28.             // Export Report in PDF  
  29.             cryRpt.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, StrPathN);  
  30.         }  
  31.     }  
  32.     if (FPath != "")  
  33.     {  
  34.         // Check for File Existing or Not  
  35.         if (System.IO.File.Exists(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf"))  
  36.             System.IO.File.Delete(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf");  
  37.         // Split and store pdf input file  
  38.         string[] files = FPath.Split(',');  
  39.         //  Marge Multiple PDF File  
  40.         MargeMultiplePDF(files, Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf");  
  41.         // Open Created/Marged PDF Output File  
  42.         Process.Start(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf");  
  43.         // Check and Delete Input file  
  44.         foreach (string item in files)  
  45.         {  
  46.             if (System.IO.File.Exists(item.ToString()))  
  47.                 System.IO.File.Delete(item.ToString());  
  48.         }  
  49.    
  50.     }  
  51. }  
  52. catch (Exception ex)  
  53. {  
  54.     XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);  
  55. }  
I have used the above code for looping on Grandview and getting a unique identity "JobId" from grid view column one by one. And also getting DataTable using "GetDataTable" method where GetDataTable returns DatTable and that is available in my class "My_GlobalClass". Then I  created an object of ReportDocument and loaded rpt file from my application startup path and based on DataTable I have an assign data source to my rpt "rptCodingvila_Articles_Report.rpt" and loaded rpt in my report viewer "CryViewer" and finally exported the  report using "ExportToDisk" Method one by one. Before that I stored path of the report with the filename I stored in string variable "FPath" as I show in above code.
 
Now after exporting all the reports I checked that FPath wasn't blank, then I checked if the same result/output file existed or not in my project directory. If I found any file then I simply deleted that file and merged all other exported input files using the created method "MargeMultiplePDF" and opened that merged document on client screen as a pdf document, and at last removed all other single exported input files from the directory instead of the output file.
 

Summary

 
This article provides an explanation about how to how to merge multiple pdf files into one pdf in using Itextsharp in C#. I also explained the use of Itextsharp library as well as how to find and delete existing files on the directory.