项目中需要按照用户填写的表单生成一个图片文件,在页面上预览图片文件之后还需要把这个图片文件打印出来.
完整代码如下:
<template>
<div class="textAlignC">
<div id="tbView">
<h3>canvas html转图片</h3>
<div class="disFlex">
<div class="flex1">姓名</div>
<div class="flex1">张三</div>
</div>
<div class="disFlex">
<div class="flex1">性别</div>
<div class="flex1">男</div>
</div>
</div>
<button @click="init()">生成图片</button>
<br />
<img id="printImg" :src="dataURL">
<br />
<button @click="print()">打印图片</button>
</div>
</template>
<script>
import html2canvas from 'html2canvas';
export default {
data() {
return {
dataURL: ''
}
},
created() {
},
methods: {
print() {
var newWin = window.open(""); //新打开一个空窗口
var imageToPrint = document.getElementById("printImg"); //将要被打印的图片
newWin.document.write(imageToPrint.outerHTML); //将图片添加进新的窗口
newWin.document.close(); //在IE浏览器中使用必须添加这一句
newWin.focus(); //在IE浏览器中使用必须添加这一句
setTimeout(function() {
newWin.print(); //打印
newWin.close(); //关闭窗口
}, 10);
},
init() {
let that = this;
html2canvas(document.getElementById("tbView"), {
backgroundColor: null
}).then(function(canvas){
let dataURL1 = canvas.toDataURL("image/png");
that.dataURL = dataURL1;
});
},
}
}
</script>
<style scoped>
.disFlex {
display: flex;
}
.flex1 {
flex: 1;
}
#tbView {
width: 1150px;
}
img {
width: 70%;
}
</style>