【问题标题】:PDF Java print : job sent in printer jobs queue but nothing printsPDF Java 打印:在打印机作业队列中发送作业但没有打印
【发布时间】:2016-08-14 15:32:46
【问题描述】:

我正在尝试打印 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 8)java 8,我用 apache PDF 框尝试了@teemoo 答案,但它只适用于 PDF 格式。
  • 我也遇到了同样的问题,请问有解决办法吗?

标签: java pdf printing


【解决方案1】:

我知道现在回答有点晚,但由于我遇到了同样的问题,我认为它可以帮助其他人发布我的解决方案。

我在 Windows (7) 上遇到过这个问题,但在 Linux (Fedora) 上却没有,所以我的第一个操作是检查驱动程序设置。

然后,我看到许多打印机无法原生处理 PDF。它被接受,但没有打印任何内容。由此,可以选择几种解决方案:

  1. 在将 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;
}

希望这会有所帮助。

【讨论】:

  • 不要忘记关闭您的 PDDocument 对象。请同时提及您正在使用的 PDFBox 版本。 (希望是 2.0.2)
猜你喜欢
  • 2018-09-27
  • 1970-01-01
  • 2016-08-06
  • 1970-01-01
  • 2010-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-20
相关资源
最近更新 更多