场景: 需要将页面的局部信息打印出来,只在前端实现,不要占用后端的资源。经过百度经验,决定使用 print-js
和html2canvas
组件。
1. 下载包
npm install print-js --save
npm install --save html2canvas
2. 组件内引用
<script>
import printJS from 'print-js'
import 'print-js/dist/print.css'
import html2canvas from 'html2canvas'
</script>
3. 执行打印方法
<div>
<el-card style="height: 780px; overflow: auto;page-break-after:always;">
<div ref="printPaperRef">
<template v-for="index in 15">
要打印的很多很多内容
</template>
</div>
</el-card>
</div>
import printJS from 'print-js'
import 'print-js/dist/print.css'
import html2canvas from 'html2canvas'
export default {
name: 'ExamProcess',
methods: {
// 打印试卷
printPaper() {
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
printJS({
printable: url,
type: 'image',
documentTitle: "--",
base64: 'true'
})
})
}
}
}
遇到的问题:
1. html2canvas 文字向下偏移
解决: 使用html2canvas@^1.0.0的版本
2. html2canvas转图片不清晰的问题
解决: 利用增大dpi
dpi:DPI是指某些设备分辨率的度量单位。DPI越低,扫描的清晰度越低,DPI越高,清晰度越高。
由于受网络传输速度的影响,web上使用的图片都是72dpi,照片使用300dpi或者更高350dpi,会很清晰。
html2canvas(template, {
dpi: 300,//加了一个这个设置
useCORS: true, //(图片跨域相关)
allowTaint: false, //允许跨域(图片跨域相关)
x: 0,//页面在横向方向上的滚动距离 横向上没有超过 所以设置为0
y: window.pageYOffset,//页面在垂直方向上的滚动距离 设置了以后 超过一屏幕的内容也可以截取
windowWidth: document.body.scrollWidth,//获取在x轴上滚动条中内容
windowHeight: document.body.scrollHeight,//获取在y轴上滚动条中内容
});
解决后的效果:
3. 打印出现空白页, 且没有去除页眉和页脚
解决: 设置打印时的样式
printJS({
printable: url,
type: 'image',
documentTitle: '',
header: null,
style:
'@media print{ @page { size: A4; margin: 0mm -1.5mm; mso-header: none; mso-footer: none; } body{margin:0 5px}}',
// mso-header: 去掉页眉
// mso-footer: 去掉页脚
// margin 因为左右还是有点间隙, 所以设置margin为0
// body{margin:0 0px} : 防止第一页出现空白页
// ps: 如果你打印的是图片, 则 需要设置img的样式, 因为img是行内块级, 会有间隙, 可以设置img {display: block;}
base64: true
})
解决后的效果: 完美, 并且多余的内容会自动生成到第二页中