• 菜鸟打印组件系列-vue3快速接入



    前言

    文章主要记录不注册商家,直接使用菜鸟打印组件提供的自定义模板的能力,来实现打印的。案例是基于vue3+vite+element-plus ,注册商家的使用可以参考官方案例。


    1. 相关名词或语句

    • CAINIAO打印组件 (菜鸟打印组件)
    • cnPrinter(菜鸟打印组件)
    • ISV(第三方软件服务商)
    • 不干胶标签纸(快递单或则商品标签贴物品 )
    • 面单(指快递单等)
    • DPI 水平 (DPI(Dots Per Inch,每英寸点数),图像每英寸(1 英寸 = 25.4 毫米)长度内的像素点数)
    • 垂直偏移量 (设置打印内容在面单的位置)

    2. CAINIAO打印组件能力

    1.支持面单使用模板,这里的模板要注册商家号获取与管理。
    2.支持全定义模板.
    3. 兼容能力:支持windows 与 macOS(但不支持14以上)
    4. 不支持独立部署,不支持离线使用(打印的数据都要上传到菜鸟的云服务器处理后,返回渲染后的面单,注意国外windows服务器传输比较慢)
    5. 面对国内用户

    3. 安装与下载

    🚀CAINIAO打印组件官网 下载插件;
    💪引用自官方 打印组件商家操作手册
    在这里插入图片描述

    4. vue3集成步骤

    4.1 使用pina 创建websoket相关处理的模块。

    菜鸟打印组件是通过websoket的方式发送指令给打印机的。这里使用pina 创建websoket相关处理的模块。
    其中用的是 13528 端口。也就是 ws://127.0.0.1:13528 , 注意端口是否被占用。

    下面的代码我让AI生产的,然后稍微改了一下

    import { defineStore } from 'pinia'
    import { printStatusApi } from '@/api/xxx'
    // export const WS_URL = 'ws://127.0.0.1:13528'
    import { RefNumEnum, WS_URL } from '@/utils/constant'
    import { ElMessageBox } from 'element-plus'
    
    export const useWebSocketStore = defineStore('websocket', {
      state: () => ({
        ws: null, // 全局存储一个 websoket ,避免重复创建
        isConnected: false, // 判断菜鸟组件是否以及启动
        reconnectInterval: 5000,
        reconnectTimer: null,
        callbackEventObj: {},
        isShowErrBox: false
      }),
      actions: {
        connect(cb: any, callbackType: any) {
          this.callbackEventObj[callbackType] = cb // 打印成功或则失败的回调函数,场景不同用callbackType 来判断对于的回调
          if (this.ws && this.ws.readyState === 1)  return
          this.ws = new WebSocket(WS_URL)
          this.ws.onopen = () => {
            console.log('WebSocket connected')
            this.isConnected = true
          }
          this.ws.onmessage = (event) => {
            console.log('WebSocket message received:', event.data)
            // 处理收到的消息
            this.subscribe(JSON.parse(event.data || ''), cb)
          }
          this.ws.onclose = () => {
            console.log('WebSocket disconnected')
            this.isConnected = false
            this.reconnect(cb, callbackType)
          }
          this.ws.onerror = (error) => {
            console.error('WebSocket error:', error)
            this.reconnect(cb, callbackType)
          }
        },
        send(message) {
          if (this.isConnected) {
            this.ws.send(message)
          } else {
            console.warn('WebSocket is not connected')
          }
        },
        close() {
          if (this.ws) {
            this.ws.close()
            this.ws = null
          }
        },
        subscribe(data: any, callBackFn: any) {
          switch (data.cmd) {
            case 'getPrinters':
              console.log('获取打印机列表', data.printers)
              if (data.printers) {
                data.printers = data.printers.filter((i: any) => {
                  return i.status == 'enable'
                })
              }
              // 缓存起来
              localStorage.setItem('PRINTERS', JSON.stringify(data.printers || []))
              break
            case 'getPrinterConfig':
              console.log('获取打印机配置')
              console.log(data.printer)
              break
            case 'print':
              console.log('发送打印')
             // console.log(data)
              if (data?.status === 'failed' && !this.isShowErrBox) {
                this.isShowErrBox = true
                ElMessageBox({
                  title: 'Warning',
                  message: `${data?.msg}`,
                  confirmButtonText: 'I know',
                  callback: () => {
                    this.isShowErrBox = false
                  }
                })
              }
              break
            case 'notifyPrintResult':
              console.log('打印通知----',data)
              if (['printed', 'failed'].includes(data.taskStatus)) {
                // 打印成功/失败 回调记录状态Api接口
                this.printStatus(data)
              }
              break
            case 'setPrinterConfig':
              console.log('设置打印机配置')
              console.log(data)
              break
          }
        },
        // 这里的data是发送给菜鸟组件的数据按文档要求来,一般有requestID,TaskID等,把自定义的拼接进去
        async printStatus(data: any) {
          // 传参
          let curId = data?.requestID.split('#') && data?.requestID.split('#')[0]
          await  printStatusApi(curId )
          this.callbackEventObj[markType]()
        },
        // 这里的重连可以设置一个次数后,停止重连
        reconnect(cb, callbackType) {
          if (!this.reconnectTimer) {
            console.log(`WebSocket will reconnect in ${this.reconnectInterval} ms`)
            this.reconnectTimer = setTimeout(() => {
              console.log('WebSocket reconnecting...')
              this.connect(cb, callbackType)
              this.reconnectTimer = null
            }, this.reconnectInterval)
          }
        },
        stopReconnect() {
          if (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer)
            this.reconnectTimer = null
          }
        }
      }
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123

    4.2 创建本地自定义模板(要打印的模板以及样式)

    自定义的模板,是菜鸟组件定义模板语言。需要传到菜鸟的服务器处理后,渲染成真正的面单,这个文件放在public文件夹下,不然vite打包的时候会处理,导致打印出错。

    
    <page
            xmlns="http://cloudprint.cainiao.com/print"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://cloudprint.cainiao.com/print http://cloudprint-docs-resource.oss-cn-shanghai.aliyuncs.com/lpml_schema.xsd"
            xmlns:editor="http://cloudprint.cainiao.com/schema/editor"
            width="210" height="297"
               >
    		<layout orientation="vertical" left="72" top= "6" width="60" height="20" style="zIndex:1;">
                   <text  
                    style="fontSize:18;align:center;">
                    
                   text>
    		layout>
                <layout left= "8" top= "22" width="80" height="36" >
                   <barcode width= "80" height= "36" value= "<%=_data.xx%>" type= "code128a" style= "hideText:false" />
                layout>
                  <layout orientation="vertical" left="108" top= "22" width="90" height="14" style="zIndex:4;">
                   <text  
                    style="fontSize:12;align:left;">
                     ]]>
                   text>
    		layout>
                  <layout left="108" top= "28" width="80" height="36" >
                    <text  
                    style="fontSize:12;align:left;">
                     ]]>
                   text>
                layout>
                  <layout left="108" top= "34" width="120" height="36" >
                    <text  
                    style="fontSize:12;align:left;">
                     ]]>
                   text>
                layout>
                  <layout left="108" top= "40" width="80" height="36" >
                    <text  
                    style="fontSize:12;align:left;">
                     ]]>
                   text>
                layout>
                <layout left="108" top= "46" width="80" height="36" >
                    <text  
                    style="fontSize:12;align:left;">
                    ]]>
                   text>
                layout>
                <layout left="108" top= "52" width="80" height="36" >
                    <text  
                    style="fontSize:12;align:left;">
                    
                   text>
                layout>
                <layout  id="1550220042465924" width="96" height="20.13" left="2" top="65.77"  style="zIndex:4;">
                      <table width="200">  
                            <tr >
                                  <th width="38"> 
                                        <text  style="fontSize:10;align:center;">
                                                          
                                        text>
                                   th>
                                  <th width="26"> 
                                   <text  style="fontSize:10;align:center;">
                                                    
                                   text>
                                   th>
                                   <th width="31"> 
                                        <text  style="fontSize:10;align:center;">
                                                          
                                        text>
                                  th>
                                  <th width="36"> 
                                        <text  style="fontSize:10;align:center;">
                                                          
                                        text>
                                   th>
                                  <th width="13"> 
                                        <text  style="fontSize:10;align:center;">
                                                          
                                        text>
                                   th>
                                  <th width="13"> 
                                        <text  style="fontSize:10;align:center;">
                                                          
                                        text>
                                   th>
                            tr>
                   
                          <% for(i=0;i<_data.arr.length;i++) { %>
                            <tr>
                                  <td> 
                                        <text  style="fontSize:10;align:center;">
                                              ]]>
                                        text>
                                  td>
                                  <td>
                                        <text   style="fontSize:10;align:center;">
                                                    ]]>
                                              text>
                                  td>
                                  <td>
                                        <text  style="fontSize:10;align:center;">
                                                    ]]>
                                              text>
                                  td>
                                  <td>
                                        <text   style="fontSize:10;align:center;">
                                                    ]]>
                                              text>
                                  td>
                                  <td>
                                        <text   style="fontSize:10;align:center;">
                                                    ]]>
                                              text>
                                  td>
                                  <td>
                                        <text style="fontSize:10;align:center;">
                                        text>
                                  td>
                            tr>
                          <%}%>
                      table>
                layout>
                 <footer height="20" >
                      <layout width="100" height="10" left="10" top="1"  style="overflow:visible;">
                        <pageIndex format="Page currentPageNumber of totalPageNumber" style="fontSize:10;">pageIndex>
                      layout>
                footer>
               
    page>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130

    4.3 结合el-table ,实现批量打印

    下面是在列表页面上使用上述模块,实现可以支持多选table的项,批量打印,记录打印的状态后刷新页面的核心代码,自行理解后根据自身业务或则交互使用。

    import { useWebSocketStore } from '@/store/modules/websocket'
    const useWebSocket = useWebSocketStore()
    // variable.selectedAr 是勾选的数据
    const doPrint = async function () {
      if (variable.selectedArr && variable.selectedArr.length === 0) {
        return ElMessage.warning('请选择需要打印的数据')
      }
      // 使用for of 是为了可以串行,也就是支持 await 放回数据后再接下去执行,同是支持 break 中断循环。
      for (const dataItem of variable.selectedArr) {
        const { data } = await detailApi({id:'123'})
        // 注意这个模板需要放在 public 里面
        const templateURL = `${window.location.origin}/cnPrinter/xxx.template`
        //打印对象   https://open.taobao.com/doc.htm?docId=107014&docType=1 根据官网调整
        const jsonObject: any ={
    	"cmd": "print",
    	"requestID": "123458976",
    	"version": "1.0",
    	"task": {
    		"taskID": "7293666",
    		"preview": false,
    		"printer": "", // 为空字符串时,取系统默认打印机
    		"documents": [{
    			"documentID": "0123456789",
    			"contents": [
    			{
    				"data": {
    					"value": "测试字段值需要配合自定义区变量名"
    				},
    				"templateURL": `${templateURL}`
    			}]
    		}]
    	}
    }
        //发送给打印机
        useWebSocket.send(JSON.stringify(jsonObject))
      }
      handleSearch()
    }
    
    const callBackFunction = () => {}
    onMounted(() => {
      useWebSocket.connect(callBackFunction,pageType)
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    总结

    本文一开始介绍了菜鸟打印组件,相关名词,以及在打印方面的相关能力和使用时的注意点。接着举例基于vue3+pina+elementPlus的项目通过步骤1.使用pina 创建websoket相关处理的模块,处理打印机与浏览器长连接的过程。步骤2.按照菜鸟要求的模板语言,调整自己的打印模板,并且放在public文件夹下,步骤3.在列表页其中使用el-table组件,引入websoket模块,连接菜鸟组件以及批量打印,实现简单的批量打印功能。

  • 相关阅读:
    第五届“强网”拟态防御国际精英挑战赛——预选赛入围战队篇
    MFC使用system有弹黑窗的解决 用WinExec(szBuffer, SW_HIDE);代替
    面试总结-Redis篇章(十二)——Redis是单线程的,为什么还那么快
    2.9每日一题(定积分的奇偶性以及比较大小)
    JdbcTemplate
    【Springer出版社】机器学习、遥感、信号处理类SCI&EI,2-3个月左右录用
    移动端测试——移动端App抓包
    基于Mxnet实现实例分割-MaskRCNN【附部分源码】
    服装行业在快手打广告效果好吗?如何在短视频平台推广服装?
    采集拼多多商品详情api接口
  • 原文地址:https://blog.csdn.net/Bruce__taotao/article/details/134182987