Home » PDFBox Merging PDF Document

PDFBox Merging PDF Document

by Online Tutorials Library

PDFBox Merging PDF Document

We can merge multiple PDF documents into a single PDF file. Merging PDF documents using PDFBox could not be simple. We can merge PDF documents by using the PDFMergerUtility class. This class provides everything we need to take multiple or multi-page PDF documents and merge them into one single PDF document. We can merge any number of files as required.

The Following is a step by step process which are used to merge all PDF’s file located in a directory without having to pass each file as an argument.

Load Existing Document

We can load the existing PDF document by using the static load() method. This method accepts a file object as a parameter. We can also invoke it using the class name PDDocument of the PDFBox.

Create PDFMergerUtility Class Object

Instantiate the PDFMergeUtility class. This class contains routines to merge PDFs. This can be shown in the following code:

Set Destination

Set path to the destination files using the setDestinationFileName() method. This can be shown in the following code:

Set Source File

Add all the source PDF files in the sequence we would like to find in the final merged PDF file. addSource() method is used to set the source file, which can be shown below.

Merge PDFs

Add all the source PDF files to be merge. Merge the documents using the mergeDocuments() method of the PDFmerger class, which can be shown in the below code.

Close Document

After completing the task, we need to close the PDDocument class object by using the close() method.

Example-

Here, we get three PDF document files and we will merge them into a single PDF file through PDFBox library of a Java Program.

PDFBox Merging PDF Document
PDFBox Merging PDF Document

PDFBox Merging PDF Document

Java Program

Output:

After successful execution of the above program, the following message will be shown below.

PDFBox Merging PDF Document

To verifying the given path, we can observe that a PDF document with name merged.pdf is created. This documents contains all the pages of the source documents file provided as shown below.

PDFBox Merging PDF Document

Next TopicPDFBox Validation

You may also like