How to merge multiple PDF file using OpenPDF and itext in Java

Updated: June 8, 2024

Using OpenPDF:

pom.xml
...
<dependency>
  <groupId>com.github.librepdf</groupId>
  <artifactId>openpdf</artifactId>
  <version>2.0.2</version>
</dependency>
...

Or using older version of iText

pom.xml
...
<dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext</artifactId>
    <version>4.2.2</version>
</dependency>
...
Main.java
public File mergePdf(String[] pdfPaths, String outputPath) {
    File outputPdf = new File(outputPath);

    try (
        /// Handle Closable resources
        Document document = new Document();
        PdfCopy pdfCopy = new PdfCopy(document, new FileOutputStream(outputPdf))
    ) {
        document.open();

        /// Loop through each PDF files
        for (String path : pdfPaths) {
            PdfReader reader = new PdfReader(path);

            /// Loop through each PDF pages and clone each page
            for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                PdfImportedPage page = pdfCopy.getImportedPage(reader, i);
                pdfCopy.addPage(page);
            }
            reader.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return outputPdf;
}