Vue使用printjs组件打印页面

Vue使用printjs组件打印页面

新需求:
需要将页面的局部信息打印出来,只在前端实现,不要占用后端的资源。
经过一通百度,决定使用 print-jshtml2canvas组件。

1、npm下载组件

笔者这里使用npm,如果npm下载失败,则尝试使用cnpm

npm install print-js --save
npm install --save html2canvas
2、main.js引入组件并注册为全局组件

笔者这里是使用Vue2.x版本,所以如果是Vue3.x,请根据新写法在main.js中引用。

import Vue from "vue";
import printjs from 'print-js'
import 'print-js/dist/print.css';
import html2canvas from 'html2canvas';

Vue.prototype.$print = printjs;
Vue.prototype.$html2canvas = html2canvas;
3、实践打印工作

前置工作准备就绪,下面开始代码实操

<div>
	<el-card style="height: 780px; overflow: auto;page-break-after:always;">
        <div ref="printPaperRef">
           <template v-for="index in 15">
              <!-- 题目: 序号、类型、题干 -->
              <div>
                <div class="num">{{index}}</div>
                【单选题】
                <div style="padding-left: 10px;">这是一道很难很难很难很难的单选题,{{index}}}</div>
              </div>

              <!-- 选项 -->
              <el-radio-group style="width: 100%" >
                <el-radio v-for="item in ['A', 'B', 'C', 'D']" border
                          class="answer_radio">
                  <!-- 选项flex浮动 -->
                  <div style="display: inline-flex;width: 90%;">
                    <div class="answer_tag">
                      {{ item }}.
                    </div>
                  </div>
                  <div style="float: right;">
                    <i class="el-icon-success" style="color:#1aac1a;">
                      答案
                    </i>
                  </div>
                </el-radio>
              </el-radio-group>
            </template>
        </div>
	</el-card>
</div>
export default {
  name: 'ExamProcess',
  methods: {
  	// 打印试卷
    printPaper() {
      this.$html2canvas(this.$refs.printPaperRef, {
        backgroundColor: 'white',
        useCORS: true,
        foreignObjectRendering: false,
        windowWidth: document.body.scrollWidth,
        windowHeight: document.body.scrollHeight
      }).then((canvas) => {
        const url = canvas.toDataURL()
        this.img = url
        this.$print({
          printable: url,
          type: 'image',
          documentTitle: "--",
          base64: 'true'
        })
      })
    }
  }
}

看效果图!
在这里插入图片描述
点击右侧打印按钮:
在这里插入图片描述
根据效果课件,可以显示指定区域的打印效果,且多余内容会自动的分页。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值