Print Chinese text to network-enabled thermal receipt printer using Java

For more information on the ESC/POS command set which receipt printers use for printing, see What is ESC/POS and How Do I Use It by Michael Billington, also the author of the excellent escpos-php PHP library for receipt printers.

Steps to run:

  1. Save the code below as NetworkReceiptPrinter.java – change printer IP accordingly.
  2. Run javac -encoding utf8 NetworkReceiptPrinter.java to compile. The encoding option is required else there will be a compilation error due to the Chinese text in the file – “error: unmappable character for encoding Cp1252”.
  3. java NetworkReceiptPrinter
import java.io.*;
import java.net.*;

class NetworkReceiptPrinter {
    public static void main(String argv[]) throws Exception {
        String str = "\n\n一二三四五六七八九十 1234567890"; // start str on new line
        String encoding = "GBK";
        String printerIp = "192.168.1.123";
        int printerPort = 9100;

        try {
            Socket socket = new Socket(printerIp, printerPort);
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            DataInputStream in = new DataInputStream(new ByteArrayInputStream(str.getBytes(encoding)));

            out.writeByte(0x1C);
            out.writeBytes("&");

            while (in.available() != 0) {
                out.write(in.readByte());
            }

            out.writeByte(0x1C);
            out.writeBytes(".");
            out.writeByte(0x00); // terminate line else str may be cut off and appear in next printout
            out.flush();

            out.close();
            in.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}