新需求:
需要将页面的局部信息打印出来,只在前端实现,不要占用后端的资源。
经过一通百度,决定使用 print-js
和html2canvas
组件。
笔者这里使用npm
,如果npm
下载失败,则尝试使用cnpm
npm install print-js --save
npm install --save html2canvas
笔者这里是使用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;
前置工作准备就绪,下面开始代码实操
<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'
})
})
}
}
}
看效果图!
点击右侧打印按钮:
根据效果课件,可以显示指定区域的打印效果,且多余内容会自动的分页。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有