DEV Community

Ali Jago Seif
Ali Jago Seif

Posted on

Merge PDF Documents in Directory in C#

In my first post, I am going to provide you with a method to merge all of the pdf files in a particular directory. The full method is displayed in PDF C# code below. Feel free to copy and paste it into your application in its entirety. Together we will cover all of the individual steps of this way to merging PDF files in C#.

First of all, please keep in mind to add the proper References to your Project, and the Using Entries to go along with these References. Your project is required that the C# PDF Library Processor Reference is added, and will require the following "using" entries:

using System;
using System.IO;
using System.Collections;
using BCL.easyPDF8.Interop.EasyPDFProcessor;

The Method's Name is as follows:

public static string MergeAllPDFFilesInDIR(string inFileDir, string OutFileName)
{

It is proposed to take two string variables and return one string variable. The return value is a String that will contain a status report, either a report of the successful conversion, with the name of the Output File produced, or the best possible Error Reports. inFileDir is the place you determine your Input Directory, while OutFileName is the output FileName.

inFileDir must use this format: @"C:\YourFolderName\". On the other side OutFileName needs to follow this format: @"C:\YourFolderName\OutName.pdf".
Otherwise, you can enter a value of null for OutFileName and the method will automatically generate an output File Name with its own name.

This is how we declare the Primary Variables and Objects.

//Declare Major Variables and Objects
string result = null;
DirectoryInfo Dir = null;
FileInfo[] FileList = null;
ArrayList InputFileList = null;
PDFProcessor oMerger = null;

Once Variables and Objects are declared, you need to check that the Input Directory exists by a small if-then statement. This also checks to see if a null variable was passed as the OutputFileName, and if so, generates a filename inside the input directory.


// Identify inFileDir and OutFileName
Dir = new DirectoryInfo(inFileDir);
if (!Dir.Exists)
{
result = "Directory : " + inFileDir + " : Does not Exist";
return result;
}
if (OutFileName == null)

//If OutFileName is NUll, provide a
//Default File Name and Location
{
OutFileName = inFileDir + "_1_Merged.pdf";
}

After that, we need to gather all of the input files to the ArrayList Object as it is shown above. If there are no PDF files in the directory, an error will be returned and the programme will end. Otherwise, all of the PDF files in the directory are going to be loaded one by one into the ArrayList Object for further merging.

// Gather Input Files
FileList = Dir.GetFiles("*.pdf", SearchOption.AllDirectories);
InputFileList = new ArrayList();
foreach (FileInfo FI in FileList) { InputFileList.Add(FI.FullName);

if (InputFileList.Count == 0)
{
result = "There were no PDF Files in : " + inFileDir;
return result;
}

When the input files are collected, the method creates the Processory Object and Initializes it as well. In addition, it applies the License Key (which is required to use this C# PDF Library) to the object. You can get the free one on PDF SDK website.

// Create Processor Object
try
{
oMerger = new PDFProcessor();
oMerger.LicenseKey = "475D-E1ED-5336-DD76-2C5E-FDAE";
//If you are using the BCL Licensing System, enter your License Key Here;
}
catch (Exception errCreate)
{
result = "Attempt to create PDFProcessor oMerger Failed : Message : "
+ errCreate.Message + " : Inner Exception : "
+ errCreate.InnerException;
return result;
}

Once the Object is initialized, the actual merger is carried out in the following code.

//Run MergeBatch
try
{
oMerger.MergeBatch(InputFileList.ToArray(), OutFileName);
}
catch (Exception errRun)
{
result = "Attempt to Merge the Documents Failed : Message : "
+ errRun.Message + " : Inner Exception : " + errRun.InnerException;
return result;
}

result = "Merging Complete : Output File located at : " + OutFileName;
return result;
}

You receive a message that indicates that the Merge has been completed if everything works as intended. The output file is located at the location specified by you. Because we formatted the OutFileName string to include the entire file address, you will be told both what the file is named and where it is located. If there are any errors, they should be reported instead.

Here is the full Method's code, ready to be added to any C# application:

public static string MergeAllPDFFilesInDIR(string inFileDir, string OutFileName)
    {
            //Declare Major Variables and Objects
        string result = null;
        DirectoryInfo Dir = null;
        FileInfo[] FileList = null;
        ArrayList InputFileList = null;
        PDFProcessor oMerger = null;

            // Identify inFileDir and OutFileName
        Dir = new DirectoryInfo(inFileDir);
        if (!Dir.Exists)
        {
            result = "Directory : " + inFileDir + " : Does not Exist";
            return result;
        }
        if (OutFileName == null)    
        //If OutFileName is NUll, provide a
        //Default File Name and Location
        {
            OutFileName = inFileDir + "_1_Merged.pdf";
        }

            // Gather Input Files
        FileList = Dir.GetFiles("*.pdf", SearchOption.AllDirectories);
        InputFileList = new ArrayList();
        foreach (FileInfo FI in FileList) { InputFileList.Add(FI.FullName); }

        if (InputFileList.Count == 0)
        {
            result = "There were no PDF Files in : " + inFileDir;
            return result;
        }

            // Create Processor Object
        try
        {
            oMerger = new PDFProcessor();
            oMerger.LicenseKey = "475D-E1ED-5336-DD76-2C5E-FDAE";    
            //If you are using the BCL Licensing System, enter your License Key Here;
        }
        catch (Exception errCreate)
        {
            result = "Attempt to create PDFProcessor oMerger Failed : Message : " 
                + errCreate.Message + " : Inner Exception : "
                + errCreate.InnerException;
            return result;
        }
        
            //Run MergeBatch
        try
        {
            oMerger.MergeBatch(InputFileList.ToArray(), OutFileName);
        }
        catch (Exception errRun)
        {
            result = "Attempt to Merge the Documents Failed : Message : " 
                + errRun.Message + " : Inner Exception : " + errRun.InnerException;
            return result;
        }

        result = "Merging Complete : Output File located at : " + OutFileName;
        return result;
    }

Please feel free to contact me if you have any questions or problems concerning this method, or if you have any ideas for Methods you would like me to create.

Have a good coding!

Top comments (0)