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
- Export Multiple Crystal Report in PDF File on Singal Click and Save that documents Directory of Project.
- Marge All the Exported Documents in Single PDF Document.
- 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#
- public static void MargeMultiplePDF(string[] PDFfileNames, string OutputFile)
- {
-
- iTextSharp.text.Document PDFdoc = new iTextSharp.text.Document();
-
- using (System.IO.FileStream MyFileStream = new System.IO.FileStream(OutputFile, System.IO.FileMode.Create))
- {
-
- iTextSharp.text.pdf.PdfCopy PDFwriter = new iTextSharp.text.pdf.PdfCopy(PDFdoc, MyFileStream);
- if (PDFwriter == null)
- {
- return;
- }
-
- PDFdoc.Open();
- foreach (string fileName in PDFfileNames)
- {
-
- iTextSharp.text.pdf.PdfReader PDFreader = new iTextSharp.text.pdf.PdfReader(fileName);
- PDFreader.ConsolidateNamedDestinations();
-
- for (int i = 1; i <= PDFreader.NumberOfPages; i++)
- {
- iTextSharp.text.pdf.PdfImportedPage page = PDFwriter.GetImportedPage(PDFreader, i);
- PDFwriter.AddPage(page);
- }
- iTextSharp.text.pdf.PRAcroForm form = PDFreader.AcroForm;
- if (form != null)
- {
- PDFwriter.CopyAcroForm(PDFreader);
- }
-
- PDFreader.Close();
- }
-
- PDFwriter.Close();
- PDFdoc.Close();
- }
- }
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#
- try
- {
- string FPath = "";
-
- for (int j = 0; j < Gridview1.Rows.Count; j++)
- {
-
- DataTable dtDetail = new My_GlobalClass().GetDataTable(Convert.ToInt32(Gridview1.Rows[0]["JobId"]));
-
- int i = Convert.ToInt32(Gridview1.Rows[0]["JobId"]);
- if (dtDetail.Rows.Count > 0)
- {
-
- ReportDocument cryRpt = new ReportDocument();
-
- string StrPath = Application.StartupPath + "\\RPT";
- StrPath = StrPath + "\\";
- StrPath = StrPath + "rptCodingvila_Articles_Report.rpt";
- cryRpt.Load(StrPath);
-
- cryRpt.SetDataSource(dtDetail);
-
- CryViewer.ReportSource = cryRpt;
- CryViewer.Refresh();
-
- string StrPathN = Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report" + i.ToString() + ".Pdf";
- FPath = FPath == "" ? StrPathN : FPath + "," + StrPathN;
-
- cryRpt.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, StrPathN);
- }
- }
- if (FPath != "")
- {
-
- if (System.IO.File.Exists(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf"))
- System.IO.File.Delete(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf");
-
- string[] files = FPath.Split(',');
-
- MargeMultiplePDF(files, Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf");
-
- Process.Start(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf");
-
- foreach (string item in files)
- {
- if (System.IO.File.Exists(item.ToString()))
- System.IO.File.Delete(item.ToString());
- }
-
- }
- }
- catch (Exception ex)
- {
- XtraMessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
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.