【发布时间】:2016-01-16 13:33:34
【问题描述】:
我正在尝试将.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;
}
【问题讨论】:
-
PdfWriter - 这不是 itext 吗?您使用的是什么版本的 PDFBox?你能上传你的PDF吗?为什么从未调用过“writer.close()”?
-
您的问题是关于 iText 还是关于 Pdfbox?它们是竞争产品。
-
@Amadee 仍然可以同时使用两者。不过,您必须了解不同的架构。