安装两个三方包
npm i html2canvas
npm i jspdf
在utils文件下写入htmlToPdf.js
import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';
export default {
install(Vue, options) {
Vue.prototype.getPdf = function(title) {
var title = this.htmlTitle;
var element = document.querySelector('#pdfDom');
setTimeout(() => {
html2Canvas(element).then(function(canvas) {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
var pageHeight = (contentWidth / 592.28) * 841.89;
var leftHeight = contentHeight;
var position = 0;
var imgWidth = 595.28;
var imgHeight = (592.28 / contentWidth) * contentHeight;
var pageData = canvas.toDataURL('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(title + '.pdf');
});
}, 0);
};
}
};
main.js导入上述文件
import htmlToPdf from './utils/htmlToPdf.js';
Vue.use(htmlToPdf);
组件中导出
<button @click="getpdfyes">导出</button>
<el-table id="pdfDom" :data="tableData" style="width: 100%">
<el-table-column prop="date" label="日期" width="180">
</el-table-column>
<el-table-column prop="name" label="姓名" width="180">
</el-table-column>
<el-table-column prop="address" label="地址"> </el-table-column>
</el-table>
methods: {
getpdfyes() {
this.getPdf();
},
},