", "printerSize": 58}
13 | ```
14 | This will print the value of **content** passed json using the printer with name **Epson**.
15 | Printer Size is used to set the value of **divider** and **Horizontal Tab**.
16 |
17 |
18 | ----------
19 | ## Available Tags
20 |
21 | | Tag | Value |
22 | | ------------- | ------------- |
23 | | CTL_LF | Print and line feed |
24 | | CAN_HT | Cancel Horizontal Tab |
25 | | HT | Horizontal Tab |
26 | | LINE_SPACE_24 | Set the line spacing at 24 |
27 | | LINE_SPACE_30 | Set the line spacing at 30 |
28 | | SELECT_BIT_IMAGE_MODE | Image |
29 | | HW_INIT | Printer hardware Clear data in buffer and reset modes |
30 | | CD_KICK_2 | Cash Drawer Sends a pulse to pin 2 |
31 | | CD_KICK_5 | Cash Drawer Sends a pulse to pin 5 |
32 | | PAPER_FULL_CUT | Full cut paper |
33 | | PAPER_PART_CUT | Partial cut paper |
34 | | TXT_NORMAL | Normal text |
35 | | TXT_2HEIGHT | Double height text |
36 | | TXT_2WIDTH | Double width text |
37 | | TXT_4SQUARE | Quad area text |
38 | | TXT\_UNDERL\_OFF | Underline font OFF |
39 | | TXT\_UNDERL\_ON | Underline font 1-dot ON |
40 | | TXT\_UNDERL2\_ON | Underline font 2-dot ON |
41 | | TXT\_BOLD\_OFF | Bold font OFF |
42 | | TXT\_BOLD\_ON | Bold font ON |
43 | | TXT\_FONT\_A | Font type A |
44 | | TXT\_FONT\_B | Font type B |
45 | | TXT\_ALIGN\_LT | Left justification |
46 | | TXT\_ALIGN\_CT | Center justification |
47 | | TXT\_ALIGN\_RT | Right justification |
48 | | LEFT_MARGIN | Left Margin |
49 | | TWO_HT | Two Horizontal Tabs |
50 | | THREE_HT | Three Horizontal Tabs |
51 | | DIV | Divider Line |
52 |
53 | ----------
54 |
55 | ## ScreenShots
56 |
57 | > Sits nicely in task bar
58 |
59 | 
60 |
61 |
62 | > Logs commands sent
63 |
64 | 
--------------------------------------------------------------------------------
/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/saurabh1e/Java-ESC-POS-Print/5b86d99b7d28257b1011ac387bf23a2367708a61/icon.png
--------------------------------------------------------------------------------
/printer.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/saurabh1e/Java-ESC-POS-Print/5b86d99b7d28257b1011ac387bf23a2367708a61/printer.png
--------------------------------------------------------------------------------
/screenshots/Screenshot_2018-03-10_11-05-07.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/saurabh1e/Java-ESC-POS-Print/5b86d99b7d28257b1011ac387bf23a2367708a61/screenshots/Screenshot_2018-03-10_11-05-07.png
--------------------------------------------------------------------------------
/screenshots/Screenshot_2018-03-10_11-06-05.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/saurabh1e/Java-ESC-POS-Print/5b86d99b7d28257b1011ac387bf23a2367708a61/screenshots/Screenshot_2018-03-10_11-06-05.png
--------------------------------------------------------------------------------
/src/HTTPServer.java:
--------------------------------------------------------------------------------
1 | import com.itextpdf.tool.xml.exceptions.RuntimeWorkerException;
2 | import com.sun.net.httpserver.HttpExchange;
3 | import com.sun.net.httpserver.HttpHandler;
4 | import com.sun.net.httpserver.HttpServer;
5 |
6 | import com.fasterxml.jackson.databind.JsonNode;
7 | import com.fasterxml.jackson.databind.ObjectMapper;
8 |
9 |
10 | import java.io.IOException;
11 | import java.io.InputStream;
12 | import java.io.OutputStream;
13 | import java.net.InetSocketAddress;
14 |
15 | public class HTTPServer {
16 | private Print dialog;
17 |
18 | public void main() throws Exception {
19 | dialog = new Print();
20 | dialog.setTrayIcon();
21 | try {
22 | // setup the socket address
23 | InetSocketAddress address = new InetSocketAddress(7655);
24 |
25 | // Initialize the HTTPS server
26 | HttpServer httpServer = HttpServer.create(address, 0);
27 | httpServer.createContext("/", new MyHandler());
28 | httpServer.setExecutor(null); // creates a default executor
29 | httpServer.start();
30 |
31 | dialog.addLog("Print Server Started on port 7655", "INFO");
32 | dialog.pack();
33 | dialog.setVisible(true);
34 |
35 | } catch (Exception exception) {
36 | dialog.addLog("Failed to create HTTPS server on port 7655 of localhost", "ERROR");
37 | exception.printStackTrace();
38 |
39 | }
40 | }
41 |
42 | public class MyHandler implements HttpHandler {
43 | @Override
44 | public void handle(HttpExchange t) throws IOException {
45 | dialog.addLog("Serving Request", "DEBUG");
46 | String response = "This is the response";
47 | t.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
48 | t.getResponseHeaders().add("Access-Control-Allow-Headers", "Authorization");
49 | t.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-type");
50 | t.sendResponseHeaders(200, response.length());
51 |
52 | StringBuilder payload = new StringBuilder();
53 |
54 |
55 | InputStream is = t.getRequestBody();
56 | int rByte;
57 | while ((rByte = is.read()) != -1) {
58 | payload.append((char) rByte);
59 | }
60 | is.close();
61 | ObjectMapper mapper = new ObjectMapper();
62 |
63 | if (payload.length() > 1) try {
64 |
65 | JsonNode p = mapper.readTree(payload.toString());
66 | try {
67 | dialog.addLog("Printing using printer " + p.get("nameOfPrinter").asText(), "INFO");
68 |
69 | PrinterConfig pc = new PrinterConfig();
70 |
71 | pc.setSize(p.get("printerSize").asInt(80));
72 |
73 | String content;
74 | content = pc.getFormattedString(p.get("content").asText());
75 |
76 | dialog.printUsingPrinter(p.get("nameOfPrinter").asText(), content);
77 |
78 | } catch (RuntimeWorkerException | NullPointerException
79 | arg11) {
80 | arg11.printStackTrace();
81 | dialog.addLog(arg11.toString(), "ERROR");
82 |
83 | }
84 |
85 | } catch (Exception arg) {
86 | dialog.addLog(arg.toString(), "ERROR");
87 |
88 | }
89 | OutputStream os = t.getResponseBody();
90 | os.write(response.getBytes());
91 | os.close();
92 | }
93 |
94 |
95 | }
96 |
97 | }
98 |
--------------------------------------------------------------------------------
/src/META-INF/MANIFEST.MF:
--------------------------------------------------------------------------------
1 | Manifest-Version: 1.0
2 | Main-Class: Main
3 |
4 |
--------------------------------------------------------------------------------
/src/Main.java:
--------------------------------------------------------------------------------
1 | public class Main {
2 |
3 | public static void main(String[] args) {
4 | try {
5 | new HTTPServer().main();
6 | } catch (Exception e) {
7 | e.printStackTrace();
8 | }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/Print.form:
--------------------------------------------------------------------------------
1 |
2 |
141 |
--------------------------------------------------------------------------------
/src/Print.java:
--------------------------------------------------------------------------------
1 | import javax.print.*;
2 | import javax.print.attribute.AttributeSet;
3 | import javax.swing.*;
4 | import java.awt.*;
5 | import java.awt.event.*;
6 | import java.awt.TrayIcon.MessageType;
7 |
8 |
9 | public class Print extends JDialog {
10 | private JPanel contentPane;
11 | private JButton buttonOK;
12 | private JButton buttonCancel;
13 | private JList
list1;
14 | private JList list2;
15 | private DefaultListModel listModel = new DefaultListModel<>();
16 | private TrayIcon trayIcon;
17 |
18 | Print() {
19 | list1.setLayoutOrientation(JList.HORIZONTAL_WRAP);
20 | list1.setModel(getPrinterListModel());
21 | list2.setModel(listModel);
22 |
23 | setContentPane(contentPane);
24 | setModal(true);
25 | getRootPane().setDefaultButton(buttonOK);
26 |
27 |
28 | buttonOK.addActionListener(new ActionListener() {
29 | public void actionPerformed(ActionEvent e) {
30 | onOK();
31 | }
32 | });
33 |
34 | buttonCancel.addActionListener(new ActionListener() {
35 | public void actionPerformed(ActionEvent e) {
36 | onCancel();
37 | }
38 | });
39 |
40 | // call onCancel() when cross is clicked
41 | setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
42 | addWindowListener(new WindowAdapter() {
43 | public void windowClosing(WindowEvent e) {
44 | onCancel();
45 | }
46 | });
47 |
48 | // call onCancel() on ESCAPE
49 | contentPane.registerKeyboardAction(new ActionListener() {
50 | public void actionPerformed(ActionEvent e) {
51 | onCancel();
52 | }
53 | }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
54 | }
55 |
56 | private static DefaultListModel getPrinterListModel() {
57 |
58 | DefaultListModel listModel = new DefaultListModel<>();
59 | PrintService[] findAllPrinters = findAllPrinters();
60 | for (int i = 0; i < findAllPrinters.length; i++) {
61 | PrintService printService = findAllPrinters[i];
62 | listModel.addElement((i+1) + ". " + printService.getName());
63 | }
64 |
65 | return listModel;
66 | }
67 |
68 | private void onOK() {
69 | // add your code here
70 | dispose();
71 | }
72 |
73 | private void onCancel() {
74 | // add your code here if necessary
75 | dispose();
76 | System.exit(0);
77 | }
78 |
79 | private PrintService findPrinterByName(String printerName) {
80 | PrintService[] printServices = findAllPrinters();
81 |
82 | for (PrintService printService : printServices) {
83 | if (printService.getName().trim().equals(printerName)) {
84 | return printService;
85 | }
86 | }
87 |
88 | return PrintServiceLookup.lookupDefaultPrintService();
89 | }
90 |
91 | private static PrintService[] findAllPrinters() {
92 | return PrintServiceLookup.lookupPrintServices((DocFlavor) null, (AttributeSet) null);
93 | }
94 |
95 | public boolean printUsingPrinter(String printerName, String content) throws PrintException {
96 | PrintService printer = findPrinterByName(printerName);
97 | DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
98 | DocPrintJob job = printer.createPrintJob();
99 | Doc doc = new SimpleDoc(content.getBytes(),flavor,null);
100 | job.print(doc, null);
101 | addLog("Print Successful", "DEBUG");
102 | return true;
103 | }
104 |
105 | public void addLog(String log, String type) {
106 | listModel.addElement(type + ": " + log);
107 | if (type.equals("INFO")) {
108 | trayIcon.displayMessage("Print Utility", log, MessageType.INFO);
109 | }
110 | if (type.equals("ERROR")) {
111 | trayIcon.displayMessage("Print Utility", log, MessageType.ERROR);
112 | }
113 | }
114 |
115 | public void setTrayIcon() throws AWTException {
116 | SystemTray tray = SystemTray.getSystemTray();
117 |
118 | //If the icon is a file
119 | Image image = Toolkit.getDefaultToolkit().createImage("printer.png");
120 | //Alternative (if the icon is on the classpath):
121 | //Image image = Toolkit.getToolkit().createImage(getClass().getResource("icon.png"));
122 |
123 | trayIcon = new TrayIcon(image, "Print Utility");
124 | //Let the system resize the image if needed
125 | trayIcon.setImageAutoSize(true);
126 | //Set tooltip text for the tray icon
127 | trayIcon.setToolTip("Print Utility");
128 | tray.add(trayIcon);
129 |
130 | trayIcon.addMouseListener(new MouseAdapter() {
131 | @Override
132 | public void mouseClicked(MouseEvent e) {
133 | super.mouseClicked(e);
134 | setAlwaysOnTop(true);
135 | setVisible(true);
136 | }
137 | });
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/src/PrinterConfig.java:
--------------------------------------------------------------------------------
1 | import java.io.UnsupportedEncodingException;
2 | import java.util.ArrayList;
3 | import java.util.HashMap;
4 | import java.util.List;
5 | import java.util.regex.Matcher;
6 | import java.util.regex.Pattern;
7 |
8 | public class PrinterConfig {
9 |
10 | public final byte[] CTL_LF = {0x0a}; // Print and line feed
11 | public static final byte[] CAN_HT = {0x1b, 0x44, 0x00}; // Cancel Horizontal Tab
12 | public static final byte[] HT = {0x09}; // Horizontal Tab
13 | public static final byte[] LINE_SPACE_24 = {0x1b, 0x33, 24}; // Set the line spacing at 24
14 | public static final byte[] LINE_SPACE_30 = {0x1b, 0x33, 30}; // Set the line spacing at 30
15 | //Image
16 | public static final byte[] SELECT_BIT_IMAGE_MODE = {0x1B, 0x2A, 33};
17 | // Printer hardware
18 | public static final byte[] HW_INIT = {0x1b, 0x40}; // Clear data in buffer and reset modes
19 | // Cash Drawer
20 | public static final byte[] CD_KICK_2 = {0x1b, 0x70, 0x00}; // Sends a pulse to pin 2 []
21 | public static final byte[] CD_KICK_5 = {0x1b, 0x70, 0x01}; // Sends a pulse to pin 5 []
22 | // Paper
23 | public static final byte[] PAPER_FULL_CUT = {0x1d, 0x56, 0x00}; // Full cut paper
24 | public static final byte[] PAPER_PART_CUT = {0x1d, 0x56, 0x01}; // Partial cut paper
25 | // Text format
26 | public static final byte[] TXT_NORMAL = {0x1b, 0x21, 0x00}; // Normal text
27 | public static final byte[] TXT_2HEIGHT = {0x1b, 0x21, 0x10}; // Double height text
28 | public static final byte[] TXT_2WIDTH = {0x1b, 0x21, 0x20}; // Double width text
29 | public static final byte[] TXT_4SQUARE = {0x1b, 0x21, 0x30}; // Quad area text
30 | public static final byte[] TXT_UNDERL_OFF = {0x1b, 0x2d, 0x00}; // Underline font OFF
31 | public static final byte[] TXT_UNDERL_ON = {0x1b, 0x2d, 0x01}; // Underline font 1-dot ON
32 | public static final byte[] TXT_UNDERL2_ON = {0x1b, 0x2d, 0x02}; // Underline font 2-dot ON
33 | public static final byte[] TXT_BOLD_OFF = {0x1b, 0x45, 0x00}; // Bold font OFF
34 | public static final byte[] TXT_BOLD_ON = {0x1b, 0x45, 0x01}; // Bold font ON
35 | public static final byte[] TXT_FONT_A = {0x1b, 0x4d, 0x00}; // Font type A
36 | public static final byte[] TXT_FONT_B = {0x1b, 0x4d, 0x01}; // Font type B
37 | public static final byte[] TXT_ALIGN_LT = {0x1b, 0x61, 0x00}; // Left justification
38 | public static final byte[] TXT_ALIGN_CT = {0x1b, 0x61, 0x01}; // Centering
39 | public static final byte[] TXT_ALIGN_RT = {0x1b, 0x61, 0x02}; // Right justification
40 | public static final byte[] LEFT_MARGIN = {0x1b, 0x6c, 0x08}; // Left Margin
41 |
42 | public byte[] TWO_HT = new byte[]{};
43 | public byte[] THREE_HT = new byte[]{};
44 | public String DIV = "";
45 | public HashMap code = new HashMap();
46 |
47 | private static String getCode(byte[] code) {
48 |
49 | try {
50 | return new String(code, "UTF-8");
51 | } catch (UnsupportedEncodingException e) {
52 | // TODO Auto-generated catch block
53 | e.printStackTrace();
54 | }
55 |
56 | return "";
57 | }
58 |
59 | public void setSize(Integer size) {
60 | switch (size) {
61 | case (80): {
62 | TWO_HT = new byte[]{0x1b, 0x44, 0x16, 0x24, 0x00};
63 | THREE_HT = new byte[]{0x1b, 0x44, 0x20, 0x28, 0x36, 0x00};
64 | DIV = "----------------------------------------------";
65 | break;
66 | }
67 | case (72): {
68 | TWO_HT = new byte[]{0x1b, 0x44, 0x10, 0x16, 0x00};
69 | THREE_HT = new byte[]{0x1b, 0x44, 0x14, 0x20, 0x25, 0x00};
70 | DIV = "---------------------------------------";
71 | break;
72 | }
73 | case (58): {
74 | TWO_HT = new byte[]{0x1b, 0x44, 0x08, 0x16, 0x00};
75 | THREE_HT = new byte[]{0x1b, 0x44, 0x12, 0x16, 0x25, 0x00};
76 | DIV = "-----------------------------------";
77 | break;
78 | }
79 | }
80 | }
81 |
82 | public String getFormattedString(String content) {
83 |
84 | String pattern = "<(.|\\n)+?>";
85 | List allMatches = new ArrayList<>();
86 |
87 | // Create a Pattern object
88 | Pattern r = Pattern.compile(pattern);
89 |
90 | // Now create matcher object.
91 | Matcher m = r.matcher(content);
92 | while (m.find()) {
93 | allMatches.add(m.group(0));
94 | }
95 |
96 | for (String allMatch : allMatches) {
97 | String code = allMatch;
98 | try {
99 | if (code.substring(1, code.length() - 1).equals("DIV")) {
100 | code = (String) ReflectUtils.getValueOf(this, code.substring(1, code.length() - 1));
101 | } else {
102 | code = getCode((byte[]) ReflectUtils.getValueOf(this, code.substring(1, code.length() - 1)));
103 | }
104 |
105 | } catch (Exception e) {
106 | e.printStackTrace();
107 | }
108 | content = content.replaceFirst(allMatch, code);
109 | }
110 | return content;
111 | }
112 |
113 | }
114 |
115 |
--------------------------------------------------------------------------------
/src/ReflectUtils.java:
--------------------------------------------------------------------------------
1 | import java.lang.reflect.Field;
2 |
3 | public class ReflectUtils {
4 |
5 | private ReflectUtils (){ }
6 |
7 | @SuppressWarnings("rawtypes")
8 | public static Object getValueOf(Object clazz, String lookingForValue)
9 | throws Exception {
10 | Field field = clazz.getClass().getField(lookingForValue);
11 | Class clazzType = field.getType();
12 | if (clazzType.toString().equals("double"))
13 | return field.getDouble(clazz);
14 | else if (clazzType.toString().equals("int"))
15 | return field.getInt(clazz);
16 | // else other type ...
17 | // and finally
18 | return field.get(clazz);
19 | }
20 |
21 | public static void main(String[] args) throws Exception{
22 |
23 | }
24 |
25 |
26 | }
27 |
--------------------------------------------------------------------------------