Search code examples
javacmdportsescpos

How to send ESC/POS commands to an usb printer?


My objective is opening a cash drawer programatically, but I didn't found detailed information about how Java interact with Windows ports so I couldn't get it working. These are the methods I tried(no errors in Java console):

public void cashdrawerOpen()   {

    String code1 = "27 112 0 150 250"; //decimal
    String code2 = "1B 70 00 96 FA"; //hexadecimal
    String code = "ESCp0û."; //ascii

     PrintService service = PrintServiceLookup.lookupDefaultPrintService();
     System.out.println(service.getName());
     DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
    DocPrintJob pj = service.createPrintJob();
     byte[] bytes;
     bytes=code2.getBytes();
     Doc doc=new SimpleDoc(bytes,flavor,null);
      try {
        pj.print(doc, null);
    } catch (PrintException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}


public void cashdrawerOpen2(){
    String code1 = "27 112 0 150 250";
    String code2 = "1B 70 00 96 FA";
    String code = "ESCp0û.";
    FileOutputStream os = null;
    try {
        os = new FileOutputStream("USB001:POS-58");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
      PrintStream ps = new PrintStream(os);
      ps.print(code1.getBytes());
      ps.close();
}

Then I started playing with cmd, specifically following this thread, but when I execute the command 'copy /b open.bat USB001' it just says: 'overwrite USB001 ? (yes/no/all)'

Any idea?


Solution

  • Solved.

    I didn't found how to send commands over USB, I had to emulate LPT ports.

    If your printer comes with a driver named TM Virtual Port Driver or something similar(in my case):

    1. Install it and configure printer connection with the GUI.
    2. Make use of Java methods

    If not:

    1. Share the printer in the control panel.
    2. Open cmd as admin
    3. NET USE LPT1 \[Computer-Name]\Printer /Persistent:Yes (doesn't work in win8.1)
    4. from Java:

      public void cashdrawerOpen(){ 
          String code2 = "1B700096FA"; // my code in hex
          FileOutputStream os = null;
          try {
              os = new FileOutputStream("LPT1:POS-58");
          } catch (FileNotFoundException e) {
              e.printStackTrace();
          }
            PrintStream ps = new PrintStream(os);
          ps.print(toAscii(code2));
            ps.close();
      }
      
      public StringBuilder toAscii( String hex ){
      StringBuilder output = new StringBuilder();
      for (int i = 0; i < hex.length(); i+=2) {
      String str = hex.substring(i, i+2);
      output.append((char)Integer.parseInt(str, 16));
      }
       return output;
      
      }