2013-02-04 60 views
3

我想用apache的pdfbox打印pdf文件,所以我創建了一個負責打印任何pdf文件的控制器。正如你在代碼中看到的那樣,控制器只有一個帶有文件路徑參數的公共方法。該控制器運行無異常,但它不打印任何東西:無法使用pdfbox打印任何東西

public class ControladorImpressao { 

    @Value("${nome.impressora}") 
    private String nomeImpressora; 
    private PDDocument arquivoPDF; 
    private Logger logger = LoggerFactory.getLogger(this.getClass()); 

    public boolean imprimir(String arquivo) { 
     try { 
      carregarArquivoPDF(arquivo); 
      iniciarImpressao(arquivo); 
      return true; 
     } catch (Exception e) { 
      logger.error("Erro ao tentar imprimir documento!",e); 
     } 
     return false; 
    } 

    private void carregarArquivoPDF(String arquivo) { 
     try { 
      arquivoPDF=new PDDocument(); 
      arquivoPDF.load(arquivo); 
     } 
     catch (Exception e) { 
      logger.error("Erro ao abrir pdf!",e); 
     } 
    } 

    private void iniciarImpressao(String nomeArquivo) throws PrinterException { 
     PrintService impressora=recuperarImpressora(); 
     PrinterJob job = PrinterJob.getPrinterJob(); 
     job.setPrintService(impressora); 
     job.setJobName(nomeArquivo); 
     job.setCopies(1); 
     arquivoPDF.silentPrint(job); 
    } 

    private PrintService recuperarImpressora() { 
     PrintService[] printServices = PrinterJob.lookupPrintServices(); 
     for (int count = 0; count < printServices.length; ++count) { 
      if (nomeImpressora.equalsIgnoreCase(printServices[count].getName())) { 
       return printServices[count]; 
      } 
     } 
     return null; 
    } 
} 

我使用PDFBOX版本1.7.0與Maven:

<dependency> 
     <groupId>org.apache.pdfbox</groupId> 
     <artifactId>pdfbox</artifactId> 
     <version>1.7.0</version> 
</dependency> 

我做錯了嗎?

回答

1

解決改變我instatiate PDDocument(我現在使用靜態負載),改變我如何使用的PrinterJob方式的問題:

public class ControladorImpressao { 

    @Value("${nome.impressora}") 
    private String nomeImpressora; 
    private PDDocument arquivoPDF; 
    private Logger logger = LoggerFactory.getLogger(this.getClass()); 

    public boolean imprimir(String arquivo) { 
     try { 
      arquivoPDF=PDDocument.load(new File(arquivo)); 
      PrinterJob job = PrinterJob.getPrinterJob(); 
      job.setPrintService(recuperarImpressora()); 
      job.setJobName(arquivo); 
      job.setPageable(arquivoPDF); 
      job.print(); 
      return true; 
     } catch (Exception e) { 
      logger.error("Erro ao tentar imprimir documento!",e); 
     } 
     return false; 
    } 

    private PrintService recuperarImpressora() { 
     PrintService[] printServices = PrinterJob.lookupPrintServices(); 
     for (int count = 0; count < printServices.length; ++count) { 
      if (nomeImpressora.equalsIgnoreCase(printServices[count].getName())) { 
       return printServices[count]; 
      } 
     } 
     return null; 
    } 
} 

我注意到有野趣的是,如果不是歐使用靜態加載方法我用:

arquivoPDF=new PDDocument(); 
arquivoPDF.load(arquivo); 

我仍然不能打印任何東西,可能問題是在加載方法。 感謝@yms,如果他沒有告訴我關於PdfBox文檔中的註釋,可能我會去另一條路徑。