我正在尝试打印 PDF 文档。
我可以在打印机队列中看到该作业,然后看到它消失,就像打印机已完成其作业一样。
但问题是没有打印任何内容。
我无法弄清楚我的代码中有什么问题。
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 发送到打印机之前,将其转换为 PS 或类似文件。
- 使用第三方库,例如阿帕奇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;
}
希望这可以帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)