vue-print打印条形码出现空白、样式丢失
1.安装插件
npm install html2canvas --save
2.在需要的页面引入
import html2canvas from 'html2canvas'
3.渲染下载
<div id="printMe" style="margin-top:20px;padding:5px 10px 0 0">
</div>
downLoad(){
var _this =this
let canvas2 = document.createElement("canvas");
let _canvas = document.getElementById("printMe")
let w = parseInt(window.getComputedStyle(_canvas).width);
// let w = parseInt((window.getComputedStyle(_canvas).width.split('px')[0] -0 +10) + 'px');
// 我打印的div有边框,按照原宽度打印,右边框不存在。所以在这里增加宽度,并且div加个右边距
let h = parseInt(window.getComputedStyle(_canvas).height);
//放大canvas画布,然后放在较小的容器内,像素会升高
canvas2.width = w*2;
canvas2.height = h*2;
canvas2.style.width = w+"px";
canvas2.style.height = h+"px";
let context = canvas2.getContext("2d");
context.scale(2,2);
html2canvas(document.getElementById('printMe'),{
canvas:canvas2
}).then(function (canvas) {
let fileName = "条形码" + ".jpg"
let imgUri = canvas.toDataURL("image/jpeg",2); // 获取生成的图片的url
//下载方法
_this.fileDown(imgUri,fileName);
});
},
fileDown(url, name) {
let fileName = name
axios({
method: "post",
url: url,
responseType: "blob",
}).then(data => {
let blob = new Blob([data.data], { type: "application/json" });
if (window.navigator.msSaveOrOpenBlob) {
//msSaveOrOpenBlob方法返回bool值
navigator.msSaveBlob(blob); //本地保存
} else {
let link = document.createElement("a"); //a标签下载
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
}
});
}