用Java打印到特定打印机(IPP URI)

Jas*_*Day 15 java printing ipp-protocol

Java中有没有办法打印到特定的IPP打印机?我发现的所有示例代码和教程都集中在如何使用以下内容打印特定类型的文档:

DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(MediaSizeName.ISO_A4);
PrintService[] pservices =
             PrintServiceLookup.lookupPrintServices(flavor, aset);
if (pservices.length > 0) {
    DocPrintJob pj = pservices[0].createPrintJob();
    try {
        FileInputStream fis = new FileInputStream("test.ps");
        Doc doc = new SimpleDoc(fis, flavor, null);
        pj.print(doc, aset);
    } catch (FileNotFoundException fe) {
    } catch (PrintException e) { 
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码段只是打印到找到的能够打印文档的第一台打印机.在我的情况下,我想通过其URI查找打印机,但PrintServiceLookup似乎不支持这一点.我尝试过使用a PrintServiceAttributeSet而不是PrintRequestAttributeSet添加PrinterURI属性,但这并没有返回任何打印机.我怀疑查找服务正在寻找可以更改其目标URI的打印机,而不是查找具有该URI的打印机.

作为最后的手段,我想到只是枚举所PrintService返回的所有s lookupPrintServices,但URI不在任何属性中.打印机名称在那里,但我需要URI.

对于后台,我的webapp需要根据当前用户将条形码打印到特定的打印机.每个用户都与一个打印机URI相关联,该URI指向CUPS服务器上的打印机.打印机URI是我唯一的信息,我不能限制打印机名称以匹配URI或URI的子字符串.

编辑:为了澄清一点,我不需要渲染数据,我只需要将blob复制到给定的打印机.我无法弄清楚的部分是如何通过其IPP URI识别打印机.

Jas*_*Day 13

我终于找到了一种方法,通过使用jipsi:

URI printerURI = new URI("ipp://SERVER:631/printers/PRINTER_NAME");
IppPrintService svc = new IppPrintService(printerURI);
InputStream stream = new BufferedInputStream(new FileInputStream("image.epl"));
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc myDoc = new SimpleDoc(stream, flavor, null);
DocPrintJob job = svc.createPrintJob();
job.print(myDoc, null);
Run Code Online (Sandbox Code Playgroud)

我不得不承认,我很遗憾不得不使用第三方库做一些看似简单的事情,比如打印到特定的打印机.

UPDATE

DR在评论中指出jipsi有一个新家和一个新名字.

Cups4J是一个不错的选择,但顾名思义,如果目的地不是CUPS服务器,它可能无法正常工作.使用Cups4J直接打印到Zebra热敏打印机,我取得了很好的效果.

  • 现在可以通过https://github.com/bhagyas/jspi获得新重构和Mavenized版本的JSPI. (3认同)