PDFBox Merging Multiple PDF Documents - PDFBox

What is PDFBox Merging Multiple PDF Documents?

In the previous section, we went through on how to split a PDF document into multiple documents. In this section, we will learn how to merge multiple PDF documents as a single document.

Merging Multiple PDF Documents

Multiple PDF documents can be merged into single PDF document using a class called PDFMergerUtility. This class provides methods to merge.

Below steps should be followed to merge multiple PDF document.

Step 1: Loading an Existing PDF Document

To load an existing document, use the load() method of the PDDocument class. Instantiate this class to load the PDF document as depicted below. It accepts a file object as parameter.

Step 2: Instantiating the PDFMergerUtility class

PDFMergerUtility class should be instantiated in order to use the methods in it for merging the documents.

Step 3: Setting the destination file

MergerUtility class provides setDestinationFileName() method to set the destination files as depicted below.

Step 4: Setting the source files

We need to set the source files using addSource() method as depicted below.

Step 5: Merging the documents

PDFmerger class provides the mergeDocuments() method to merge the documents.

Step 6: Closing the Document

Lastly, to close the document use close() method of the PDDocument class as depicted below.

Example

Let us consider two PDF documents by name sample1.pdf and sample2.pdf in the path C:/PdfBox_Examples/.

PDFBox Merging Multiple PDF Documents

PDFBox Merging Multiple PDF Documents

Example below explains on how to merge above mentioned PDF documents. We will merge the two documents sample1.pdf and sample2.pdf into a single PDF document with name merged.pdf. Save the above code in a file by name MergePDFs.java.

Once the file is saved, compile and execute it from command prompt using the below commands-

Above program will split the given PDF document. Below message is rendered upon execution-

Verify the path given while saving the document and you will see that a PDF document of name merged.pdf is created and has the pages of the documents as depicted below.

PDFBox Merging Multiple PDF Documents

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PDFBox Topics