1. 安装html2canvas和jsPDF
npm install html2canvas --save
npm install jsPDF --save
2.配置
可以选择在main.js中直接全局引入并挂载
import html2canvas from 'html2canvas'
import jsPDF from 'jsPDF '
Vue.prototype.html2canvas = html2canvas
Vue.prototype.jsPDF = jsPDF
也可以选择中直接引入
import html2canvas from 'html2canvas'
import jsPDF from 'jsPDF '
or
<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
<script src="https://cdn.bootcss.com/jspdf/1.3.4/jspdf.debug.js"></script>
3.上代码,分页和不分页都注释了
html部分:<div ref="toPdf"></div>
js部分:html2canvas(this.$refs.toPdf, {
// [具体属性配置可以去html2canvas官网看看](https://html2canvas.hertzen.com/configuration)
allowTaint: true, // 允许跨域
scale: 1, // 提高清晰度可设置2,正常设置为1就行
}).then((res) => {
// 获取html的宽高
let contentWidth = res.width;
let contentHeight = res.height;
// 不分页做法
// var pageData = res.toDataURL('image/jpeg', 1.0)
// var pdf = new jsPDF("p", "pt", [contentWidth, contentHeight]); //第三个参数直接设置宽高
// var position = 0
// pdf.addImage(pageData, 'JPEG', 0, position, contentWidth, contentHeight)
// 分页做法,一般按a4纸[595.28,841.89]
// var pageHeight = contentWidth / 595.28 * 841.89
// var leftHeight = contentHeight
// var position = 0
// var imgWidth = 595.28
// var imgHeight = 595.28 / contentWidth * contentHeight
// var pageData = canvas.toDataURL('image/jpeg', 1.0)
// var pdf = new jsPDF("p", "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 > 10) {
// pdf.addPage()
// }
// }
// }
// 导出
pdf.save('xxx.pdf')
// 预览
// pdf.output('dataurlnewwindow', "xxx.pdf");
});