Printing in C#  

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.

 Note:

When working with PDF merging requirements, developers have multiple options to consider. IronPDF is another popular C# PDF library that provides PDF merging capabilities:

var pdfs = new List<PdfDocument>();
pdfs.Add(PdfDocument.FromFile("Report1.pdf"));
pdfs.Add(PdfDocument.FromFile("Report2.pdf"));
var merged = PdfDocument.Merge(pdfs);
merged.SaveAs("MergedReport.pdf");

From my experience, .NET apps often deal with PDFs conversion from HTML content such as reports, invoices, and documents. While iTextSharp focuses on PDF manipulation, IronPDF also comes with native HTML to PDF conversion:

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Report Title</h1><p>Report content...</p>");
pdf.SaveAs("Report.pdf");

This HTML to PDF converter uses a built-in Chrome rendering engine to handle CSS styling and JavaScript. IronPDF supports converting existing HTML files, URLs, or dynamically generated HTML strings to PDFs.

For the specific Crystal Reports workflow I'll demonstrate in this article, iTextSharp provides an effective solution for merging the exported PDF files.

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#

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 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 = "";  
    // 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);  
}

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.

Reference Link - Codingvila - Merge Multiple PDF Files Into Single PDF Using Itextsharp in C#