- npm i html2canvas
- npm i jspdf
- 创建一个js文件
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
const htmlPdf = {
getPdf(title, html) {
html2Canvas(html, {
allowTaint: false,
taintTest: false,
logging: false,
useCORS: true,
dpi: window.devicePixelRatio * 4,
scale: 4,
}).then((canvas) => {
const pdf = new JsPDF('p', 'mm', 'a4')
const ctx = canvas.getContext('2d')
const a4w = 190
const a4h = 200
const imgHeight = Math.floor((a4h * canvas.width) / a4w)
let renderedHeight = 0
while (renderedHeight < canvas.height) {
const page = document.createElement('canvas')
page.width = canvas.width
page.height = Math.min(imgHeight, canvas.height - renderedHeight)
page
.getContext('2d')
.putImageData(
ctx.getImageData(
0,
renderedHeight,
canvas.width,
Math.min(imgHeight, canvas.height - renderedHeight)
),
0,
0
)
pdf.addImage(
page.toDataURL('image/jpeg', 1.0),
'JPEG',
10,
10,
a4w,
Math.min(a4h, (a4w * page.height) / page.width)
)
renderedHeight += imgHeight
if (renderedHeight < canvas.height) {
pdf.addPage()
}
}
pdf.save(`${
title}.pdf`)
})
},
}
export default htmlPdf
页面在调用这个方法就可以了
<template>