一、简易步骤(仅支持下载一页,无法分页)
1.下载插件模块
npm install html2canvas jspdf --save
2.编写代码
import html2canvas from 'html2canvas' // 引入插件 import {jsPDF} from 'jspdf'
// html2canvs jspdf pdf文件下载 export const downloadPdf = (dom, name = 'pdf', isPaging = true, format) => { // dom是传入要下载的dom,ispaging是否分页,format是下载格式 return new Promise(async (resolve, reject) => { if (!dom) { throw new Error('dom is require') } const canvas = await html2canvas(dom, { useCORS: true, allowTaint: true }).catch((err) => reject(err)) const link = canvas.toDataURL('image/png', 1) const canvasWidth = canvas.width / 2 const canvasHeight = canvas.height / 2 const leftMargin = 15 const heightMargin = 15 const size = isPaging ? (format || 'a4') : [canvasWidth, canvasHeight] // 分页则自己传页面格式,默认A4不分页默认下载整张图片
//默认A4目前只能默认下载一页A4纸,若该dom超过A4纸,则自动截至图片无法生成超过A4纸部分
// eslint-disable-next-line new-cap
const pdf = new jsPDF('p', 'pt', size)
pdf.addImage(link, 'PNG', leftMargin, heightMargin, canvasWidth, canvasHeight)
pdf.save(name + '.pdf') resolve() })
}
二、扩展详解 https://blog.csdn.net/qq_45613931/article/details/124132717