Merge PDF programmatically

Now, merging pdf files is one of the most demanded tasks. This article shows how to merge multiple PDF files into a single PDF document using Aspose.PDF for Java. The example is written in Java, but the API can be used in other programming languages. PDF files are merged such that the first one is joined at the end of the other document.

Merge PDF Files using Java

To concatenate two PDF files:

  1. Create two Document objects, each containing one of the input PDF files.
  2. Then call the PageCollection collection’s Add method for the Document object you want to add the other PDF file to.
  3. Pass the PageCollection collection of the second Document object to the first PageCollection collection’s Add method.
  4. Finally, save the output PDF file using the Save method.

The following code snippet shows how to concatenate PDF files with Java.

package com.aspose.pdf.examples;

import com.aspose.pdf.*;

public class ExampleMerge {
    // The path to the documents directory.
    private static String _dataDir = "/home/admin1/pdf-examples/Samples/";

    public static void Merge() {
        
        // Open first document
        Document pdfDocument1 = new Document(_dataDir + "Concat1.pdf");
        // Open second document
        Document pdfDocument2 = new Document(_dataDir + "Concat2.pdf");

        // Add pages of second document to the first
        pdfDocument1.getPages().add(pdfDocument2.getPages());

        // Save concatenated output file
        pdfDocument1.save(_dataDir+"ConcatenatePdfFiles_out.pdf");

    }

}