2017-08-10 171 views
0

我想合并PDF文件,但在打开文件时出现错误。我的代码是:合并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

)的代码,我就指出,你不使用''里面tobyte message'('。 – shmosel

+0

谢谢@shmosel。它的一个愚蠢的错误。 –

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