vue实现打印功能

469 阅读1分钟

vue-print-nb

通过 npm 安装 vue-print-nb

npm install vue-print-nb --save

在 main.js 中注册挂载

 import Print from 'vue-print-nb'
 Vue.use(Print)

然后就可以进行使用了

将要打印的内容加上 id

image.png

将触发打印事件的元素加上 v-print 指令, 值有字符串和对象两种形式

字符串格式 -- 直接绑定要打印内容的 id即可

image.png

对象格式 -- 可以设置标题、头部文字、执行钩子函数等操作

image.png

     printObj: {
        id: 'printBox',  // 绑定要打印元素的id
        popTitle: '这是一个很棒的打印标题',    //打印的标题
        extraCss: '',  // 打印可引入外部的一个 css 文件
        extraHead: '这是一句头部文字',  // 打印头部文字
        beforeOpenCallback (vue) {
          console.log('打开之前')
        },
        openCallback (vue) {
          console.log('执行了打印')
        },
        closeCallback (vue) {
          console.log('关闭了打印工具')
        }
     }

完成之后就可以实现打印功能了, 若出现样式问题可以使用行内样式来解决

image.png

若想去除页眉页脚只需在页面的 style 中加入 @page 即可

@page{
    size:  auto;   /* auto is the initial value */
    margin: 3mm;  /* this affects the margin in the printer settings */
  }