效果图:
![](https://i-blog.csdnimg.cn/blog_migrate/67cf4057bcbd7c71da7e25e02d20f90d.png)
环境安装
将页面html转换成图片
npm install --save html2canvas
将图片生成pdf
npm install jspdf --save
创建htmlToPdf.js
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
install(Vue, options) {
Vue.prototype.getPdf = function(idStr, title) {
html2Canvas(document.querySelector('#' + idStr), {
// allowTaint: true,
useCORS: true
}).then(function(canvas) {
let contentWidth = canvas.width
let contentHeight = canvas.height
//一页pdf显示html页面生成的canvas高度;
let pageHeight = contentWidth / 592.28 * 841.89
//生成pdf的html页面高度
let leftHeight = contentHeight
//页面偏移
let position = 0
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
let imgWidth = 595.28
let imgHeight = 592.28 / contentWidth * contentHeight
// canvas.crossOrigin="anonymous";
let pageData = canvas.toDataURL('image/jpeg', 1.0);
let PDF = new JsPDF('', 'pt', 'a4')
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围,无需分页
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文件里面进行全局定义
/*引入导出js*/
import htmlToPdf from './utils/htmlToPdf';
Vue.use(htmlToPdf);
在需要的导出的页面,调用htmlToPdf.js中getPdf方法
<div class="reportInstrument">
<div class="reportInstrumentContent1">
<el-button class="reportButton" type="info" @click="headelReport">导出报告</el-button>
</div>
</div>
//printReport为导出div部分的id
<div class="report-text" id="printReport">
<div class="lawReportcontent">
<div class="ReportTitle">
<div style="height: 50px;">
此处为需要导出为pdf的代码 图片也可放入代码中 导出后可实现盖章
</div>
</div>
</div>
</div>
/*导出PDF报告*/
//printReport为导出div部分的id,分析报告为导出PDF的文件名
headelReport(){
this.getPdf("printReport","分析报告");
},