如何访问打印机的状态?

IT小君   2021-11-14T06:23:23

我需要知道打印机状态。我需要使用 Java 程序控制打印机状态。例子

  1. 检查打印机状态,天气是否接受作业,
  2. 没纸了
  3. 打印机队列
  4. 碳粉
  5. 等等..

我知道有一种方法可以检查基本信息,例如名称、颜色是否支持。但我找不到任何检查纸张、碳粉、作业队列的示例。我想知道是否可以使用 Java API。我找到了打印机功能的大 API,但他们没有给出如何使用它的简单示例。

评论(4)
IT小君

看看这个PrinterStateReason还有javax.print

2021-11-14T06:23:23   回复
IT小君

获取打印机的完整状态是不可能的。打印机有一个能够请求服务的本机驱动程序,但是因为有很多可能的打印机功能,Java 只支持它的一个子集。

您实际上可以通过调用让用户修改状态

PrinterJob pj = PrinterJob.getPrinterJob();
pj.printDialog()

它显示了本机打印机对话框。尽管 javax.print API 中的信息表明可以检查打印机状态,但我无法为我的打印机这样做(佳能)。

检查代码:

import javax.print.*;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.PrintServiceAttributeSet;
import javax.print.attribute.standard.PrinterStateReason;
import javax.print.attribute.standard.PrinterStateReasons;
import javax.print.attribute.standard.Severity;
import javax.print.event.*;
import java.awt.*;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.*;
import java.util.Set;

/**
 * PrintTest
 */
public class PrintTest implements PrintServiceAttributeListener,PrintJobListener,Doc, Printable, PrintJobAttributeListener {

  private static final transient String TEXT = "12345";

  public static void main(String[] args) {
    PrintTest test = new PrintTest();
    test.checkPrinters();
  }

  public void checkPrinters() {
    Thread newThread = new Thread(new Runnable() {
      public void run() {
    PrintService ps = PrinterJob.getPrinterJob().getPrintService();

    DocFlavor[] myFlavors = ps.getSupportedDocFlavors();
    ps.addPrintServiceAttributeListener(PrintTest.this);
    DocPrintJob docJob = ps.createPrintJob();
      docJob.addPrintJobAttributeListener(PrintTest.this, null);
    docJob.addPrintJobListener(PrintTest.this);
    try {
      docJob.print(PrintTest.this,null);
    }
    catch (PrintException e) {
      e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }
    } });

    newThread.start();
    /**
    PrintServiceAttributeSet attSet = ps.getAttributes();
    PrinterStateReasons psr = ps.getAttribute(PrinterStateReasons.class);

    if (psr != null) {
      Set<PrinterStateReason> errors = psr.printerStateReasonSet(Severity.REPORT);
      for (PrinterStateReason reason : errors)
        System.out.printf(" Reason : %s",reason.getName());
      System.out.println();
    }          */
  }

  public void attributeUpdate(PrintServiceAttributeEvent psae) {
    System.out.println(psae.getAttributes());
  }

  public void printDataTransferCompleted(PrintJobEvent pje) {
    System.out.println("Transfer completed");
  }

  public void printJobCompleted(PrintJobEvent pje) {
    System.out.println("Completed");
  }

  public void printJobFailed(PrintJobEvent pje) {
    System.out.println("Failed");
    PrinterStateReasons psr = pje.getPrintJob().getPrintService().getAttribute(PrinterStateReasons.class);
    if (psr != null) {
      Set<PrinterStateReason> errors = psr.printerStateReasonSet(Severity.REPORT);
      for (PrinterStateReason reason : errors)
        System.out.printf(" Reason : %s",reason.getName());
      System.out.println();
    }
  }

  public void printJobCanceled(PrintJobEvent pje) {
    System.out.println("Canceled");
  }

  public void printJobNoMoreEvents(PrintJobEvent pje) {
    System.out.println("No more events");
  }

  public void printJobRequiresAttention(PrintJobEvent pje) {
    System.out.println("Job requires attention");
    PrinterStateReasons psr = pje.getPrintJob().getPrintService().getAttribute(PrinterStateReasons.class);
    if (psr != null) {
      Set<PrinterStateReason> errors = psr.printerStateReasonSet(Severity.REPORT);
      for (PrinterStateReason reason : errors)
        System.out.printf(" Reason : %s",reason.getName());
      System.out.println();
    }
  }

  public DocFlavor getDocFlavor() {
    return DocFlavor.SERVICE_FORMATTED.PRINTABLE;  //To change body of implemented methods use File | Settings | File Templates.
  }

  public Object getPrintData() throws IOException {
    return this;
  }

  public DocAttributeSet getAttributes() {
    return null;  //To change body of implemented methods use File | Settings | File Templates.
  }

  public Reader getReaderForText() throws IOException {
    return null; //To change body of implemented methods use File | Settings | File Templates.
  }

  public InputStream getStreamForBytes() throws IOException {
    return null;  //To change body of implemented methods use File | Settings | File Templates.
  }

  public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
    return pageIndex == 0 ? PAGE_EXISTS : NO_SUCH_PAGE;  //To change body of implemented methods use File | Settings | File Templates.
  }

  public void attributeUpdate(PrintJobAttributeEvent pjae) {
    System.out.println("Look out");
  }
}

我试图通过故意打开箱子或取出纸张来获得 PrinterReasonsState,但我没有成功。也许其他人可以展示它是如何可能的,但到目前为止,API 似乎提供了更多实际上不可用的功能。

或者简而言之:它不起作用,至少不适用于我的打印机。

2021-11-14T06:23:23   回复
IT小君

有人告诉我可以通过这种方式检查打印机状态:

PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
AttributeSet attributes = printService.getAttributes();
String printerState = attributes.get(PrinterState.class).toString();
String printerStateReason = attributes.get(PrinterStateReason.class).toString();

System.out.println("printerState = " + printerState); // May be IDLE, PROCESSING, STOPPED or UNKNOWN
System.out.println("printerStateReason = " + printerStateReason); // If your printer state returns STOPPED, for example, you can identify the reason 

if (printerState.equals(PrinterState.STOPPED.toString()) {

    if (printerStateReason.equals(PrinterStateReason.TONER_LOW.toString()) {

        System.out.println("Toner level is low.");
    }
}

遗憾的是,我的打印机似乎不支持 printerState,因此我无法对其进行测试。

2021-11-14T06:23:24   回复
IT小君

更新: 我建议不要像这样直接使用 Powershell,而不是查询 WMI“win32_printer”对象,它的 API 更简洁:

Get-Printer | where PrinterStatus -like 'Normal' | fl

查看所有打印机和状态:

Get-Printer | fl Name, PrinterStatus

要查看所有属性:

Get-Printer | fl

您仍然可以在 Java 中使用 ProcessBuilder,如下所述。

更新前:

仅适用于 Windows 的解决方案。在 Windows 中,您可以查询 WMI "win32_printer" 类,因此您可以检查 OS 层上的状态:Win32_Printer 类

在 Java 中,您可以像这样使用 ProcessBuilder 来启动 PowerShell 并像这样执行 PS 脚本:

String printerName = "POS_PRINTER";
ProcessBuilder builder = new ProcessBuilder("powershell.exe", "get-wmiobject -class win32_printer | Select-Object Name, PrinterState, PrinterStatus | where {$_.Name -eq '"+printerName+"'}");

String fullStatus = null;
Process reg;
builder.redirectErrorStream(true);
try {
    reg = builder.start();
    fullStatus = getStringFromInputStream(reg.getInputStream());
    reg.destroy();
} catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}
System.out.print(fullStatus);

将 InputStream 转换为 String 后,您应该得到如下内容:

Name        PrinterState PrinterStatus
----        ------------ -------------
POS_PRINTER            0             3

State 和 Status 应该在各种情况下发生变化(打印机关闭、缺纸、盖子打开……)。

这应该有效,但取决于打印机和驱动程序。我将它与带有 ESDPRT 端口的 EPSON TM 打印机一起使用,我可以获得如下信息:无纸、盖子打开、打印机离线/关闭、打印机暂停。

更全面的答案在这里: -我在类似问题上的 StackOverflow 回答

2021-11-14T06:23:24   回复