【问题标题】:GetPages error while migrating PDFBox to 2.x将 PDFBox 迁移到 2.x 时出现 GetPages 错误
【发布时间】:2019-03-15 09:43:13
【问题描述】:

我正在将我的 PDFBox 1.8.x 迁移到 2.0.12,并且必须进行一些更改。

我无法弄清楚的最后一个发生在下面的代码中。

    public static byte[] mergeDocuments(byte[] document1, byte[] document2) {
    try (PDDocument pdDocument1 = load(document1); PDDocument pdDocument2 = load(document2)) {
        final List<PDPage> pages1 = getPages(pdDocument1);
        final List<PDPage> pages2 = getPages(pdDocument2);
        pages1.addAll(pages2);
        return createDocument(pages1);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

private static List getPages(PDDocument pdDocumentTarget) {
    return pdDocumentTarget.getDocumentCatalog().getAllPages();
}

最后一行发生错误,我必须将旧的“.getAllPages()”更改为“.getPages”,但随后我将 PDPageTree 作为返回而不是 List。

代码是几年前写的,不是我写的。我已经尝试过一些事情,比如强制转换或更改类型,但它总是会在不同的地方导致错误。

提前感谢您的帮助

【问题讨论】:

  • 除了答案,你也可以试试document.getPage(i)document.getNumberOfPages()

标签: java list pdfbox


【解决方案1】:

PDPageTree 实现了Iterable&lt;PDPage&gt;,因此您实际上需要一种为Iterable 生成List 的方法。

This question 说明了许多方法,例如假设 Java 8:

private static List<PDPage> getPages(PDDocument pdDocumentTarget) {
    List<PDPage> result = new ArrayList<>();
    pdDocumentTarget.getPages().forEach(result::add);
    return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 2016-07-04
    • 2019-07-21
    • 2016-10-03
    • 2014-11-30
    • 1970-01-01
    相关资源
    最近更新 更多