合并Pdf:错误:打开此文档文件时出错,因为它没有页面而无法打开

时间:2017-08-10 05:41:28

标签: java pdf pdfbox

我正在尝试合并pdf文件,但在打开文件时出错。我的代码是:

    public void merge(){
        byte[] pdf1 = tobyte("hello");
        byte[] pdf2 = tobyte("world");
        PDFMergerUtility merger = new PDFMergerUtility();
        merger.addSource(new ByteArrayInputStream(pdf1));
        merger.addSource(new ByteArrayInputStream(pdf2));
        merger.setDestinationFileName("final.pdf");
        merger.mergeDocuments();
    }

    static byte[] tobyte(String message) {
        PDDocument doc = new PDDocument();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        doc.save(baos);
        return baos.toByteArray();
    }

1 个答案:

答案 0 :(得分:0)

以下是适用的代码

//Loading an existing PDF document
File file1 = new File("sample1.pdf");
PDDocument doc1 = null;
try {
    doc1 = PDDocument.load(file1);
} catch (IOException e1) {
    e1.printStackTrace();
}

File file2 = new File("sample2.pdf");
PDDocument doc2 = null;
try {
    doc2 = PDDocument.load(file2);
} catch (IOException e1) {
    e1.printStackTrace();
}

//Instantiating PDFMergerUtility class
PDFMergerUtility PDFmerger = new PDFMergerUtility();

//Setting the destination file
PDFmerger.setDestinationFileName("merged.pdf");

//adding the source files
PDFmerger.addSource(file1);
PDFmerger.addSource(file2);

//Merging the two documents
try {
    PDFmerger.mergeDocuments();
} catch (COSVisitorException | IOException e) {
    e.printStackTrace();
}

System.out.println("Documents merged");
//Closing the documents
try {
    doc1.close();
} catch (IOException e) {
    e.printStackTrace();
}
try {
    doc2.close();
} catch (IOException e) {
    e.printStackTrace();
}