html2canvas + jspdf 实现前端将页面内容生成 PDF
一、简易步骤(仅支持下载一页,无法分页)
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
三、补充问题:导出Img标签路径如果为跨域图片,则无法被导出。
解决途径:将跨域路径的图片改为base64图片
export function convertImgToBase64(url, callback, outputFormat) { var canvas = document.createElement('CANVAS') var ctx = canvas.getContext('2d') var img = new Image() img.crossOrigin = 'Anonymous' img.onload = function() { canvas.height = img.height canvas.width = img.width ctx.drawImage(img, 0, 0) var dataURL = canvas.toDataURL(outputFormat || 'image/jpg') callback.call(this, dataURL) canvas = null } img.src = url }
if (data.picture_file_name) { convertImgToBase64(data.picture_file_name, (base64Img) => { 使用 data.picture_file_name = base64Img }) }
分类:
实际开发遇到的问题-解决方案
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通