Vue使用vue-print-nb打印,并去除页眉页脚,打开打印窗口自动打印

这篇博客介绍了如何利用vue-print-nb插件在Element-UI的Dialog对话框中实现打印功能。作者详细阐述了安装、配置过程,包括在main.js中注册插件、在Dialog中添加打印按钮,并展示了如何自定义打印样式以去除页眉页脚。此外,还提及了如何在打印前动态设置样式以满足不同场景需求。
摘要由CSDN通过智能技术生成

一、这次使用的是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);

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值