Java Program To Merge Two PDF Files
Chapter:
Miscellaneous
Last Updated:
18-03-2023 14:39:47 UTC
Program:
/* ............... START ............... */
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
public class PdfMerger {
public static void main(String[] args) {
// Create a new PDFMergerUtility object
PDFMergerUtility pdfMerger = new PDFMergerUtility();
// Add the first PDF file
File file1 = new File("file1.pdf");
pdfMerger.addSource(file1);
// Add the second PDF file
File file2 = new File("file2.pdf");
pdfMerger.addSource(file2);
// Set the destination file name
File mergedFile = new File("merged.pdf");
pdfMerger.setDestinationFileName(mergedFile.getAbsolutePath());
try {
// Merge the PDF files
pdfMerger.mergeDocuments(null);
System.out.println("PDF files merged successfully.");
} catch (IOException e) {
System.err.println("Error merging PDF files: " + e.getMessage());
}
}
}
/* ............... END ............... */
Notes:
-
The program is written in Java and uses the Apache PDFBox library to merge two PDF files.
- First, we create a new PDFMergerUtility object, which is a utility class provided by PDFBox for merging multiple PDF documents. We then add the two source PDF files that we want to merge using the addSource() method.
- Next, we set the destination file name for the merged PDF file using the setDestinationFileName() method. In this case, the destination file name is "merged.pdf".
- Finally, we call the mergeDocuments() method to merge the two PDF files. If the merge is successful, the program prints a message to the console saying "PDF files merged successfully". If an error occurs during the merge, the program catches the exception and prints an error message to the console.
- It's worth noting that this program assumes that the PDFBox library has been properly included in the project's classpath, so that the program can use the necessary PDFBox classes and methods.
Tags
#Java Program To Merge Two PDF Files # Apache PDFBox library # merge two PDF files