1.下载插件 html2canvas
2.下载插件 jspdf
3.在文件中导入
1.导入
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
2.methods代码部分
downPdf() {
let _this = this
document.documentElement.scrollTop = 0
let canvas = document.createElement('canvas') // 生成canvas上下文
let context = canvas.getContext('2d')
let _articleHtml = document.getElementById('app')
let _w = _articleHtml.clientWidth //获取需要导出pdf区域的宽度和高度
let _h = _articleHtml.clientHeight
let scale = 3
if (_w > _h) {
_h = _w
}
canvas.width = _w * scale
canvas.height = _h * scale
context.scale(scale, scale)
let opts = {
scale: 1,
width: _w, //dom 原始宽度
height: _h,
canvas: canvas,
useCORS: true, //允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
}
// 以上部分都是为了强化清晰度的,放大canvas画布
html2canvas(_articleHtml, opts).then((canvas) => {
_this.createPdfAll(canvas, scale)
})
},
createPdfAll(canvas, scale) {
let contentWidth = canvas.width / scale
let contentHeight = canvas.height / scale
let pdf = new jsPDF('', 'pt', [contentWidth, contentHeight]) //自定义宽高
let pageData = canvas.toDataURL('image/jpeg', 1.0) //转换图片为dataURL
pdf.addImage(pageData, 'JPEG', 0, 0, contentWidth, contentHeight) //添加图像到页面
pdf.save(`123.pdf`)
},
createPdfPage(canvas) {
let contentWidth = canvas.width
let contentHeight = canvas.height
let pageHeight = (contentWidth / 592.28) * 841.89
let leftHeight = contentHeight
// pdf页面向上偏移
let position = 0
// a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
let imgWidth = 595.28
let imgHeight = (592.28 / contentWidth) * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0) //转换图片为dataURL
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(`${this.detail.title}.pdf`)
},
3.html部分代码
<div class="popover-item flex" @click="downPdf">
123123
</div>
字数太少啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊