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

Duplicating Pages in an Existing PDF

Date: November 8, 2012
Author: James Coe

In our Second Method of the Week, we look at duplicating a page within an already existing PDF file. Like always, at the bottom of this page the full method will be displayed in 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 PDFProcessor 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

As you may have noticed, the name specifically mentions Forms; that is because this method was originally an experiment from our Engineers to see if we could duplicate a page in an existing PDF Form and preserve that pages Form Fields. After determining that we could, the Engineers shared a version of this method, which I have slightly modified. I will assure you this method works equally well on normal non-Form PDF Files.

As for the Method itself, it is intended to take two string variables, two integer 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.

  • InFileName should use the following format; @"C:\YourFolderName\InName.pdf"
  • 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.
  • PageToDuplicate should be an integer value starting from an index of 1. The Code itself will convert this to a 0-index Integer when used.
  • TimestoDuplicate should be an integer value of at least 1.

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 File was both specified and 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 Initialize the Processor Object that was previously created. Here I also apply the License Key using the BCL Licensing Method and a simple Trial Key.

Gather Input Files

This sample method is designed to not rely on Temporary Files, and will work purely in Memory. As such we will use the Processor object to Extract the Pages into Memory, as shown below;

Create Processor Object

This large section of Code Extracts all of the Pages into one of three Page Categories. The Front being all of the Pages before the Page to be Duplicated, the Middle being only the Page to be Duplicated, and the Back being all of the Pages that follow. This way, we can use a very simple for Loop to position all of the pages in the ArrayList for merging. This could also be modified to take a Range of Pages to duplicate.

Merge the Files

Once the pages are loaded into the ArrayList, all that remains is a very simple call for the Processor.MergeBatchMem() method.

Merge the Files

From there, you can take the OutFileMem, being just a simple Byte[] Array, and do anything you want. Since it is in Memory you could load it into the ProcessorHandle using OpenMem() and perform further operations on it, or duplicate more pages with just a slight change to the existing code. In my sample Method I then use the native IO capabilites of the System to save the Byte[] Stream as a PDF.

Merge the Files

And here is the full Method's code, ready to be added to your application;

          
    public string DuplicateSpecificPageInForm(
        string InFileName, 
        string OutFileName, 
        int PageToDuplicate, 
        int TimesToDuplicate)
    {
        // Declare Necessary Variables and Objects
        string result = null;
        PDFProcessor oProcessor = null;

        byte[] InFileMem = null;
        byte[] OutFileMem = null;

        ArrayList OutputFilePieces = null;
        byte[] FileSection_Front = null;
        byte[] FileSection_Middle = null;
        byte[] FileSection_Back = null;

        // Load InFileName into Memory
        if (InFileName == null)
        {
            result = "ERROR : Input File Not Specified";
            return result;
        }
        else if (!File.Exists(InFileName))
        {
            result = "ERROR : Input File does not Exist";
            return result;
        }
        else
        {
            InFileMem = File.ReadAllBytes(InFileName);
        }
        //If OutFileName is NUll, provide a Default File Name
        if (OutFileName == null) 
        {
            OutFileName = InFileName + "_OUT.pdf";
        }

        // Create Processor Object
        try
        {
            oProcessor = new PDFProcessor();
            oProcessor.LicenseKey = "4755-E1ED-5296-DD76-7E75-89CC";
            //If you are using the BCL Licensing System, enter your License Key Here;
        }
        catch (Exception errCreate)
        {
            result = "Attempt to create PDFProcessor oProcessor Failed : Message : "
                + errCreate.Message + " : Inner Exception : " + errCreate.InnerException;
            return result;
        }

        //Extract Front Pages
        try
        {
            FileSection_Front = 
                (byte[])oProcessor.ExtractPagesMem(
                    InFileMem, 
                    0,
                    PageToDuplicate - 2);
        }
        catch (Exception errCreate)
        {
            result = "Attempt to Extract the Front Pages Failed : Message : "
                + errCreate.Message + " : Inner Exception : " + errCreate.InnerException;
            return result;
        }
        //Extract Page to Duplicate
        try
        {
            FileSection_Middle =
                (byte[])oProcessor.ExtractPagesMem(
                    InFileMem, 
                    PageToDuplicate - 1,
                    PageToDuplicate - 1);
        }
        catch (Exception errCreate)
        {
            result = "Attempt to Extract the Target Page Failed : Message : "
                + errCreate.Message + " : Inner Exception : " + errCreate.InnerException;
            return result;
        }
        //Extract Back Pages
        try
        {
            FileSection_Back = 
                (byte[])oProcessor.ExtractPagesMem(
                    InFileMem, 
                    PageToDuplicate,
                    oProcessor.GetPageCount(InFileName)-1);
        }
        catch (Exception errCreate)
        {
            result = "Attempt to Extract the Back Pages Failed : Message : "
                + errCreate.Message + " : Inner Exception : " + errCreate.InnerException;
            return result;
        }

        //Add the Pages to the ArrayList
        OutputFilePieces = new ArrayList();
        OutputFilePieces.Add(FileSection_Front);
        for (int i = 1; i <= TimesToDuplicate; i++)
        {
            OutputFilePieces.Add(FileSection_Middle);
        }
        OutputFilePieces.Add(FileSection_Back);

        //Merge The Pieces Together
        try
        {
            OutFileMem = oProcessor.MergeBatchMem(OutputFilePieces.ToArray());
        }
        catch (Exception errRun)
        {
            result = "Attempt to Merge the Documents Failed : Message : "
                + errRun.Message + " : Inner Exception : " + errRun.InnerException;
            return result;
        }

        //Save the Output to the specified File Name
        try
        {
            File.WriteAllBytes(OutFileName, OutFileMem);
            result = "Success! Output File saved to : " + OutFileName.ToString();
            return result;
        }
        catch (Exception errRun)
        {
            result = "Attempt to Save the Output Failed : Message : "
                + errRun.Message + " : Inner Exception : " + errRun.InnerException;
            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.