安装html2canvas、print-js
<div ref="canvas" class="a4-container">
.
.
.
//需要打印的内容
</div>
import html2canvas from 'html2canvas'
import printJS from 'print-js'
methods: {
html2Canvas(printContent, callback){
// 获取dom 宽度 高度
const width = printContent.clientWidth;
const height = printContent.clientHeight;
// 创建一个canvas节点
const canvas = document.createElement("canvas");
const scale = 1; // 定义任意放大倍数,支持小数;越大,图片清晰度越高,生成图片越慢。
canvas.width = width * scale; // 定义canvas 宽度 * 缩放
canvas.height = height * scale; // 定义canvas高度 *缩放
canvas.style.width = width * scale + "px";
canvas.style.height = height * scale + "px";
canvas.getContext("2d").scale(scale, scale); // 获取context,设置scale
const scrollTop =
document.documentElement.scrollTop || document.body.scrollTop; // 获取滚动轴滚动的长度
const scrollLeft =
document.documentElement.scrollLeft || document.body.scrollLeft; // 获取水平滚动轴的长度
html2canvas(printContent, {
canvas,
backgroundColor: null,
useCORS: true,
windowHeight: document.body.scrollHeight,
scrollX: -scrollLeft, // 解决水平偏移问题,防止打印的内容不全
scrollY: -scrollTop,
background: "#ffffff", // 一定要添加背景颜色,否则出来的图片,背景全部都是透明的
})
.then(canvas => {
const url = canvas.toDataURL("image/png");
//console.log("canvas url :" + url);
callback({ url: url });
})
.catch(err => {
console.error(err);
});
},
printImg(url, callback){
printJS({
printable: url,
type: "image",
documentTitle: "", // 标题
style: "@page{size:auto;margin: 1cm ;}", // 去除页眉页脚
onStart: () => {
console.log("打印开始");
},
onEnd: () => {
console.log("打印完成");
}
});
},
saveAsImages() {
this.html2Canvas(this.$refs.canvas, res => {
this.printDomUrl = res.url;
this.printImg(res.url, printRes => {});
});
}
}
如果预览打印的内容不全,可以配合修改样式修复