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.
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.
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.
PDFMergerUtility class should be instantiated in order to use the methods in it for merging the documents.
MergerUtility class provides setDestinationFileName() method to set the destination files as depicted below.
We need to set the source files using addSource() method as depicted below.
PDFmerger class provides the mergeDocuments() method to merge the documents.
Lastly, to close the document use close() method of the PDDocument class as depicted below.
Let us consider two PDF documents by name sample1.pdf and sample2.pdf in the path C:/PdfBox_Examples/.
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 Related Interview Questions
|Adv Java Interview Questions||Core Java Interview Questions|
|Java applet Interview Questions||Java Developer Interview Questions|
|Java collections framework Interview Questions||Apache Hive Interview Questions|
|Apache Pig Interview Questions||Java Management Extensions (JMX) Interview Questions|
|Angular 5 Interview Questions||Apache Wicket Interview Questions|
|Java 9 Interview Questions|
All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.