本文讲 前端 JS 将 HTML 转图片后用 PDF 下载
缺点
- 转成的PDF是由图片生成的,而不是文字
- 文件大,打印后容易失真
下载依赖
"html2canvas": "^1.4.1",
"jspdf": "^2.5.1",
新增plugins
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
import Vue from 'vue'
const htmlToPDF = {
install(Vue, options) {
Vue.prototype.getPdf = function ( pdfDomId, htmlTitle, isVertical = true) {
const title = htmlTitle
html2Canvas(document.querySelector(`#${pdfDomId}`), {
taintTest: false,
useCORS: true,
dpi: window.devicePixelRatio * 5,
scale: 5
}).then(function (canvas) {
const contentWidth = canvas.width
const contentHeight = 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
if (!isVertical) {
pageHeight = contentWidth / 841.89 * 592.28
imgWidth = 841.89
imgHeight = 841.89 / contentWidth * contentHeight
}
canvas.setAttribute('crossOrigin', 'anonymous')
const pageData = canvas.toDataURL('image/jpeg', 1.0)
const PDF = new JsPDF(isVertical ? '' : 'l', '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 -= isVertical ? 841.89 : 595.28
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save(title + '.pdf')
})
}
}
}
Vue.use(htmlToPDF)
在nuxt.config.js中新增plugins
plugins: [
'@/plugins/htmlToPDF',
],
调用
this.getPdf('contractPdf', '文件名.pdf', false)