VUE 利用html2canvas+jspdf实现HTML转PDF
Vue版本2.5.17
第一步引包
在控制台输入
npm i -s html2canvas
在index.html引入
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
第二步编写HTML
<template>
<div style="width: 592px;height: 100%;margin: auto">
<button @click="inputFun" >导出PDF</button>
<div style="width: 100%;height: 100%;position: relative">
<div id="domId" style="">
<el-table
:data="data"
border
style="width: 100%">
<el-table-column
prop="webName"
label="名称"
width="100">
</el-table-column>
<el-table-column
prop="url"
label="URL"
width="180">
<template slot-scope="scope">
<a :href="scope.row.url" class="aStyle">{{scope.row.url}}</a>
</template>
</el-table-column>
<el-table-column
prop="editTime"
label="时间"
width="150">
</el-table-column>
<el-table-column
prop="proType"
label="类型"
width="80">
</el-table-column>
<el-table-column
prop="proLevel"
label="级别"
width="80">
</el-table-column>
</el-table>
</div>
</div>
</div>
</template>
第二步JS代码
import html2canvas from "html2canvas";
/**
* 将HTML转为ODF
* @param content HTML dom对象
* @param name 文件名
*/
export function downLoadPdf(content, fileName) {
content = content ? content : null;
// 条件判断是否打印
if(!content){
this.$message({
type: 'error',
message: "打印失败,请重新操作"
});
return false
}
// 开始打印
console.log(content)
var contentWidth = content.style.clientWidth;
var contentHeight = content.style.clientHeight;
var canvas = document.createElement("canvas")
canvas.width = contentWidth
canvas.height = contentHeight
var context = canvas.getContext("2d");
html2canvas(content,{
allowTaint:true,
scale:2 // 提升画面质量,但是会增加文件大小
}).then(function(canvas){
var pdfWidth = canvas.width;
var pdfHeight = canvas.height;
var pageHeight = pdfWidth / 592.28 * 841.89;
var leftHeight = pdfHeight;
var position = 0;
var imgWidth = 595.28;
var imgHeight = 595.28 / pdfWidth * pdfHeight;
var pageData = canvas.toDataURL("img/jpeg",1.0);
var pdf = new jsPDF('', 'pt', 'a4');
// 判断打印dom高度是否需要分页,如果需要进行分页处理
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(fileName + ".pdf")
})
}
/**
* 页面点击事件
*/
inputFun() {
//获取dom
let dom = document.getElementById('domId')
//导出
downLoadPdf(dom, '文件名称')
this.loading = false
}