PDF Java打印:在打印机作业队列中发送的作业,但没有打印
我正在尝试打印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());
}
如果有人可以帮助我在此...
我知道这是有点晚了回答,但因为我有同样的问题,我认为它可以帮助别人后我的解决方案。
我在Windows(7)上遇到了这个问题,但在Linux(Fedora)上没有,所以我的第一个操作是检查驱动程序设置。
然后,我看到许多打印机并不处理PDF。它被接受但没有打印。从这里可以选择几种解决方案:
- 在将PDF发送到打印机之前,将PDF转换为PS或类似的东西。
- 使用第三方库,如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;
}
希望这有助于。
不要忘记关闭你的PDDocument对象。请同时提及您正在使用的PDFBox版本。 (希望2.0.2) –
谢谢!我会尝试。 – user1260928
@TilmanHausherr好主意,谢谢,回答编辑。 – teemoo
你有没有想过这个?我有同样的问题... –
不,我没有。问题仍在进行中 – user1260928