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
        })
      }

 

posted on   ChoZ  阅读(534)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示