2015-07-21 67 views
2

我想使用PDFBox打印現有的PDF文件。這裏的代碼:PDFBox凍結在打印()命令

public void sendToPrinter(){ 
    File PDFFile = new File("Example.pdf"); 

    try { 
     PDDocument pd = PDDocument.load(PDFFile); 
     pd.print(); 
     pd.close(); 
    } catch (IOException | PrinterException ex) { 
     System.out.println("Error: Couldn't find pdf or printers"); 
    } 
} 

但是,當我運行它,程序凍結在pd.print()。不會拋出異常,不會出現打印對話框。它只是沒有做任何事情。有沒有人有過這個問題?

規格:Mac OS X的優山美地,PDFBox的v1.8.9,JDK1.8.0_05,HP Photosmart打印機

+0

您使用的是哪個版本?您是否可以使用PDFReader命令行實用程序顯示該文件?您是否可以使用PrintPDF命令行工具進行打印?每個PDF都會發生,還是隻發生在一個特定的一個?你能分享PDF文件嗎? –

+0

我使用的是最新版本1.8.9。我沒有使用任何一個命令行實用程序,但我測試過的所有三個PDF文件都在普通PDF查看器中打開,但不在PDFBox中。 – corpico

+0

這是我嘗試過的PDF格式之一。它只有1頁幾乎沒有任何東西:http://cl.ly/c0cX/download/nYPhhd.pdf – corpico

回答

1

具有相同問題的人。當我將所有PDF工作放到另一個線程上時,我的print()命令起作用。供參考:

public void sendToPrinter() { 

     //Create new Task 
     Task task = new Task<Boolean>() { 
      @Override 
      public Boolean call() { 

       //Reference the PDF file 
       File PDFFile = new File("File.pdf"); 

       try { 
        //Load PDF & create a Printer Job 
        PDDocument pd = PDDocument.load(PDFFile); 
        PrinterJob job = PrinterJob.getPrinterJob(); 
        job.setPageable(new PDFPageable(pd)); 

        //Show native print dialog & wait for user to hit "print" 
        if (job.printDialog()) { 
         job.print(); 
        } 

        pd.close(); 
       } catch (IOException | PrinterException ex) { 
       } 

       return true; 
      } 
     }; 
     //Run task on new thread 
     new Thread(task).start(); 

}