使用html2canvas和jspdf插件实现
该方式是通过html2canvas
将HTML页面转换成图片,然后再通过jspdf
将图片的base64生成为pdf文件。实现步骤如下:
一、下载插件模块
npm install html2canvas jspdf --save
二、定义功能实现方法
// 导出页面为PDF格式
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
export default {
install(Vue, options) {
Vue.prototype.getPdfOrImg = function (e,type, dom) {
html2Canvas(document.querySelector(dom), {
dpi: 192, // 将分辨率提高到特定的dpi,默认值为96 与scale组合使用可增加清晰度
scale: 2, // 按比例增加分辨率,默认值为1,pc端值为1,手机端值为2
allowTaint: true,
}).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 = canvas.toDataURL("image/jpeg", 1.0);
if(type==='img'){
const a = document.createElement("a");
a.href = pageData;
a.setAttribute("download", e);
a.click();
return
}
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(e + ".pdf");
});
};
},
};
三、全局引入实现方法
import htmlToPdf from '@/utils/htmlToPdf'
Vue.use(htmlToPdf)// 使用Vue.use()方法就会调用工具方法中的install方法
四、使用方法
<template>
<div id="pdfDom">
<el-button type="primary" @click="getPdfOrImg('页面','img','#pdfDom')">导出</el-button>
</div>
</template>
getPdf这个方法已经注册到全局,接受三个参数,第一个是导出的名字,第二个参数是导出的类型img or pdf,第三个是需要导出的页面的id
这里发现导出后会有个bug
elementUI的下拉框和输入框会有文字偏移的问题
目前解决办法是把版本锁定1.0.0可解决