Vue将页⾯导出为图⽚或者PDF 本⽂实例为⼤家分享了Vue导出页⾯为PDF格式的具体代码,供⼤家参考,具体内容如下
导出为图⽚
1.将页⾯html转换成图⽚
npm install html2canvas --save
2.在需要导出的页⾯引⼊
import html2canvas from 'html2canvas';
在 methods 中添加⽅法
dataURLToBlob(dataurl) {//ie 图⽚转格式
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);pdf转html
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type: mime})
},
downloadResult(name) {
let canvasID = document.body
let a = ateElement('a');
html2canvas(canvasID).then(canvas => {
let dom = document.body.appendChild(canvas);
dom.style.display = "none";
a.style.display = "none";
veChild(dom);
let blob = this.DataURL("image/png"));
a.setAttribute("href", ateObjectURL(blob));
a.setAttribute("download", name + ".png")
document.body.appendChild(a);
a.click();
veChild(a);
});
},
printOut(name) {
/
/ 个⼈观察只是截取可见范围以及以下的区域,所以先将滚动条置顶
$(window).scrollTop(0); // jQuery 的⽅法
document.body.scrollTop = 0; // IE的
document.documentElement.scrollTop = 0; // 其他
this.downloadResult(name)
},
导出为PDF
1.将页⾯html转换成图⽚
npm install html2canvas --save
2.将图⽚⽣成pdf
npm install jspdf --save
3.在需要导出的页⾯引⼊
import html2canvas from 'html2canvas';
import JsPDF from 'jspdf'
在 methods 中添加⽅法
printOut(name) {
let shareContent = document.body,//需要截图的包裹的(原⽣的)DOM 对象
width = shareContent.clientWidth, //获取dom 宽度
height = shareContent.clientHeight, //获取dom ⾼度
canvas = ateElement("canvas"), //创建⼀个canvas节点
scale = 2; //定义任意放⼤倍数⽀持⼩数
canvas.width = width * scale; //定义canvas 宽度 * 缩放
canvas.height = height * scale; //定义canvas⾼度 *缩放
canvas.style.width = shareContent.clientWidth * scale + "px";
canvas.style.height = shareContent.clientHeight * scale + "px";
let opts = {
scale: scale, // 添加的scale 参数
canvas: canvas, //⾃定义 canvas
logging: false, //⽇志开关,便于查看html2canvas的内部执⾏流程
width: width, //dom 原始宽度
height: height,
useCORS: true, // 【重要】开启跨域配置
};
html2Canvas(shareContent, opts).then(() => {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
//⼀页pdf显⽰html页⾯⽣成的canvas⾼度;
var pageHeight = (contentWidth / 592.28) * 841.89;
//未⽣成pdf的html页⾯⾼度
var leftHeight = contentHeight;
//页⾯偏移
var position = 0;
//a4纸的尺⼨[595.28,841.89],html页⾯⽣成的canvas在pdf中图⽚的宽⾼
var imgWidth = 595.28;
var imgHeight = (592.28 / contentWidth) * contentHeight;
var pageData = DataURL("image/jpeg", 1.0);
var PDF = new JsPDF("", "pt", "a4");
if (leftHeight < pageHeight) {
PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
leftHeight -= pageHeight;
position -= 841.89;
if (leftHeight > 0) {
PDF.addPage();
}
}
}
PDF.save(name + ".pdf"); // 这⾥是导出的⽂件名
});
},
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。