Search code examples
javaandroidprintingthermal-printer

Command for thermal printer in java


i have a set of command to use for my thermal printer: this is an example

ASCII ESC a n
Decimal 27 97 n
Hexadecimal 1B 61 n

Description Default is 0
0 ≤ m ≤ 2 or 48 ≤ m ≤ 50
Align left: n=0,48
Align middle: n=1,49
Align right: n=2,50 

I want to know how to use this command?? i know that i need to write into the printer the command like this:

   byte [] cmd = new byte[3];
   cmd[0]=??
   cmd[1]???
    mmOutputStream.write(cmd);//out put stream of soccket connected to
    //printer by bluetooth

For more explanation: i want to add command to my printer to make text appear in center


Solution

  • Here, in Hex and plain, a sample sequence of character codes as you can send it to your printer so that text will be left-aligned, centered and right-aligned. Escape sequences are simply embedded in the regular text.

    1b 40 
    1b 61 00 This is left-aligned 0a
    1b 61 01 This is centered 0a
    1b 61 02 This is right-aligned 0a
    

    The initial ESC @ resets formatting.

    I don't know what 48, 49, 50 will produce, but a similar experiment should tell you.

    To write an escape sequence you store it in a byte array and write it, as you would regular text:

    byte[] center = new byte[]{ 0x1b, 0x61, 0x01 };
    outputStream.write( center );
    outputStream.write( "This is centered\n".getBytes() );
    

    And you can "wrap" a PrintWriter around your OutputStream, which makes everything simple:

    // next stmt according to OP
    BufferedWriter bw =new OutputStreamWriter( otputStream, "8859_6" );
    PrintWriter pw = new PrintWriter( bw, true );
    String center = "\u001b\u0061\u0001";
    pw.println( center + "This is centered" );