废话不多说,直接上源码

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 = "";@Autowiredprivate IShopOrderService shopOrderService;@Autowiredprivate IOrderGoodsService orderGoodsService;@Autowiredprivate IGoodsService goodsService;@Autowiredprivate IUserPropService userPropService;@Autowiredprivate IPlatformDevicesService platformDevicesService;@Autowiredprivate IShopDevicesService shopDevicesService;@Autowiredprivate IUserService  userService;@Autowiredprivate 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));}
}

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

  1. NWJS(NodeJS)调用打印机 - 打印小票

    1 背景 架构设计:VueJS + Spring Cloud微服务架构 功能要求: 调用小票打印机打印小票,功能和超市收银结算功能相同 使用NWJS包装VueJS前端代码实现exe安装包和可执行文件 ...

  2. Java中Date类型如何向前向后滚动时间,( 附工具类)

    Java中的Date类型向前向后滚动时间(附工具类) 废话不多说,先看工具类: 1 import java.text.SimpleDateFormat; 2 import java.util.Cale ...

  3. hutool工具类生成二维码案例

    hutool工具类生成二维码案例 一.环境: 添加hutool工具类依赖,hutool生成二维码是利用Google的zixing,而且不是强依赖,所以还需引入zxing依赖 <dependenc ...

  4. Redis工具类封装讲解和实战

    Redis工具类封装讲解和实战     简介:高效开发方式 Redis工具类封装讲解和实战         1.常用客户端 https://redisdesktop.com/download      ...

  5. java如何设置控制台打印的字体颜色、背景、字体样式(idea设置打印字体样式)工具类 - 附插件方式

    效果: 设置控制台打印字体颜色.背景.字体样式,java工具类 package org.dxl.log;import java.util.Arrays;/*** 在控制台按照传入格式输出 ** @au ...

  6. 这可能是最精简的Android6.0运行时权限处理,百行代码的工具类,支持Rationale,附:各种权限详细处理

    0x00:前言 对于Android6.0运行时权限的处理方式网上有很多,包括注解,RxJava等等.一直没有正面提到我关心的问题–如果我不在Activity或者Fragment里面,需要运行时权限该怎 ...

  7. 自己整理出来的java实现打印机打印小票

    //实现Printable接口 用于创建打印内容 public class UserTicket implements Printable {private String name1;private ...

  8. JAVA连接打印机打印小票、产品信息。标签打印机

    2018年写了一个标签打印机(TSC TX600),标签打印程序,实现功能是通过串口读出设备ID生成二维码和设备信息,用于esp8266 smart config配网.源码和资料:https://do ...

  9. [改善Java代码]让工具类不可实例化

    建议42: 让工具类不可实例化 Java项目中使用的工具类非常多,比如JDK自己的工具类java.lang.Math.java.util.Collections等都是我们经常用到的.工具类的方法和属性 ...

  10. java 下载txt文件(页面代码+Java后台代码+下载工具类)

    需求:页面有一个下载按钮,当点击下载的时候将页面表单数据下载到成为txt文件,并在网页直接下载该文件 1.页面(html) 下载一定要通过form表单的方式,js的ajax函数的返回类型只有xml.t ...

最新文章

  1. 谈C/C++指针精髓
  2. findall与match、search区别及小括号的注意事项
  3. day4 Python的selenium库
  4. 对‘TIFFReadDirectory@LIBTIFF_4.0’未定义的引用
  5. 第四十期:2019年度十大Web开发趋势
  6. [转] PHP 转义与反转义函数
  7. 串行口通信c语言代码,问一下单片机串行口通信用c语言实现的问题
  8. 视频PPT互动问答丨数据库技术前沿的创新与实践专题
  9. 大规模机器学习在LinkedIn预测模型中的应用实践
  10. 论文阅读02:基于深度学习的图像细粒度分类算法
  11. mysql weblogic_weblogic连mysql的问题
  12. ffmpeg文档3:播放声音
  13. python画曲线图-python画蝴蝶曲线图的实例
  14. 设计高性能大并发WEB系统架构注意点
  15. 【系列三之CentOS系列】CentOS命令操作(2)
  16. 机器学习进阶路上不可错过的 28 个视频
  17. Android Studio查看MD5与SHA1
  18. 简易论坛代码源码(php+css+js+mysql)完整的代码源码,系统使用B/S架构
  19. 2000坐标系和WGS84的关系
  20. 用计算机怎么计算税率,税率计算器 个税计算器2017税率表公式

热门文章

  1. C++中toupper、tolower 、isalpha、isalnum、isdigit、islower、isupper、isblank、isspace的用法
  2. 60个有趣的经济学定律!
  3. C#调用AForge实现摄像头录像
  4. 098-rsshub-radar-2021-03-02
  5. axure 倒计时_Axure倒计时效果
  6. oeasy教您玩转vim - 4 - # 深入帮助
  7. 西安电子科技大学计算机本校好考吗,西安电子科技大学:除了计算机和通信工程,这些专业高考也很热门...
  8. 论文阅读:Neural Motifs: Scene Graph Parsing with Global Context
  9. python对5万多行的excel进行数据统计
  10. 解决Mysql计算时除数为0