vue使用html2canvas和jspdf把页面元素生成pdf文件

1.npm install html2canvas jspdf --save
2.import html2canvas from ‘html2canvas’
import jsPDF from ‘jspdf’
3.使用

html2canvas(document.querySelector('#exportContent')).then(function(canvas) { 
//元素id为exportContent
        var imgData = canvas.toDataURL('image/jpeg')
        console.log(imgData)
        var img = new Image()
        img.src = imgData
        //根据图片的尺寸设置pdf的规格,要在图片加载成功时执行,之所以要*0.5是因为比例问题
        img.onload = function () {
          //此处需要注意,pdf横置和竖置两个属性,需要根据宽高的比例来调整,不然会出现显示不完全的问题
          var doc=''
          if (this.width > this.height) {
              doc = new jsPDF('l', 'mm', [this.width * 0.5, this.height * 0.5])
          } else {
              doc = new jsPDF('p', 'mm', [this.width * 0.5, this.height * 0.5])
          }
          doc.addImage(imgData, 'jpeg', 0, 0, this.width * 0.175, this.height * 0.175)  //比例可根据需要调节
          //根据下载保存成不同的文件名
          doc.save('pdf_' + new Date().getTime() + '.pdf')
        };
      })

备注:
可能遇到的问题:内容过长,会有显示不全的情况。
解决:只能把内容分开,生成多个文件。

猜你喜欢

转载自blog.csdn.net/qq_38834863/article/details/86626317