头图

当然的,最重要的首先是引入LodopFuncs.js:

// eslint-disable-next-line one-var,no-unused-vars
var CreatedOKLodop7766 = null, CLodopIsLocal

// ====判断是否需要 Web打印服务CLodop:===
// ===(不支持插件的浏览器版本需要用它)===
function needCLodop () {
  try {
    var ua = navigator.userAgent
    if (ua.match(/Windows\sPhone/i)) {
      return true
    }
    if (ua.match(/iPhone|iPod|iPad/i)) {
      return true
    }
    if (ua.match(/Android/i)) {
      return true
    }
    if (ua.match(/Edge\D?\d+/i)) {
      return true
    }

    var verTrident = ua.match(/Trident\D?\d+/i)
    var verIE = ua.match(/MSIE\D?\d+/i)
    var verOPR = ua.match(/OPR\D?\d+/i)
    var verFF = ua.match(/Firefox\D?\d+/i)
    var x64 = ua.match(/x64/i)
    if ((!verTrident) && (!verIE) && (x64)) {
      return true
    } else if (verFF) {
      verFF = verFF[0].match(/\d+/)
      if ((verFF[0] >= 41) || (x64)) {
        return true
      }
    } else if (verOPR) {
      verOPR = verOPR[0].match(/\d+/)
      if (verOPR[0] >= 32) {
        return true
      }
    } else if ((!verTrident) && (!verIE)) {
      var verChrome = ua.match(/Chrome\D?\d+/i)
      if (verChrome) {
        verChrome = verChrome[0].match(/\d+/)
        if (verChrome[0] >= 41) {
          return true
        }
      }
    }
    return false
  } catch (err) {
    return true
  }
}

// ====页面引用CLodop云打印必须的JS文件,用双端口(8000和18000)避免其中某个被占用:====
if (needCLodop()) {
  var src1 = 'http://localhost:8000/CLodopfuncs.js?priority=1'
  var src2 = 'http://localhost:18000/CLodopfuncs.js?priority=0'

  var head = document.head || document.getElementsByTagName('head')[0] || document.documentElement
  var oscript = document.createElement('script')
  oscript.src = src1
  head.insertBefore(oscript, head.firstChild)
  oscript = document.createElement('script')
  oscript.src = src2
  head.insertBefore(oscript, head.firstChild)
  CLodopIsLocal = !!((src1 + src2).match(/\/\/localho|\/\/127.0.0./i))
}

// ====获取LODOP对象的主过程:====
function getLodop (oOBJECT, oEMBED) {
  // var strHtmInstall = "<br><font color='#FF00FF'>打印控件未安装!点击这里<a href='install_lodop32.exe' target='_self'>执行安装</a>,安装后请刷新页面或重新进入。</font>"
  // var strHtmUpdate = "<br><font color='#FF00FF'>打印控件需要升级!点击这里<a href='install_lodop32.exe' target='_self'>执行升级</a>,升级后请重新进入。</font>"
  // // eslint-disable-next-line camelcase
  // var strHtm64_Install = "<br><font color='#FF00FF'>打印控件未安装!点击这里<a href='install_lodop64.exe' target='_self'>执行安装</a>,安装后请刷新页面或重新进入。</font>"
  // // eslint-disable-next-line camelcase
  // var strHtm64_Update = "<br><font color='#FF00FF'>打印控件需要升级!点击这里<a href='install_lodop64.exe' target='_self'>执行升级</a>,升级后请重新进入。</font>"
  // var strHtmFireFox = "<br><br><font color='#FF00FF'>(注意:如曾安装过Lodop旧版附件npActiveXPLugin,请在【工具】->【附加组件】->【扩展】中先卸它)</font>"
  // var strHtmChrome = "<br><br><font color='#FF00FF'>(如果此前正常,仅因浏览器升级或重安装而出问题,需重新执行以上安装)</font>"
  // // eslint-disable-next-line camelcase
  // var strCLodopInstall_1 = '<br><font color="#FF00FF">Web打印服务CLodop未安装启动,点击这里<a href="CLodop_Setup_for_Win32NT.exe" target="_self">下载执行安装</a>'
  // // eslint-disable-next-line camelcase
  // var strCLodopInstall_2 = "<br>(若此前已安装过,可<a href='CLodop.protocol:setup' target='_self'>点这里直接再次启动</a>)"
  // // eslint-disable-next-line camelcase
  // var strCLodopInstall_3 = ',成功后请刷新本页面。</font>'
  // var strCLodopUpdate = "<br><font color='#FF00FF'>Web打印服务CLodop需升级!点击这里<a href='CLodop_Setup_for_Win32NT.exe' target='_self'>执行升级</a>,升级后请刷新页面。</font>"
  var LODOP
  try {
    var ua = navigator.userAgent
    var isIE = !!(ua.match(/MSIE/i)) || !!(ua.match(/Trident/i))
    if (needCLodop()) {
      try {
        // eslint-disable-next-line
        LODOP = getCLodop()
      } catch (err) {
      }
      if (!LODOP && document.readyState !== 'complete') {
        alert('网页还没下载完毕,请稍等一下再操作.')
        return
      }
      if (!LODOP) {
        // eslint-disable-next-line camelcase
        // document.body.innerHTML = strCLodopInstall_1 + (CLodopIsLocal ? strCLodopInstall_2 : '') + strCLodopInstall_3 + document.body.innerHTML
        return
      } else {
        // eslint-disable-next-line
        // if (CLODOP.CVERSION < '3.0.7.5') {
        //   document.body.innerHTML = strCLodopUpdate + document.body.innerHTML
        // }
        if (oEMBED && oEMBED.parentNode) {
          oEMBED.parentNode.removeChild(oEMBED)
        }
        if (oOBJECT && oOBJECT.parentNode) {
          oOBJECT.parentNode.removeChild(oOBJECT)
        }
      }
    } else {
      // eslint-disable-next-line no-unused-vars
      var is64IE = isIE && !!(ua.match(/x64/i))
      // =====如果页面有Lodop就直接使用,没有则新建:==========
      if (oOBJECT || oEMBED) {
        if (isIE) {
          LODOP = oOBJECT
        } else {
          LODOP = oEMBED
        }
      } else if (!CreatedOKLodop7766) {
        LODOP = document.createElement('object')
        LODOP.setAttribute('width', 0)
        LODOP.setAttribute('height', 0)
        LODOP.setAttribute('style', 'position:absoluteleft:0pxtop:-100pxwidth:0pxheight:0px')
        if (isIE) {
          LODOP.setAttribute('classid', 'clsid:2105C259-1E0C-4534-8141-A753534CB4CA')
        } else {
          LODOP.setAttribute('type', 'application/x-print-lodop')
        }
        document.documentElement.appendChild(LODOP)
        CreatedOKLodop7766 = LODOP
      } else {
        LODOP = CreatedOKLodop7766
      }
      // =====Lodop插件未安装时提示下载地址:==========
      if ((!LODOP) || (!LODOP.VERSION)) {
        // if (ua.indexOf('Chrome') >= 0) {
        //   document.body.innerHTML = strHtmChrome + document.body.innerHTML
        // }
        // if (ua.indexOf('Firefox') >= 0) {
        //   document.body.innerHTML = strHtmFireFox + document.body.innerHTML
        // }
        // // eslint-disable-next-line camelcase
        // document.body.innerHTML = (is64IE ? strHtm64_Install : strHtmInstall) + document.body.innerHTML
        return LODOP
      }
    }
    if (LODOP.VERSION < '6.2.2.6') {
      if (!needCLodop()) {
        // eslint-disable-next-line camelcase
        // document.body.innerHTML = (is64IE ? strHtm64_Update : strHtmUpdate) + document.body.innerHTML
      }
      return LODOP
    }
    // ===如下空白位置适合调用统一功能(如注册语句、语言选择等):==

    // =======================================================
    return LODOP
  } catch (err) {
    alert('getLodop出错:' + err)
  }
}

const LodopPlugin = {}
LodopPlugin.install = function (Vue, options) {
  // 4. 添加实例方法
  Vue.prototype.$getLodop = getLodop
}
export default LodopPlugin

那么我们就需要设置一个页面,在这个页面中可以获取打印机设置并保存在本地缓存中。(注意引入的lodop.js存放的位置)
代码:

<template>
  <div>
    <div id="container" style="border-top: 1px solid #cccccc;">
      <div style="width: 500px; margin: 0 auto; margin-top: 50px;">
        <table width="500" style="margin: 0 auto;" class="table table-bordered" border="">
          <!-- <tr>
              <th>生产小票打印机(白):</th>
              <td>
                <select id="factoryPrinter" v-model="factoryPrinter">
                  <option v-for="printer in factoryPrinters" :value="printer" :selected="printer === selectedPrinter">{{ printer }}</option>
                </select>
              </td>
            </tr>
            <tr>
              <th>生产小票打印机(红):</th>
              <td>
                <select id="factoryPrinterRed" v-model="factoryPrinterRed">
                  <option v-for="printer in factoryPrinterReds" :value="printer" :selected="printer === selectedPrinter">{{ printer }}</option>
                </select>
              </td>
            </tr>
            <tr>
              <th>A5打印机:</th>
              <td>
                <select id="a5Printer" v-model="a5Printer">
                  <option v-for="printer in a5Printers" :value="printer" :selected="printer === selectedPrinter">{{ printer }}</option>
                </select>
              </td>
            </tr> -->
          <tr>
            <th>包裹小票打印机:</th>
            <td>
              <select id="tailorStock" v-model="tailorStock">
                <option v-for="printer in tailorStocks" :value="printer" :selected="printer === selectedPrinter" v-bind:key="printer">{{ printer }}</option>
              </select>
            </td>
          </tr>
          <tr>
            <td colspan="2" style="text-align: center;">
              <button type="button" class="btn btn-primary" style="width: 180px;" @click="doSave()">保存配置</button>
            </td>
          </tr>
        </table>
      </div>

    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import LodopFuncs from '@/utils/LodopFuncs'
Vue.use(LodopFuncs)
export default {
  name: 'PrintConfig',
  data () {
    return {
      factoryPrinterRed: '',
      factoryPrinter: '',
      a5Printer: '',
      tailorStock: '',
      factoryPrinterReds: [],
      factoryPrinters: [],
      a5Printers: [],
      tailorStocks: []
    }
  },
  created () { },
  mounted () {
    // 进来时先初始化方便查看
    this.factoryPrinter = localStorage.factoryPrinterName
    this.factoryPrinterRed = localStorage.factoryPrinterRedName
    this.a5Printer = localStorage.a5PrinterName
    this.tailorStock = localStorage.tailorStockPrinterName
    this.listPrinters()
  },
  destroyed () { },
  methods: {
    getPrinterCount () {
      var LODOP = this.$getLodop()
      return LODOP.GET_PRINTER_COUNT()
    },
    getPrinterName (iPrinterNO) {
      var LODOP = this.$getLodop()
      return LODOP.GET_PRINTER_NAME(iPrinterNO)
    },
    listPrinters () {
      const selectedFactoryPrinterRedName = localStorage.factoryPrinterRedName
      const selectedFactoryPrinterName = localStorage.factoryPrinterName
      const selectA5PrinterName = localStorage.a5PrinterName
      const tailorStockPrinterName = localStorage.tailorStockPrinterName

      const printerCount = this.getPrinterCount()
      console.log('打印机配置有' + JSON.stringify(printerCount))
      for (let i = 0; i < printerCount; i++) {
        const printerName = this.getPrinterName(i)
        console.log('打印机名字有' + JSON.stringify(printerName))
        if (selectedFactoryPrinterName && printerName === selectedFactoryPrinterName) {
          this.factoryPrinters.push(printerName)
        } else {
          this.factoryPrinters.push(printerName)
        }

        if (selectedFactoryPrinterRedName && printerName === selectedFactoryPrinterRedName) {
          this.factoryPrinterReds.push(printerName)
        } else {
          this.factoryPrinterReds.push(printerName)
        }

        if (selectA5PrinterName && printerName === selectA5PrinterName) {
          this.a5Printers.push(printerName)
        } else {
          this.a5Printers.push(printerName)
        }

        if (tailorStockPrinterName && printerName === tailorStockPrinterName) {
          this.tailorStocks.push(printerName)
        } else {
          this.tailorStocks.push(printerName)
        }
      }
    },
    doSave () {
      const factoryPrinterRedName = this.factoryPrinterRed
      const factoryPrinterName = this.factoryPrinter
      const a5PrinterName = this.a5Printer

      localStorage.factoryPrinterRedName = factoryPrinterRedName
      localStorage.factoryPrinterName = factoryPrinterName
      localStorage.a5PrinterName = a5PrinterName
      localStorage.tailorStockPrinterName = this.tailorStock
      // console.log('本地缓存:白打印机' + localStorage.factoryPrinterName)
      // console.log('本地缓存:红打印机' + localStorage.factoryPrinterRedName)
      // console.log('本地缓存:A5打印机' + localStorage.a5PrinterName)
      console.log('本地缓存:库存小票打印机' + localStorage.tailorStockPrinterName)
      alert('保存配置成功')
    }
  }
}
</script>

好,我们这里先通过按钮,触发后端获取需要打印的数据:

<el-table-column label="打印">
        <template slot-scope="scope">
          <span style="color:#02a7f0;text-decoration: underline;"
                @click="stockupPackagePrint(scope.row.packageNo)">打印包裹小票</span>
        </template>
      </el-table-column>
 stockupPackagePrint (packageNo) {
      api.get('/stockup-package/getStockupPackageDetails?stockupPackageNo=' + packageNo).then(res => {
        this.$refs.stockupPackage.commonPrintReceipt(res.data)
      }).catch(error => {
        console.log(error)
      })
    },

跳到第二个页面,调用方法打印:
这是第一个页面: 引入第二个页面的内容

<!-- 打印模版 -->
    <div style="display: none">
      <stockup-package ref="stockupPackage"></stockup-package>
    </div>
import stockupPackage from '@/pages/print-template/stockupPackage.vue'
export default {
  components: {
    stockupPackage
  },
 ....

第二个页面的内容:进行打印:
commonPrintReceipt 为生成页面并进行打印的方法

<template>
  <div ref="backendReceipt" style="width: 65mm;text-align: center; margin-left: 10px;">
    <div style="padding-top: 10px;">
      <span style="font-size: 14px;">包裹编号:{{ packageNo }}</span>
      <span style="margin-left: 30px;font-size: 14px;">总件数:{{ total }}</span>
    </div>
    <div>
      <span style="font-size: 16px;">打印时间:{{ printTimeStr }}</span>
    </div>
    <table border="1" style="font-size: 16px;">
      <thead>
      <tr>
        <th>产品编码</th>
        <th>货品编码</th>
        <th>颜色</th>
        <th>尺码</th>
        <th>数量</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="item in stockupPackageItemList" :key="item.id">
        <td style="font-size: 16px;">{{ item.productCode }}</td>
        <td style="font-size: 16px;">{{ item.goodsNo }}</td>
        <td style="font-size: 16px;">{{ item.color }}</td>
        <td style="font-size: 16px;">{{ item.size }}</td>
        <td style="font-size: 16px;">{{ item.total }}</td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import Vue from 'vue'
import LodopFuncs from '@/utils/LodopFuncs'

Vue.use(LodopFuncs)
export default {
  name: 'stockupPackage',
  data () {
    return {
      packageNo: '',
      printTimeStr: '',
      total: 0,
      stockupPackageItemList: []
    }
  },
  methods: {
    commonPrintReceipt (data) {
      this.packageNo = data.packageNo || ''
      this.printTimeStr = data.printTimeStr || ''
      this.total = data.total || ''
      this.stockupPackageItemList = data.stockupPackageItemList || []
      this.$nextTick(() => {
        const LODOP = this.$getLodop()
        const html = this.$refs.backendReceipt.innerHTML
        var tailorStockPrinterName = localStorage.tailorStockPrinterName
        console.log('获取的打印机为' + tailorStockPrinterName)
        if (tailorStockPrinterName && tailorStockPrinterName !== undefined) {
          console.log('select 生产单 printer, ' + tailorStockPrinterName)
          LODOP.SET_PRINTER_INDEXA(tailorStockPrinterName)
        }
        LODOP.SET_PRINT_PAGESIZE(0, 800, 600, '优速标准')
        LODOP.SET_PRINT_MODE('PRINT_PAGE_PERCENT', '100%')
        LODOP.SET_PRINT_MODE('POS_BASEON_PAPER', true)
        LODOP.ADD_PRINT_HTM(0, 0, 800, 600, html)
        // LODOP.PREVIEW() // 直接预览
        LODOP.PRINT() // 直接打印
        this.$message({
          message: '打印成功',
          type: 'success'
        })
      })
    }
  }
}
</script>

<style scoped>

</style>


小全栈工程师小鹿
4 声望0 粉丝

一个菜鸡的全干工程师......