如何在Java中将两个PDF文件合并为一个?

问题描述:

我想使用 PDFBox 将许多PDF文件合并为一个,这就是我所做的:

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();

其中 pdfFiles ArrayList< String> 包含所有PDF文件。

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?

为什么不使用 PDFMergerUtility

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