Java pdfbox 文件未加载

Java pdfbox file not being loaded

我无法弄清楚为什么我的文件没有被加载到 PDDocument 对象中。

我的流程如下:

请参阅下面的代码。

public class Main {

public static void main(String[] args) throws IOException {

    //open directory
    File folder = new File("pdfs");

    //Extract Files
    File[] files = folder.listFiles();

    //print out file names
    for (File file:files) {
        System.out.println(file.getName());
        System.out.println("Can read?: " + file.canRead());
        System.out.println("Can write?: " + file.canWrite());
    }


    //Load PDF
    PDDocument firstDocument = new PDDocument();

    try {
        firstDocument.load(files[0]);
    }
    finally
    {
        if (firstDocument != null) {
            firstDocument.close();

        }
    }

    System.out.println("Num Pages: " + firstDocument.getNumberOfPages());

输出:

EnterpriseArchitectInvoice.pdf
Can read?: true
Can write?: true
ooad_textbooks_invoice.pdf
Can read?: true
Can write?: true
Num Pages: 0

我可以保证PDF是有效的。

感谢帮助!!!

而不是像这样加载您的文档:

PDDocument firstDocument = new PDDocument();
firstDocument.load(files[0]);

这样做:

PDDocument firstDocument = PDDocument.load(files[0]);

您应该已经看到 IDE 发出的警告(如果它是好的)表明 load 是一个静态方法。

您的代码所做的是显示空 PDDocument 对象中的页数。

请注意,此答案仅适用于 2.0.*。在 1.8.* 中它也可以工作,除非 PDF 被加密。为了也涵盖这一点,请使用 loadNonSeq 而不是 load,后者也将解密。