需要使用的三个插件

  1. docx-preview      (npm install docx-preview) 安装

  2. jszip                    (npm install jszip)安装

  3. print-js                 (npm install print-js)安装

 html部分

<div ref="word" class="print-main"></div>

js部分

import printJS from 'print-js'



methods:{

downFile(url, parameter) {
  return axios({
    url: url,
    params: parameter,
    method: 'get',
    responseType: 'blob'
  })
}

    async handlePrint({ printFile }) {
      try {
        this.focuser = setInterval(() => window.dispatchEvent(new Event('focus')), 500) //聚焦监听关闭打印
        this.hide = this.$message.loading('加载中..', 0)
        const docx = require('docx-preview')
        const blob = await this.downFile(printFile) //获取文件流
        docx
          .renderAsync(
            blob, //Blob | ArrayBuffer | Uint8Array, 可以是 JSZip.loadAsync 支持的任何类型
            this.$refs.word, // HTMLElement 渲染文档内容的元素
          )
          .then(
            setTimeout(() => {
              this.print(document.getElementsByClassName('docx')[0]) //需要打印的div
              setTimeout(this.hide) //关闭加载中
            }, 1000)
          )
      } catch (e) {
        setTimeout(this.hide) //关闭加载中
        console.log(e)
      }
    },
    print(ref, title, style, type, jsonData, borderHeadStyle, gridStyle, css) {
      printJS({
        printable: ref,
        header: title || null,
        type: type || 'html',
        headerStyle: 'font-size:6px;font-weight:600;text-align:center;padding:15px 0 10px 0;', //标题设置
        properties: jsonData || [], //json数据元
        gridHeaderStyle:
          borderHeadStyle ||
          'font-size:6px;font-weight:400;height:40px;line-height:40px;border: 1px solid #ccc;padding:3px 5px 3px 5px;text-align:center;', //json格式表头样式
        gridStyle:
          gridStyle ||
          'font-size:1px;font-weight:200;border: 1px solid #ccc;padding:3px 5px 3px 5px;text-align:center;', //json各式表格样式
        scanStyles: false, //不使用默认样式
        repeatTableHeader: false, //打印json表头只显示在第一页
        style: style || '@page{size:auto;size: a4;margin: 0cm 1cm ;}', //去除页眉页脚,A4纸
        css: css || null, //css url
        onPrintDialogClose: () => {
          this.$nextTick(() => {
            clearInterval(this.focuser)
            console.log('打印窗口关闭了')
            // 删除打印元素
            var parentElement = this.$refs.word
            while (parentElement.firstChild) {
              parentElement.removeChild(parentElement.firstChild)
            }
          })
        }
      })
    },
}

 css部分

.print-main {
  position: fixed;
  top: -10000px;  //不在页面上显示
  /deep/.docx-wrapper {
    background: none;
  }
  /deep/.docx-wrapper > section.docx {
    margin-bottom: 0;
  }
}

 注意:

  1. blob如果是docx格式的就不需要额外处理

  2.  this.print(需要打印的div) 传入的元素不正确可能导致有上下横线等问题

  3. onPrintDialogClose只能监听到关闭了打印窗口不知道是确定打印了还是取消打印了,需要开启dispatchEvent才能监听到

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐