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

watch_later Tuesday, January 22, 2019
comment 4 Comments

Introduction


This article provides an explanation about how to merge multiple pdf files into single pdf in using Itextsharp in c# here I also explained the use of Itextsharp library as well as how to find and delete existing files on the directory.
Merge Multiple PDF Files Into Single PDF Using Itextsharp in C#
Merge Multiple PDF Files Into Single PDF Using Itextsharp in C#

While you working with any web/windows software application sometimes at the time of reporting you to need some advanced functionality like auto export, multiple exports 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 document in a single document that you exported as per client's need.

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);
}
If You analyzed above code I have used for loop on Grandview and get a unique identity "JobId" from grid view column one by one. and get DataTable using "GetDataTable" method where GetDataTable return DataTable and that is available in my class "My_GlobalClass". and then create object of ReportDocument and load rpt file from my application startup path and  based on DataTable I have assign data source to my rpt "rptCodingvila_Articles_Report.rpt" and load rpt in my report viewer "CryViewer" and finally export report using "ExportToDisk" Method one by one but before that I stored path of report with filename I stored in string variable "FPath " as I show in above code. 

Now after export all the reports I checked in FPath is not blank then I checked for the same result/output file existing or not in my project directory if I found any file then I simply delete that file and marge all other exported input file using created method "MargeMultiplePDF" and open that merged document on client screen as pdf document and at last remove all other single exported input file from directory instead of 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# here I also explained the use of Itextsharp library as well as how to find and delete existing files on the directory.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

avatar

You can try to do it using ZetPDF.com. It's one of the best website for this one. It's very easy to use.

delete February 13, 2019 at 11:52 PM
avatar
Codingvila person

Thanks for your valuable suggestions Great, and sure I will try it.

delete February 14, 2019 at 8:57 AM
avatar

I simply use ZETPDF to generate PDF reports and I think ZETPDF is the best solution for generting PDF reports.

delete February 19, 2019 at 2:15 AM



sentiment_satisfied Emoticon