前端实现生成pdf文件并下载

前端实现生成pdf文件并下载

思路

通过 html2canvas 将 HTML 页面转换成图片,然后再通过 jspdf 将图片的 base64 生成为 pdf 文件

下载依赖

  1. html2canvas 把html转成图片
  2. jspdf 将图片的 base64 生成为 pdf 文件
npm i html2canvas jspdf -S

使用方式

<a-button type="primary" @click="getPdf(`文档`)">导出</a-button>
 <!-- 要转成pdf导出的html, id为resultsHuiZongTableId-->
<div class="student-info" id="resultsHuiZongTableId">
	<div class="student-info-item">姓名:张三</div>
	<div class="student-info-item">年龄:18</div>
	<div class="student-info-item">学校:xxx高中</div>
	<div class="student-info-item">班级:6班</div>
</div>
      import html2Canvas from 'html2canvas'
  	  import JsPDF from 'jspdf'

      getPdf(title) {
    
    
        return new Promise(resolve => {
    
    
            html2Canvas(document.querySelector('#resultsHuiZongTableId'), {
    
    
                allowTaint: false,
                useCORS: true, // allowTaint、useCORS只能够出现一个
                imageTimeout: 0,
                dpi: 300,  // 像素
                scale: 4,  // 图片大小
            }).then(function (canvas) {
    
    
                // document.body.appendChild(canvas)
                // 用于将canvas对象转换为base64位编码
                let pageData = canvas.toDataURL('image/jpeg', 1.0),
                    canvasWidth = canvas.width,
                    canvasHeight = canvas.height,
                    concentWidth = 500,
                    concentHeight = Math.round((concentWidth / canvasWidth) * canvasHeight),
                    position = 72,
                    pageHeight = 892,
                    height = concentHeight
                console.log(height, pageHeight)
                // 新建一个new JsPDF,A3的像素大小 842*1191,A4的像素大小 592*841。这个px像素不准确,不清楚他们的像素大小来源如何
                let PDF = new JsPDF('p', 'px', 'a3')
                if (height <= pageHeight) {
    
    
                    // 添加图片
                    PDF.addImage(pageData, 'JPEG', 68, position, concentWidth, concentHeight)
                } else {
    
    
                    while (height > 0) {
    
    
                        PDF.addImage(pageData, 'JPEG', 68, position, concentWidth, concentHeight)
                        height -= pageHeight
                        position -= pageHeight
                        if (height > 0) {
    
    
                            PDF.addPage()
                        }
                    }
                }
                // 保存 pdf 文档
                PDF.save(`${
      
      title}.pdf`)
                resolve(true)
            }).catch(() => {
    
    

            }).finally(() => {
    
    
              this.pdfExporting = false;
              console.log(88888)
            })
        })
      },

备注

jspdf 转pdf,会存在以下问题:
1、无法自动分页,需要自己计算内外边距实现分页
2、多转几页,会出现颜色、内容丢失

参考

https://www.jianshu.com/p/318285100592
https://blog.csdn.net/g_geng/article/details/126834015

猜你喜欢

转载自blog.csdn.net/Boale_H/article/details/128041452