Search code examples
javapdfpdfbox

How to merge two PDF files into one in Java?


I want to merge many PDF files into one using PDFBox and this is what I've done:

PDDocument document = new PDDocument();
for (String pdfFile: pdfFiles) {
    PDDocument part = PDDocument.load(pdfFile);
    List<PDPage> list = part.getDocumentCatalog().getAllPages();
    for (PDPage page: list) {
        document.addPage(page);
    }
    part.close();
}
document.save("merged.pdf");
document.close();

Where pdfFiles is an ArrayList<String> containing all the PDF files.

When I'm running the above, I'm always getting:

org.apache.pdfbox.exceptions.COSVisitorException: Bad file descriptor

Am I doing something wrong? Is there any other way of doing it?


Solution

  • Why not use the PDFMergerUtility of pdfbox?

    PDFMergerUtility ut = new PDFMergerUtility();
    ut.addSource(...);
    ut.addSource(...);
    ut.addSource(...);
    ut.setDestinationFileName(...);
    ut.mergeDocuments();