【问题标题】:Apache pdfbox .doc to .pdf conversionApache pdfbox .doc 到 .pdf 的转换
【发布时间】: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 仍然可以同时使用两者。不过,您必须了解不同的架构。

标签: java pdf itext pdfbox doc


【解决方案1】:

你使用 iText 类并做

documentByteArray = out.toByteArray();

在你完成文档之前

document.close();

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

【讨论】:

    猜你喜欢
    • 2013-07-23
    • 2010-12-02
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    相关资源
    最近更新 更多