Java Program To Merge Two PDF Files

Chapter: Miscellaneous Last Updated: 18-03-2023 14:39:47 UTC


            /* ............... START ............... */
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");

        // Add the second PDF file
        File file2 = new File("file2.pdf");

        // Set the destination file name
        File mergedFile = new File("merged.pdf");

        try {
            // Merge the PDF files
            System.out.println("PDF files merged successfully.");
        } catch (IOException e) {
            System.err.println("Error merging PDF files: " + e.getMessage());
                /* ............... END ............... */


  • 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.


#Java Program To Merge Two PDF Files # Apache PDFBox library # merge two PDF files

Similar Programs Chapter Last Updated
Java Parse JSON String To Object Miscellaneous 24-03-2023
Java Program For Date And Time Miscellaneous 24-03-2023
Java Binary Search Tree Implementation Miscellaneous 21-03-2023
How To Create A Git Repository | Git repository commands Miscellaneous 31-07-2021
Currency Formatter In Java | How To Format Currency In Java Miscellaneous 19-07-2021
Factory Design Pattern In Java Miscellaneous 11-05-2021
Data Types In Java Miscellaneous 09-06-2018