html2canvas+jspdf导出html代码为pdf⽂件
由于项⽬需求需要导出页⾯内容为pdf⽂件,最开始的思路是调⽤后端接⼝,但是由于接⼝跨域问题导致调⽤失败经过多⽅⾯沟通后决定前端完成导出。思路:使⽤html2canvas先将指定代码⽚段转为canvas图⽚,然后再将canvas使⽤jspdf转为pdf⽂件下载(上代码)。
1.引⼊html2canvas和jspdf的包
2.新建pdf.js⽤于定义html2canvas 和 jspdf的配置
import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';
export default {
install(Vue) {
Pdf = function(dom, title) {
let that = this;
let width = document.querySelector(dom).clientWidth; //获取dom 宽度
let height = document.querySelector(dom).clientHeight; //获取dom ⾼度
document.querySelector(dom).lor = '#000';//默认导出时页⾯的字体更改为⿊⾊,防⽌页⾯字体为⽩⾊时导出的pdf看不到字体
console.log(document.querySelector(dom));
console.log(width);
console.log(height);
let canvas = ateElement('canvas'); //创建⼀个canvas节点
let scale = 1; //定义任意放⼤倍数⽀持⼩数
canvas.width = width * scale; //定义canvas 宽度 * 缩放
canvas.height = height * scale; //定义canvas⾼度 *缩放
let opts = {
tainttest: true, //检测每张图⽚都已经加载完成
scale, // 添加的scale 参数
useCORS: true,
canvas, //⾃定义 canvas
logging: true, //⽇志开关
width, //dom 原始宽度
height, //dom 原始⾼度
};
html2Canvas(document.querySelector(dom), {
allowTaint: true,
.
..opts,
}).then(function(canvas) {
console.log(canvas);
let contentWidth = canvas.width;
let contentHeight = canvas.height;
console.log(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 = DataURL('image/jpeg');
let PDF = new JsPDF('', 'pt', 'a4');
// return
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');
that.isPrint = true;
});
};
},
};
//vue⽂件使⽤
<template>
<div>
<div class="export" @click="download()">导出</div>
</div>
div  id="pdfDoms"  ref="pdfDom"  v-html="rich"></div>
</template>
<script>
import html2canvas from 'html2canvas';
import JSPDF from 'jspdf';
export default{
data(){
return{
};
},
methods(){
download() {
pdf转html
setTimeout(() => {
this.$refs.lor = '#fff';//这⾥的字体颜⾊设置为页⾯的字体颜⾊,导出后将页⾯字体颜⾊更改为原来的字体颜⾊          }, 500);
},
renderHtmlToImage(c) {
html2canvas(c, {
allowTaint: true,
//scale: 4, // 提升导出⽂件的分辨率
}).then(canvas => {
// var doc = new jsPDF('l', 'pt', [canvas.width / 2, imgheight])
let pdf = new JSPDF();
//addImage后两个参数控制添加图⽚的尺⼨,此处将页⾯⾼度按照a4纸宽⾼⽐列进⾏压缩
pdf.addImage(
'JPEG',
0,
0,
595.28,
(592.28 / canvas.width) * canvas.height,
);
pdf.save('stone.pdf');
});
},
},
}
</script>