2016-12-23 106 views
1

我無法弄清爲什麼我的文件沒有加載到PDDocument對象中。未加載Java pdfbox文件

我的過程如下:

  • 打開目錄的文件
  • 獲取文件從目錄
  • 加載一個文件數組到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是有效的。

感謝您的幫助!

回答

0

而不是加載文檔是這樣的:

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

做到這一點:

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

您應該將IDE看到一個警告(如果是好的),其load是一個靜態方法。

enter image description here

你的代碼所做的是爲了顯示一個空PDDocument對象的頁數。

請注意,此答案僅適用於2.0。*。在1.8。*中也可能工作,除非PDF被加密。要覆蓋這一點,請使用loadNonSeq而不是load,這也將解密。

+0

非常好,謝謝! – btbam91