1.安装两个插件
npm install html2canvas -S npm install jspdf -S
2.在utils文件夹中创建方法htmlToPdf.js:
import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
install(Vue) {
Vue.prototype.getPdfFromHtml = function (ele, pdfFileName) {
let eleW = ele.offsetWidth
let eleH = ele.scrollHeight
let eleOffsetTop = ele.offsetTop
let eleOffsetLeft = ele.offsetLeft
var canvas = document.createElement("canvas")
var abs = 0
let win_in = document.documentElement.clientWidth || document.body.clientWidth
let win_out = window.innerWidth
if (win_out > win_in) {
abs = (win_out - win_in) / 2
}
canvas.width = eleW * 2
canvas.height = eleH * 2
var context = canvas.getContext("2d")
context.scale(2, 2)
context.translate(-eleOffsetLeft - abs, -eleOffsetTop)
html2canvas(ele, {
dpi: 300,
scale:2,
useCORS: true
}).then(canvas => {
var contentWidth = canvas.width
var contentHeight = canvas.height
var pageHeight = (contentWidth / 592.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("", "pt", "a4")
if (leftHeight < pageHeight) {
pdf.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
pdf.addImage(pageData, "JPEG", 5, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
if (leftHeight > 0) {
pdf.addPage()
}
}
}
pdf.save(pdfFileName + ".pdf")
})
}
}
}
3.main.js配置:
import htmlToPdf from "@/utils/htmlToPdf.js"
Vue.use(htmlToPdf)
4.页面使用:
节点:
<div id="demo ref="sprintReport">
方法:
this.getPdfFromHtml(document.querySelector('#demo'),'招标公告.pdf');