Merge PDF Files in Java

Merging PDF files is useful when you need to combine related documents into a single file for distribution, archiving, or processing.

Live Example

Aspose.PDF Merger is a free online application for testing PDF merging in a browser.

This topic shows how to merge multiple PDF files into a single document in Java:

  1. Open both source documents with the Document constructor.
  2. Append the Page collection from the second Document to the first one with document1.getPages().add(document2.getPages()).
  3. Save the merged Document to the output path.

Merge two PDF documents

The following Java example is based on MergeDocumentExamples.java.

public static void mergeTwoDocuments(Path inputFile1, Path inputFile2, Path outputFile) {
    try (Document document1 = new Document(inputFile1.toString());
         Document document2 = new Document(inputFile2.toString())) {
        document1.getPages().add(document2.getPages());
        document1.save(outputFile.toString());
    }
}