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

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


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文件。


当我运行上面的代码时,我总是得到:


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

难道我做错了什么?还有其他方法吗?


慕码人8056858
浏览 2376回答 3
3回答

明月笑刀无情

为什么不使用pdfbox 的PDFMergerUtility?PDFMergerUtility ut = new PDFMergerUtility();ut.addSource(...);ut.addSource(...);ut.addSource(...);ut.setDestinationFileName(...);ut.mergeDocuments();

MMMHUHU

package article14;import java.io.File;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDPage;import org.apache.pdfbox.util.PDFMergerUtility;public class Pdf{&nbsp; &nbsp; public static void main(String args[])&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; new Pdf().createNew();&nbsp; &nbsp; &nbsp; &nbsp; new Pdf().combine();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; public void combine()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; try&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; PDFMergerUtility mergePdf = new PDFMergerUtility();&nbsp; &nbsp; &nbsp; &nbsp; String folder ="pdf";&nbsp; &nbsp; &nbsp; &nbsp; File _folder = new File(folder);&nbsp; &nbsp; &nbsp; &nbsp; File[] filesInFolder;&nbsp; &nbsp; &nbsp; &nbsp; filesInFolder = _folder.listFiles();&nbsp; &nbsp; &nbsp; &nbsp; for (File string : filesInFolder)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mergePdf.addSource(string);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; mergePdf.setDestinationFileName("Combined.pdf");&nbsp; &nbsp; mergePdf.mergeDocuments();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch(Exception e)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; }public void createNew(){&nbsp; &nbsp; PDDocument document = null;&nbsp; &nbsp; try&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; String filename="test.pdf";&nbsp; &nbsp; &nbsp; &nbsp; document=new PDDocument();&nbsp; &nbsp; &nbsp; &nbsp; PDPage blankPage = new PDPage();&nbsp; &nbsp; &nbsp; &nbsp; document.addPage( blankPage );&nbsp; &nbsp; &nbsp; &nbsp; document.save( filename );&nbsp; &nbsp; }&nbsp; &nbsp; catch(Exception e)&nbsp; &nbsp; {&nbsp; &nbsp; }}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java