How to merge two PDF files into one in Java?

Lipis picture Lipis · Aug 27, 2010 · Viewed 128.2k times · Source

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?

Answer

cherouvim picture cherouvim · Feb 2, 2011

Why not use the PDFMergerUtility of pdfbox?

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