Introduction
Merge Multiple PDF Files Into Single PDF Using Itextsharp in C# |
Assume that you are working with a well-known reporting tool "Crystal Report Viewer" and as per your requirement you exporting 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 archive this kind of requirement? So in this article, I gonna show you how to archive this kind of requirement.
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 Forum of C# Corner but didn't get any solution as per my need, I Searched on many of websites available on internet but didn't get right solution.
Then from my current company, one of my superior/senior suggest 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 wrote a method and using this method we can merge multiple PDF Document in Single Document and got a solution that I gonna share with you.
What is Itextsharp library?
Itextsharp is an advanced tool library that is a free and open source which is used for creating complex pdf documents and that help 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 Document 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 to a merge pdf document in the single document, but before that, you need to download Itextsharp.dll file and add in your project as a reference assembly. You can download Itextsharp.dll from the internet, there is many websites are 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 Marge Multiple PDF Document Using Itextsharp
C#
public static void MargeMultiplePDF(string[] PDFfileNames, string OutputFile) { // Create document object iTextSharp.text.Document PDFdoc = new iTextSharp.text.Document(); // Create a object of FileStream which will be disposed at the end using (System.IO.FileStream MyFileStream = new System.IO.FileStream(OutputFile, System.IO.FileMode.Create)) { // Create a PDFwriter that is listens to the Pdf document iTextSharp.text.pdf.PdfCopy PDFwriter = new iTextSharp.text.pdf.PdfCopy(PDFdoc, MyFileStream); if (PDFwriter == null) { return; } // Open the PDFdocument PDFdoc.Open(); foreach (string fileName in PDFfileNames) { // Create a PDFreader for a certain PDFdocument iTextSharp.text.pdf.PdfReader PDFreader = new iTextSharp.text.pdf.PdfReader(fileName); PDFreader.ConsolidateNamedDestinations(); // Add content 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); } // Close PDFreader PDFreader.Close(); } // Close the PDFdocument and PDFwriter PDFwriter.Close(); PDFdoc.Close(); }// Disposes the Object of FileStream }
How to use MargeMultiplePDF Function
After, Create this function here I will show you how you can use this function to merge your multiple pdf documents. So, If you analyzed 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 name/path of input files.
Let's take an example to use this function in C#
C#
try { string FPath = ""; // Create For loop for get/create muliple report on single click based on row of gridview control for (int j = 0; j < Gridview1.Rows.Count; j++) { // Return datatable for data 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) { // Create Object of ReportDocument ReportDocument cryRpt = new ReportDocument(); //Store path of .rpt file string StrPath = Application.StartupPath + "\\RPT"; StrPath = StrPath + "\\"; StrPath = StrPath + "rptCodingvila_Articles_Report.rpt"; cryRpt.Load(StrPath); // Assign Report Datasource cryRpt.SetDataSource(dtDetail); // Assign Reportsource to Report viewer CryViewer.ReportSource = cryRpt; CryViewer.Refresh(); // Store path/name of pdf file one by one string StrPathN = Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report" + i.ToString() + ".Pdf"; FPath = FPath == "" ? StrPathN : FPath + "," + StrPathN; // Export Report in PDF cryRpt.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, StrPathN); } } if (FPath != "") { // Check for File Existing or Not if (System.IO.File.Exists(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf")) System.IO.File.Delete(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf"); // Split and store pdf input file string[] files = FPath.Split(','); // Marge Multiple PDF File MargeMultiplePDF(files, Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf"); // Open Created/Marged PDF Output File Process.Start(Application.StartupPath + "\\Temp" + "\\Codingvila_Articles_Report.pdf"); // Check and Delete Input file 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); }