【问题标题】:Efficiently determining the number of pages in a large pdf using pdfbox 2.x使用 pdfbox 2.x 有效地确定大型 pdf 中的页数
【发布时间】:2017-07-18 15:46:09
【问题描述】:

有没有一种有效的方法可以使用 pdfbox 2.x 获取 pdf 中的页数?目前,我从我们的 java web 应用程序中执行 shell 命令 pdfinfo 以获取此信息。当我用 pdfbox 做同样的事情时,下面的代码可以让我得到正确的页数,但是对于大文件来说它比 pdfinfo 慢得多。一个 670 MB 的 pdf 文件在 pdfinfo 中需要 270 毫秒,在 pdfbox 中需要 7300 毫秒。

public static void main(String[] args) {

    Date startDate = new Date();
    PDDocument document = null;
    try (FileInputStream in = new FileInputStream("D:\\pdftest\\test.pdf")){
        MemoryUsageSetting memoryUsageSetting = MemoryUsageSetting.setupMixed(1024*1024*500);
        document = PDDocument.load(in, memoryUsageSetting);
        System.out.println(String.format("number of pages: %d", document.getNumberOfPages()));

    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
    finally {
        if (document != null) {
            try {
                document.close();
            } catch (IOException e) {
                System.out.println("error closing the pdf file.");
            }
        }
    }

    Date endDate = new Date();

    System.out.println(endDate.getTime() - startDate.getTime());
}

【问题讨论】:

  • 您的问题类似于这个问题:“为什么奔驰 S500 在行驶 200 米以将一封信放入邮箱时比尼桑 Micra 消耗更多的油?”
  • PDFBox 专为处理完整文件而设计。加载 PDF 时,它确实是完全加载的。但是,对于大多数 info 目的,您实际上只需要加载 PDF 对象的一小部分。因此,专门的 info 工具自动比 PDFBox 等通用库更快。

标签: java performance pdf pdfbox


【解决方案1】:

理论上,您可以编写一个 Inputstream 来加载 PDF 并检查其内容以查找根页面字典。如果找到,/Count 会为您提供页数(因为/Count 是必需属性)。但请注意,在以后的 PDF 规范中,内容是扁平化编码的,所以你需要先扁平化解码......

一个例子(PDF Spec 1.4):

...
30980 0 obj
<< 
/Type /Catalog 
/Pages 30881 0 R 
/Metadata 30868 0 R 
...
>> 
endobj
....
30881 0 obj
<< 
/Type /Pages 
/Kids [ ... ] 
/Count 978 
>> 

【讨论】:

  • 感谢您提供的信息,我可能会在不久的将来继续使用 pdfinfo。我不想解析原始 pdf 来查找页数。
  • 是的,你问的是 ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
  • 2018-12-25
  • 2013-07-15
  • 2015-02-01
  • 1970-01-01
相关资源
最近更新 更多