一、首先,先下载相关模块
cnpm install html2canvas jspdf --save
二、自定义一个js 方法,一般放在utils 中
注意在本地测试时会报图片跨域的问题通常该问题只需要项目上线后自然可以解决
将其命名为htmlToPdf.js
以下配置,已设定高清配置,cv即用
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
export default {
install(Vue, options) {
Vue.prototype.getPdf = function(id, title) {
window.pageYOffset = 0;
document.documentElement.scrollTop = 0;
document.body.scrollTop = 0;
html2Canvas(document.querySelector(`#${
id}`), {
allowTaint: true,
taintTest: false,
useCORS: true,
dpi: window.devicePixelRatio * 4,
scale: 4,
}).then(function(canvas) {
let contentWidth = canvas.width;
let contentHeight = canvas.height;
let pageHeight = (contentWidth / 592.28) * 841.89;
let leftHeight = contentHeight;
let position = 0;
let imgWidth = 595.28;
let imgHeight = (592.28 / contentWidth) * contentHeight;
let pageData = new Image();
pageData.setAttribute("crossOrigin", "Anonymous");
pageData = canvas.toDataURL("image/jpeg", 1.0);
let 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(title + ".pdf");
});
};
},
};
在main.js中添加全局方法
import htmlToPdf from './htmlToPdf' //相对路径
Vue.use(htmlToPdf)
其中定义了需要在方法中写上他对应的ID和他的文件名称
getDownPdf() {
this.getPdf("需要生成区域的滴", "自定义名称");
},
最后设定相应的按钮进行下载,注意要和getPdf区分开不然会报死循环错误