How to access the status of the printer?

前端 未结 4 1779
醉酒成梦
醉酒成梦 2020-12-03 20:03

I need to know the Printer Status. I need to control the Printer Status using Java Program. Example

  1. Check the Printer status, weather will it accept the Job
4条回答
  •  盖世英雄少女心
    2020-12-03 20:28

    UPDATE: Instead of querying WMI "win32_printer" object I would recommend using Powershell directly like this, its much cleaner API :

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

    To see all the printers and statuses:

    Get-Printer | fl Name, PrinterStatus
    

    To see all the attributes:

    Get-Printer | fl
    

    You can still use ProcessBuilder in Java as described below.

    Before update:

    Solution for Windows only. In Windows you can query WMI "win32_printer" class, so you check that the state on OS layer: Win32_Printer class

    In Java you can use ProcessBuilder like this to start PowerShell and execute the PS script like this:

    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);
    

    After converting the InputStream to String you should get something like that:

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

    State and Status should change for various situations (printer turned off, out of paper, cover opened,...).

    This should work, but depends on the printer and drivers. I used this with EPSON TM printers with ESDPRT port and I could get information like: no paper, cover open, printer offline/turned off, printer paused.

    More comprehensive answer here: - my StackOverflow answer on a similar question.

提交回复
热议问题