2016-04-21 184 views
2

我正在嘗試打印PDF文檔。
我可以在打印機隊列中看到作業,然後看到它消失,就像打印機已完成作業一樣。PDF Java打印:在打印機作業隊列中發送的作業,但沒有打印

但問題是沒有打印。 我找不出在我的代碼中有什麼問題。

PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null,null); 
PrintService service = null; 
for (String imprimante : listImprimantes){ 
    for(PrintService printService : printServices) { 
     Attribute[] attrs = printService.getAttributes().toArray(); 
     for (int j=0; j<attrs.length; j++) { 
      String attrName = attrs[j].getName(); 
      String attrValue = attrs[j].toString(); 
      if (attrName.equals("printer-info")){ 
       if (attrValue.equals(imprimante)){ 
        service = printService; 
        DocFlavor[] flavors = service.getSupportedDocFlavors(); 
        break; 
       } 
      } 
     } 
    } 
} 
InputStream fi = new ByteArrayInputStream(baos.toByteArray()); 

DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; 
DocPrintJob printJob = service.createPrintJob(); 
Doc doc = new SimpleDoc(fi, flavor, null); 
try { 
    if (doc != null) { 
     printJob.print(doc, null); 
    } 
} 
catch (PrintException e1) { 
    log.debug(e1.getMessage()); 
} 

如果有人可以幫助我在此...

+0

你有沒有想過這個?我有同樣的問題... –

+0

不,我沒有。問題仍在進行中 – user1260928

回答

1

我知道這是有點晚了回答,但因爲我有同樣的問題,我認爲它可以幫助別人後我的解決方案。

我在Windows(7)上遇到了這個問題,但在Linux(Fedora)上沒有,所以我的第一個操作是檢查驅動程序設置。

然後,我看到許多打印機並不處理PDF。它被接受但沒有打印。從這裏可以選擇幾種解決方案:

  1. 在將PDF發送到打印機之前,將PDF轉換爲PS或類似的東西。
  2. 使用第三方庫,如Apache PdfBox(當前版本爲2.0.2)。

我選擇瞭解決方案2,它的功能就像一個魅力。其中的好處在於它還使用PrintService和屬性,因此您可以處理頁面,打印機托盤和許多選項。

這裏是我的代碼的一部分:

private boolean print(PrintService printService, InputStream inputStream, PrintRequestAttributeSet attributes) 
    throws PrintException { 

    try { 
     PDDocument pdf = PDDocument.load(inputStream); 
     PrinterJob job = PrinterJob.getPrinterJob(); 
     job.setPrintService(printService); 
     job.setPageable(new PDFPageable(pdf)); 
     job.print(attributes); 
     pdf.close(); 
    } catch (PrinterException e) { 
     logger.error("Error when printing PDF file using the printer {}", printService.getName(), e); 
     throw new PrintException("Printer exception", e); 
    } catch (IOException e) { 
     logger.error("Error when loading PDF from input stream", e); 
     throw new PrintException("Input exception", e); 
    } 
    return true; 
} 

希望這有助於。

+0

不要忘記關閉你的PDDocument對象。請同時提及您正在使用的PDFBox版本。 (希望2.0.2) –

+0

謝謝!我會嘗試。 – user1260928

+0

@TilmanHausherr好主意,謝謝,回答編輯。 – teemoo