2017-08-10 299 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(); 
}