print-js:打印插件使用,demo基于vue

82 阅读1分钟
<template>
  <div class="container">
    <e-card id="printFrom">
      <span>单号:ID202402191839</span>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="date" label="日期" width="180">
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="address" label="地址"> </el-table-column>
      </el-table>
      <img
        src="@/assets/images/403.png"
        alt="11"
        style="width: 100px; height: 100px; margin-top: 20px"
      />
    </e-card>
    <Button
      style="width: 75px"
      size="small"
      type="info"
      @click="handlePrint(printData)"
    >
      打印
    </Button>
  </div>
</template>

<script>
import printJS from 'print-js'

export default {
  data() {
    return {
      tableData: [
        {
          date: '2016-05-02',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        },
        {
          date: '2016-05-04',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1517 弄'
        },
        {
          date: '2016-05-01',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1519 弄'
        },
        {
          date: '2016-05-03',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1516 弄'
        }
      ],
      printData: {
        printable: 'printFrom',
        // header:'再生资源收货单',
        ignore: ['no-print'],
        type: 'html' // 打印的元素类型
      }
    }
  },
  methods: {
    handlePrint(params) {
      // var printFrom = document.getElementById('printFrom')
      // printFrom.style.display = 'block';
      // setTimeout(() => {
      //   printFrom.style.display = 'none';
      // }, 2000);
      // print.js的onPrintDialogClose事件触发失效,在打印事件触发之前,添加派发一个focus聚焦事件,然后点击取消或打印,清除focus事件。
      let focuser = setInterval(
        () => window.dispatchEvent(new Event('focus')),
        500
      )
      printJS({
        printable: params.printable, // 'printFrom', // 标签元素id
        type: params.type || 'html',
        header: params.header, // '表单',
        targetStyles: ['*'],
        style: '@page {margin:0 10mm};', // 可选-打印时去掉眉页眉尾
        ignoreElements: params.ignore || [], // ['no-print']
        properties: params.properties || null,
        //打印完成或关闭打印的事件
        onPrintDialogClose: () => {
          //取消打印回调
          //清除focus事件
          clearInterval(focuser)
          // printFrom.style.display = 'none';
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  #printFrom {
    width: 500px;
    margin-top: 50px;
  }
}
</style>

备注:

原型:

image.png

打印预览: image.png