一、这次使用的是vue-print-nb插件完成打印的功能。

借鉴链接:vue html页面打印功能vue-print-nb - 潇湘羽西 - 博客园

文档:vue-print-nb - npm

使用方式

安装 npm install vue-print-nb --save

在main.js文件中注册

import Print from 'vue-print-nb'

Vue.use(Print);

我使用的是element-ui,打印功能使用了Dialog 对话框:的稍等

    <el-dialog
      title="提示"
      :visible.sync="printDrawer"
      width="50%"
      @opened="openPrintDialog"
      ref="printRef"
    >
      <el-card class="print-card" id="print-content" shadow="never">
        <div>
          <p>锄禾日当午</p>
                
          <p>汗滴禾下土</p>
                
          <p>谁知盘中餐</p>
                
          <p>粒粒皆辛苦</p>
        </div>
      </el-card>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button ref="printClick" type="primary" v-print="printObj" 
          >打 印</el-button
        >
      </span>
    </el-dialog>

添加参数(放data里):

printObj: {
        id: "print-content",
        popTitle: "",
        // extraCss: 'https://www.google.com,https://www.google.com',
        extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
        beforeOpenCallback (vue) {
                vue.printLoading = true
                console.log('打开之前')
              },
              openCallback (vue) {
                vue.printLoading = false
                console.log('执行了打印')
              },
              closeCallback (vue) {
                console.log('关闭了打印工具')
              }
      },

2、由于使用场景的需要,我做了弹出对话框直接打印(因为打印的时候需要选择打印机)

    // 对话框打开之后执行
    openPrintDialog(){
      console.log(this.$refs)
      this.$refs.printClick.$el.click();
    }

3、加样式去除页眉页脚

// 去除打印的页眉页脚
<style media="print">
@page {
  size: auto; /* auto is the initial value */
  margin: 3mm; /* this affects the margin in the printer settings */
}
</style>
// 去除打印的页眉页脚

如果内嵌了多个打印界面,如果需要不同的打印样式,可以在打印之前设置打印样式

在打印之前的函数增加如下代码:

var style = document.createElement('style');
      style.innerHTML = "@page{size: 85mm 56mm;margin: 5mm;}" +
              " html{background-color: #FFFFFF; margin: 0;}" +
              " body{border: solid 0px #FFFFFF;}";
      window.document.head.appendChild(style);

Logo

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

更多推荐