打印机打印小票代码(附工具类,接口讲解和源码)

废话不多说,直接上源码

1.工具类 PrintDeviceUtil
package com.ncxp.easy.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 设备打印工具类
 */
public class PrintDeviceUtil {
    /**
     * 打印类
     * @param url   通讯地址
     * @param deviceNo 设备编号
     * @param key  秘钥
     * @param content 打印内容
     * @param times 打印次数
     * @throws IOException
     */
    public static JSONObject print(String url, String deviceNo, String key, String content, String times) throws IOException {
        Map<String, String> params= new HashMap<String, String>(16);
        params.put("deviceNo", deviceNo);
        params.put("key", key);
        params.put("printContent", content);
        params.put("times", times);
        String result = HttpClientTool.doPost(url + "/addOrder", params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }

    /**
     * 查看打印状态
     * @param url
     * @param deviceNo
     * @param key
     * @param orderindex
     * @return
     * @throws IOException
     */
    public static JSONObject printStatus(String url, String deviceNo, String key, String orderindex) throws IOException {
        Map<String, String> params= new HashMap<String, String>(16);
        params.put("deviceNo", deviceNo);
        params.put("key", key);
        params.put("orderindex", orderindex);
        String result = HttpClientTool.doPost(url + "/queryOrder", params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }

    /**
     * 查看设备,在线状态
     * @param url
     * @param deviceNo
     * @param key
     * @return
     */
//    public static JSONObject checkoutDeviceOnlinkStatus(String url, String deviceNo, String key) throws IOException {
//        Map<String, String> params= new HashMap<String, String>(16);
//        params.put("deviceNo", deviceNo);
//        params.put("key", key);
//        String result = HttpClientTool.doPost(url, params);
//        JSONObject jsonObject = JSONObject.parseObject(result);
//        return jsonObject;
//    }

}
2.核心代码

参考打印设备接口: http://open.printcenter.cn:8080/index.jsp

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
try {
JSONObject jsonObject = PrintDeviceUtil.print(url, shopDevices.getDeviceNo(),
shopDevices.getMkey(), content, shopDevices.getTimes() + “”);
String responseCode = jsonObject.getString(“responseCode”);
if (“0”.equals(responseCode)) {
//获取打印设备的订单索引
String orderindex = jsonObject.getString(“orderindex”);
JSONObject jsonObject1 = PrintDeviceUtil.printStatus(url, shopDevices.getDeviceNo(),
shopDevices.getMkey(), orderindex);
String responseCode1 = jsonObject1.getString(“responseCode”);
if (“0”.equals(responseCode1)) {

               if(orListChange != null){
                   //System.out.println("-----------------------"+orListChange.size()+"------------------------------------");
                   if( returnCount == orListChange.size() ){///
                       int count=0;
                       for(OrderInfo orderInfo2:orListChange){
                           if(orderInfo2.getShopPrint() == 0 ){
                               count += orderGoodsService.updateByInfoId(orderInfo2.getOrderId(), orderInfo2.getGoodsId());
                           }
                           else{
                               clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);
                               logger.error("商家端打印失败:订单中商品部分已经打印!" );
                           }
                       }
                       if(count == orListChange.size()){
                           /*System.out.println("====打印完之后的小票打印状态====" + orderGoodsService.getById(orderInfo.getId()).getShopPrint());
                           System.out.println("====控制台输出订单打印内容===="+content);*/
                           clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);
                           logger.info(content);
                           logger.info("商家端打印成功");
                       }else{
                           if(k==shopDevicesList.size()){clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);}
                           logger.error("商家端打印失败:订单中商品未全部成功修改打印状态!" );
                       }
                   }
                   else{
                       if(k==shopDevicesList.size()){clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);}
                       logger.error("商家端打印失败:订单中商品未全部录入待打印状态!" );
                   }
               }else{
                   if(k==shopDevicesList.size()){clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);}
                   logger.error("商家端打印失败:无符合订单!" );
               }

           } else {
               if(k==shopDevicesList.size()){clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);}
               logger.error("商家端打印失败:" + jsonObject1);
           }
       } else {
           if(k==shopDevicesList.size()){clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);}
           logger.error("商家端打印失败:" + jsonObject);
       }
   } catch (IOException e) {
       if(k==shopDevicesList.size()){clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);}
       logger.error("商家端打印失败:" + e.getMessage());
   }
3.源码(业务逻辑适当修改)
package com.ncxp.easy.scheduling;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ncxp.easy.admin.entity.OrderInfo;
import com.ncxp.easy.admin.entity.PlatformDevices;
import com.ncxp.easy.admin.entity.ShopDevices;
import com.ncxp.easy.admin.entity.SysUser;
import com.ncxp.easy.admin.service.IPlatformDevicesService;
import com.ncxp.easy.admin.service.IShopDevicesService;
import com.ncxp.easy.admin.service.IUserService;
import com.ncxp.easy.recycle.entity.Goods;
import com.ncxp.easy.recycle.entity.OrderGoods;
import com.ncxp.easy.recycle.entity.ShopOrder;
import com.ncxp.easy.recycle.entity.UserProp;
import com.ncxp.easy.recycle.service.IGoodsService;
import com.ncxp.easy.recycle.service.IOrderGoodsService;
import com.ncxp.easy.recycle.service.IShopOrderService;
import com.ncxp.easy.recycle.service.IUserPropService;
import com.ncxp.easy.util.PrintDeviceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 用于订单打印
 *
 * @author beiming
 */
@Configuration
public class GoodsOrderPrintScheduling {
    private static final Logger logger = LoggerFactory.getLogger(GoodsOrderPrintScheduling.class);

    @Value("${device.print.url}")
    public String url = "";

    @Autowired
    private IShopOrderService shopOrderService;
    @Autowired
    private IOrderGoodsService orderGoodsService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IUserPropService userPropService;
    @Autowired
    private IPlatformDevicesService platformDevicesService;
    @Autowired
    private IShopDevicesService shopDevicesService;
    @Autowired
    private IUserService  userService;
    @Autowired
    private IOrderGoodsService  OrderGoodsService;

   /**
     * 待付款订单,执行自动打印
     */

    @Scheduled(cron = "0/5 * * * * ?")
    public void cancelOrder() {
        logger.info("开始打印订单小票");
            QueryWrapper<ShopOrder> queryWrapper = new QueryWrapper<ShopOrder>();
            queryWrapper.eq("status", 2);
            queryWrapper.eq("print_status", 0);
            List<ShopOrder> shopOrderList = shopOrderService.list(queryWrapper);

        for (ShopOrder shopOrder : shopOrderList) {
            int num = 1;
            String content = "<CB>农村小铺</CB><BR>";
            content += "序号 名称        单价 数量";
            content += "--------------------------------<BR>";
            QueryWrapper<OrderGoods> queryOrderGoodsWrapper = new QueryWrapper<OrderGoods>();
            queryOrderGoodsWrapper.eq("order_id", shopOrder.getId());
            List<OrderGoods> orderGoodsList = orderGoodsService.list(queryOrderGoodsWrapper);
            for (OrderGoods orderGoods : orderGoodsList) {
                Goods goods = goodsService.getById(orderGoods.getGoodsid());
                if(goods!=null){
                    String stardardName = orderGoods.getStardardName();
                    if(stardardName == null || stardardName.equals("")){
                        content += num + " " + cutString(goods.getName()) + "   " + goods.getPrice()
                                + "  " + orderGoods.getBuynum() + "<BR>";
                    }else{
                        content += num + " " + cutString(goods.getName()+"/"+stardardName) + "   " + goods.getPrice()
                                + "  " + orderGoods.getBuynum() + "<BR>";
                    }
                    num++;
                }
            }
            content += "备注:" + shopOrder.getBak() + "<BR>";
            content += "--------------------------------<BR>";
            content += "合计:" + shopOrder.getPrice() + "元<BR>";
            UserProp prop = userPropService.getById(shopOrder.getAddressId());
            content += "订单编号:" + shopOrder.getOrderNo() + "<BR>";
            content += "送货地点:" + prop.getAddress() + "<BR>";
            content += "收货人:"   + prop.getUserName() + "<BR>";
            content += "联系电话:" + prop.getPhone() + "<BR>";
            content += "下单时间:" + shopOrder.getCreatetime() + "<BR>";

        QueryWrapper<PlatformDevices> queryPlatformDevicesWrapper = new QueryWrapper<PlatformDevices>();
        queryPlatformDevicesWrapper.eq("status", 1);
        List<PlatformDevices> platformDevicesList = platformDevicesService.list(queryPlatformDevicesWrapper);
        for (PlatformDevices platformDevices : platformDevicesList) {
            try {
                JSONObject jsonObject = PrintDeviceUtil.print(url, platformDevices.getDeviceNo(),
                        platformDevices.getMkey(), content, platformDevices.getTimes() + "");
                String responseCode = jsonObject.getString("responseCode");
                if ("0".equals(responseCode)) {
                    //获取打印设备的订单索引
                    String orderindex = jsonObject.getString("orderindex");
                    JSONObject jsonObject1 = PrintDeviceUtil.printStatus(url, platformDevices.getDeviceNo(),
                            platformDevices.getMkey(), orderindex);
                    String responseCode1 = jsonObject1.getString("responseCode");
                    if ("0".equals(responseCode1)) {
                        shopOrder.setPrintStatus(1);
                        shopOrderService.updateById(shopOrder);
                        logger.info(content);
                        logger.info("打印成功");
                    } else {
                        logger.error("打印失败:" + jsonObject1);
                    }

                } else {
                    logger.error("打印失败:" + jsonObject);
                }
            } catch (IOException e) {
                logger.error("打印失败:" + e.getMessage());
            }
        }
    }
    logger.info("打印结束");
}


/**
 * 待付款订单,打印给商家端
 */

@Scheduled(cron = "0/5 * * * * ?")
public  void shopCancelOrder(){
    logger.info("开始打印商家端订单小票");
    QueryWrapper<ShopOrder> queryWrapper = new QueryWrapper<ShopOrder>();
    queryWrapper.eq("status", 2);//待发货
    queryWrapper.eq("is_del",2);//未删除的
    List<ShopOrder> shopOrderList = shopOrderService.list(queryWrapper);  //得到订单表

    for (ShopOrder shopOrder : shopOrderList) {// 遍历订单表
        String content ="";
        List<OrderInfo> orderInfoList = orderGoodsService.selectShopIdAndOther(shopOrder.getId());  //只搜索打印状态为0的 ,可以得到商品id的

        for (int i =0 ; i< orderInfoList.size();) {
            int num = 1;

            List<OrderInfo> orListChange = new ArrayList<>();
            BigDecimal totalPrice = new BigDecimal(0);
            BigDecimal totalPrice2 = new BigDecimal(0);
            BigDecimal totalPriceTotal = new BigDecimal(0);

            OrderInfo orderInfo = orderInfoList.get(i);
            Goods goods = goodsService.getById(orderInfo.getGoodsId());
            Long shopId = goods.getShopId();
            int returnCount = orderGoodsService.selectByShopIdReturnCount(shopOrder.getId(), shopId);
            SysUser sysUser = userService.selectByPrimaryKey(shopId);
            int flag = 0;
            if(flag == 0){
                if(sysUser!=null){
                    content = "<CB>"+sysUser.getShopName()+"</CB><BR>";
                    content += "序号 名称        单价 数量 ";
                    content += "--------------------------------<BR>";
                    flag++;
                }
                else{logger.error("商家端打印失败:无此商家" );}
            }
            for (int j =i+1 ; j< orderInfoList.size(); j++){
                OrderInfo orderInfo1 = orderInfoList.get(j);
                Goods goods1 = goodsService.getById(orderInfo1.getGoodsId());
                Long shopId1 = goods1.getShopId();
                if(shopId1.equals(shopId) && goods1 != null && orderInfo1.getShopPrint()==0 ){
                    String stardardName = orderInfo1.getStardardName();
                    if(stardardName == null || stardardName.equals("")){
                        content += num + " " + cutString(goods1.getName()) + " " + orderInfo1.getUnitPrice()
                                + "  " + orderInfo1.getBuyNum() + "<BR>";
                    }else{
                        content += num + " " + cutString(goods1.getName()+"/"+stardardName) + " " + orderInfo1.getUnitPrice()
                                + "  " + orderInfo1.getBuyNum() + "<BR>";
                    }
                    num++;
                    i++;
                    orListChange.add(orderInfo1);
                    //System.out.println("--------------加入orListChange的orderInfo为shopid->"+orderInfo1.getShopId()+"商品id为"+orderInfo1.getGoodsId()+"----------------");
                    totalPrice = totalPrice.add(orderInfo1.getUnitPrice().multiply(new BigDecimal(orderInfo1.getBuyNum())));
                }
                else{ continue; }
            }
            if(goods != null ){
                if( orderInfo.getShopPrint()==0){
                    String stardardName = orderInfo.getStardardName();
                    if(stardardName == null || stardardName.equals("")){
                        content += num + " " + cutString(goods.getName()) + " " + orderInfo.getUnitPrice()
                                + "  " + orderInfo.getBuyNum() + "<BR>";
                    }else{
                        content += num + " " + cutString(goods.getName()+"/"+stardardName) + " " + orderInfo.getUnitPrice()
                                + "  " + orderInfo.getBuyNum() + "<BR>";
                    }
                    num++;
                    i++;
                    orListChange.add(orderInfo);
                    totalPrice2 = totalPrice2.add(orderInfo.getUnitPrice().multiply(new BigDecimal(orderInfo.getBuyNum())));
                }
            }
            else{
                clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);
                logger.error("商家端打印失败:无此商品 -> id: " + goods.getId() );
            }
            content += "备注:" + shopOrder.getBak() + "<BR>";
            content += "--------------------------------<BR>";
            totalPriceTotal= totalPrice.add(totalPrice2);
            content += "  合计: " + totalPriceTotal + "元<BR>";
            UserProp prop = userPropService.getById(shopOrder.getAddressId());
            content += "订单编号:" + shopOrder.getOrderNo() + "<BR>";
            content += "送货地点:" + prop.getAddress() + "<BR>";
            content += "收货人:  " + prop.getUserName() + "<BR>";
            content += "联系电话:" + prop.getPhone() + "<BR>";
            content += "下单时间:" + shopOrder.getCreatetime() + "<BR>";

            QueryWrapper<ShopDevices> queryShopDevicesWrapper = new QueryWrapper<ShopDevices>();
            queryShopDevicesWrapper.eq("status", 1);
            queryShopDevicesWrapper.eq("shop_id", shopId);
            List<ShopDevices> shopDevicesList = shopDevicesService.list(queryShopDevicesWrapper);
            for (int k = 0; k<shopDevicesList.size(); k++) {
                ShopDevices shopDevices = shopDevicesList.get(k);
                if (shopDevices.getStatus() == 1) {
                    try {
                        JSONObject jsonObject = PrintDeviceUtil.print(url, shopDevices.getDeviceNo(),
                                shopDevices.getMkey(), content, shopDevices.getTimes() + "");
                        String responseCode = jsonObject.getString("responseCode");
                        if ("0".equals(responseCode)) {
                            //获取打印设备的订单索引
                            String orderindex = jsonObject.getString("orderindex");
                            JSONObject jsonObject1 = PrintDeviceUtil.printStatus(url, shopDevices.getDeviceNo(),
                                    shopDevices.getMkey(), orderindex);
                            String responseCode1 = jsonObject1.getString("responseCode");
                            if ("0".equals(responseCode1)) {

                                if(orListChange != null){
                                    //System.out.println("-----------------------"+orListChange.size()+"------------------------------------");
                                    if( returnCount == orListChange.size() ){///
                                        int count=0;
                                        for(OrderInfo orderInfo2:orListChange){
                                            if(orderInfo2.getShopPrint() == 0 ){
                                                count += orderGoodsService.updateByInfoId(orderInfo2.getOrderId(), orderInfo2.getGoodsId());
                                            }
                                            else{
                                                clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);
                                                logger.error("商家端打印失败:订单中商品部分已经打印!" );
                                            }
                                        }
                                        if(count == orListChange.size()){
                                            /*System.out.println("====打印完之后的小票打印状态====" + orderGoodsService.getById(orderInfo.getId()).getShopPrint());
                                            System.out.println("====控制台输出订单打印内容===="+content);*/
                                            clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);
                                            logger.info(content);
                                            logger.info("商家端打印成功");
                                        }else{
                                            if(k==shopDevicesList.size()){clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);}
                                            logger.error("商家端打印失败:订单中商品未全部成功修改打印状态!" );
                                        }
                                    }
                                    else{
                                        if(k==shopDevicesList.size()){clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);}
                                        logger.error("商家端打印失败:订单中商品未全部录入待打印状态!" );
                                    }
                                }else{
                                    if(k==shopDevicesList.size()){clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);}
                                    logger.error("商家端打印失败:无符合订单!" );
                                }

                            } else {
                                if(k==shopDevicesList.size()){clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);}
                                logger.error("商家端打印失败:" + jsonObject1);
                            }
                        } else {
                            if(k==shopDevicesList.size()){clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);}
                            logger.error("商家端打印失败:" + jsonObject);
                        }
                    } catch (IOException e) {
                        if(k==shopDevicesList.size()){clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);}
                        logger.error("商家端打印失败:" + e.getMessage());
                    }
                } else {
                    if(k==shopDevicesList.size()){clearAllCont(totalPrice,totalPrice2,totalPriceTotal,orListChange);}
                    logger.error("商家端打印失败,打印机未开启!");
                }
            }
        }
    }
    logger.info("商家端打印结束");
}

public static void clearAllCont(BigDecimal totalPrice,BigDecimal totalPrice2,BigDecimal totalPriceTotal,List<OrderInfo> orListChange){
    orListChange.clear();
    totalPrice = BigDecimal.ZERO;
    totalPrice2 = BigDecimal.ZERO;
    totalPriceTotal = BigDecimal.ZERO;
}

/**
 * 切割字符串
 *
 * @param str
 * @return
 */
public static String cutString(String str) {
    String result = str_split(str, 10, "<BR>");
//        System.out.println(result);
        return result;
    }

public static String[] str_split(String str, int length) {
    int len = str.length();
    String[] arr = new String[(len + length - 1) / length];
    for (int i = 0; i < len; i += length) {

        int n = len - i;

        if (n > length) {
            n = length;
        }
        if(i > 0){
            arr[i / length] = "  " + str.substring(i, i + n);
        }else{
            arr[i / length] =  str.substring(i, i + n);
        }
    }
    while (arr[arr.length - 1].length() < 15){
        arr[arr.length - 1] += " ";
    }
    return arr;
}

public static String str_split(String str, int length, CharSequence delimiter) {

    return String.join(delimiter, str_split(str, length));

}
}
在Delphi安卓平台下,可以使用Android的USB主机模式API来连接USB热敏打印机进行打印。以下是一个示例代码: ``` procedure TForm1.Button1Click(Sender: TObject); var manager: JUsbManager; deviceList: JHashMap; deviceIterator: JIterator; device: JUsbDevice; intf: JUsbInterface; ep: JUsbEndpoint; conn: JUsbDeviceConnection; buffer: TJavaArray<Byte>; printerCmd: AnsiString; begin // 获取USB设备列表 manager := TJUsbManager.Wrap(TAndroidHelper.Context.getSystemService(TJContext.JavaClass.USB_SERVICE)); deviceList := manager.getDeviceList; // 遍历设备列表 deviceIterator := deviceList.values.iterator; while deviceIterator.hasNext do begin device := TJUsbDevice.Wrap(deviceIterator.next); if device.getVendorId = VENDOR_ID then // VENDOR_ID是热敏打印机的厂商ID begin // 打开设备 conn := manager.openDevice(device); if Assigned(conn) then begin // 打印小票 intf := device.getInterface(0); ep := intf.getEndpoint(0); conn.claimInterface(intf, True); try // 设置打印机参数 printerCmd := #27#64; // 初始化打印机 printerCmd := printerCmd + #27#33#0; // 设置字符大小为标准 printerCmd := printerCmd + #27#100#4; // 打印并换行 printerCmd := printerCmd + #27#109; // 切纸 buffer := TJavaArray<Byte>.Create(TEncoding.UTF8.GetBytes(printerCmd)); conn.bulkTransfer(ep, buffer, Length(buffer), 5000); finally // 关闭设备 conn.releaseInterface(intf); conn.close; end; end; end; end; end; ``` 需要注意的是,此代码仅供参考,实际使用时需要根据具体的热敏打印机型号和接口进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值