前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Vue使用printjs组件打印页面

Vue使用printjs组件打印页面

作者头像
猫老师的叶同学
发布2023-03-25 13:09:55
2.7K0
发布2023-03-25 13:09:55
举报
文章被收录于专栏:中间件的探究中间件的探究

Vue使用printjs组件打印页面

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

1、npm下载组件

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

代码语言:javascript
复制
npm install print-js --save
npm install --save html2canvas
2、main.js引入组件并注册为全局组件

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

代码语言:javascript
复制
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、实践打印工作

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

代码语言:javascript
复制
<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'
        })
      })
    }
  }
}

看效果图!

在这里插入图片描述
在这里插入图片描述

点击右侧打印按钮:

在这里插入图片描述
在这里插入图片描述

根据效果课件,可以显示指定区域的打印效果,且多余内容会自动的分页。

本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-03-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Vue使用printjs组件打印页面
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com