English | 日本
PDF Java
Shopping CartContact Us
Knowledgebase
BCL easy PDF SDK

Merge PDF Documents in Directory with using C#

Date: May 21, 2012
Author: James Coe

In our first Method of the Week, I will provide a method to merge all of the pdf documents in a specified directory. At the bottom of this page the full method will be displayed in PDF C# code, allowing you to copy and paste it into your application in its entirety. Before that however, I will cover all of the individual steps of the method.

First, remember to add the proper References to your Project, and the Using Entries to go along with these References. This project will require that the PDF SDK Processor Library Reference is added, and will require the following "using" entries;

  • using System;
  • using System.IO;
  • using System.Collections;
  • using BCL.easyPDF7.Interop.EasyPDFProcessor;

Next, the Method's Name is as follows;

Method Name

It is intended 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 proper Error Reports. inFileDir is where you specify your Input Directory, while OutFileName is the output FileName.

  • inFileDir should use the following format; @"C:\YourFolderName\"
  • OutFileName should use the following format; @"C:\YourFolderName\OutName.pdf"
  • Alternatively, you can pass a value of null for OutFileName and the method will generate an outpuf File Name on its own name.

Next, we declare the Primary Variables and Objects.

Declaring Variables

Once these are declared, a small if-then statement checks to make sure that the Input Directory exists. This block also checks to see if a null variable was passed as the OutputFileName, and if so, generates a filename inside the input directory.

Check Input Directory

Next, we gather all of the input files to the ArrayList Object declared above. If there are no pdf files in the directory, an error will be returned stating such and the method will termine. Otherwise, all of the pdf files in the directory are loaded one by one into the ArrayList Object for easy merging.

This is a useful bit of code even for other operations, as it can give you a single collected area to store all of your filename addresses for easy use.

Gather Input Files

Once the input files are gathered, the method creates the Processory Object and Initializes it. It also applies the BCL License Key to the object. In this case the displayed Key is simply a Trial Extension Key, however the process is identical for a Full Key.

Create Processor Object

Finally, once the Object is initialized, the actual merger is carried out in a single line of code.

Merge the Files Merge the Files

If everything works as intended, you will receive a message telling you that the Merge has been completed and the file is located at the specified location. 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 will be reported instead.

That said, there are some limitations on this method. For starters, all of the PDF files have to be in the same folder. Next, if any of the pdf files in the directory are corrupt or inaccessible, it could cause the entire method to fail, and will, because of the way MergeBatch works, not tell you which file specifically caused the problem. Likewise, it does not give you any control over the order in which the files were merged and does not let you exclude any pdf files in the folder from the merge.

And here is the full Method's code, ready to be added to your 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;
    }
          

If you have any questions or problems concerning this method, or if you have any ideas for Methods you would like to see me create, please send me an email (Preferably with "Method of the Week" or "MotW" in its subject) at;

jcoe@bcltechnologies.com.

Happy Coding!

To use this method, you need to have easyPDF SDK installed in your machine

Download

PDF SDK Knowledgebase
 
BCL
© 1993 - , BCL Technologies.
All other trademarks are the property of their respective owners.