如何使用escpos-2.2 jar和jSerialComm-2.5.0 jar在热敏接收打印机上打印收据

时间:2019-08-10 08:31:30

标签: java escpos

我正在用Java构建POS桌面应用程序,该应用程序使用热敏打印机打印交易收据。我发现可以使用escpos和JSerialComm Java API来实现此目的。我从GitHub复制了示例代码以尝试使用API​​。下面是应该起作用的代码,但返回NullPointerExceptionError。

我不知道我在做什么错。因此,我该怎么做才能至少打印出“ Hello World”,以查看我的应用程序是否可以真正进入打印机。救命!


package com;

import com.fazecast.jSerialComm.SerialPort;
import com.github.terrytsai.escpos.EscPosWriter;
import com.github.terrytsai.escpos.enums.CharacterCodeTable;
import com.github.terrytsai.escpos.enums.CutA;
import com.github.terrytsai.escpos.enums.Height;
import com.github.terrytsai.escpos.enums.Justification;
import com.github.terrytsai.escpos.enums.Pin;
import com.github.terrytsai.escpos.enums.PulseTime;
import com.github.terrytsai.escpos.enums.Width;
import com.github.terrytsai.escpos.serial.SerialFactory;
import com.github.terrytsai.escpos.serial.config.SerialConfig;
import java.io.OutputStream;

public class PrinterClass {

    private static PrinterClass printer = null;
    private static  OutputStream out;
    private static EscPosWriter escPos;

    private PrinterClass(){
        initSerial();
    }

    protected static void writeReceipt(){
        System.out.println("Receipt started...");
        escPos = new EscPosWriter(out)
        .initialize()
        .setCharacterCodeTable(CharacterCodeTable.PC437)
        .setJustification(Justification.CENTER)
        .setCharacterSize(Width.X3, Height.X3)
        .setEmphasize(true)
        .text("HELLO WORLD")
        .printAndFeedLines(5)
        .cut(CutA.PARTIAL)
        .sendRealTimeRequestPulse(Pin.TWO, PulseTime.FOUR);
        System.out.println("Receipt done!");
    }

    private static PrinterClass getInstance(){
        if(printer == null){
            printer = new PrinterClass();
        }
        return printer;
    }

    private void initSerial(){
        SerialPort port = SerialFactory.com(3, SerialConfig.CONFIG_9600_8N1());
        port.openPort();
        out = port.getOutputStream();
        port.closePort();
      }

    public static void main(String [] args){
        PrinterClass pc = PrinterClass.getInstance();
        pc.writeReceipt();
    }
}

“我希望它能打印收据。但是我收到一个错误:”

Exception in thread "main" java.lang.NullPointerException
    at com.github.terrytsai.escpos.EscPosWriter.write(EscPosWriter.java:1345)
    at com.github.terrytsai.escpos.EscPosWriter.initialize(EscPosWriter.java:1213)
    at com.PrinterClass.writeReceipt(PrinterClass.java:30)
    at com.PrinterClass.main(PrinterClass.java:58)

1 个答案:

答案 0 :(得分:0)

PC上通常有服务器的COM端口,尝试找出哪个是打印机的端口,不一定是3。相应地更新initSerial方法。