Merge Pdf: Error: there was an error opening this document file cannot be opened because it has no pages

Merge Pdf: Error: there was an error opening this document file cannot be opened because it has no pages

我正在尝试合并 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();
    }

这是有效的代码

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