2016-01-16 43 views
-2

我試圖將.doc轉換爲.pdf,但是我得到了這個異常,我不知道如何解決它。阿帕奇pdfbox .doc到.pdf轉換

java.io.IOException: Missing root object specification in trailer 
at org.apache.pdfbox.pdfparser.COSParser.parseTrailerValuesDynamically(COSParser.java:2042) 

這就是拋出異常:

PDDocument pdfDocument = PDDocument.load(convertDocToPdf(documentInputStream)); 

這裏是我的轉換方法:

private byte[] convertDocToPdf(InputStream documentInputStream) throws Exception { 
    Document document = null; 
    WordExtractor we = null; 
    ByteArrayOutputStream out = null; 
    byte[] documentByteArray = null; 
    try { 
     document = new Document(); 
     POIFSFileSystem fs = new POIFSFileSystem(documentInputStream); 

     HWPFDocument doc = new HWPFDocument(fs); 
     we = new WordExtractor(doc); 
     out = new ByteArrayOutputStream(); 
     PdfWriter writer = PdfWriter.getInstance(document, out); 

     Range range = doc.getRange(); 
     document.open(); 
     writer.setPageEmpty(true); 
     document.newPage(); 
     writer.setPageEmpty(true); 

     String[] paragraphs = we.getParagraphText(); 
     for (int i = 0; i < paragraphs.length; i++) { 
      org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i); 
      paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", ""); 
      document.add(new Paragraph(paragraphs[i])); 
     } 
     documentByteArray = out.toByteArray(); 
    } catch (Exception ex) { 
     ex.printStackTrace(System.out); 
     throw new Exception(STATE.FAILED_CONVERSION.name()); 
    } finally { 
     document.close(); 
     try { 
      we.close(); 
      out.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return documentByteArray; 
} 
+0

PdfWriter - 不是那個itext?你使用的是什麼版本的PDFBox?你能上傳你的PDF嗎?爲什麼「writer.close()」從不叫? –

+0

是關於iText還是關於Pd​​fbox的問題?他們是競爭產品。 –

+0

@Amadee仍然可以並排使用。不過,我們必須意識到不同的體系結構。 – mkl

回答

0

您使用的iText類和你之前做

documentByteArray = out.toByteArray(); 

完成文檔

document.close(); 

因此,documentByteArray只包含PDFBox抱怨的不完整PDF。