html2canvas + jspdf 实现html下载为pdf

530 阅读2分钟

一、安装

npm install --save html2canvas
npm install --save jspdf

二、实现下载方法

htmlToPdf: function (id, title) {
      this.$message(title+'生成中...');
      const element = document.getElementById(`${id}`)
      const opts = {
     //   scale: 12, // 缩放比例,提高生成图片清晰度,设置后导致超过一页时页面内容空白,所以删除
        useCORS: true, // 允许加载跨域的图片
        allowTaint: false, // 允许图片跨域,和 useCORS 二者不可共同使用
        tainttest: true, // 检测每张图片已经加载完成
        logging: true, // 日志开关,发布的时候记得改成 false
       // backgroundColor:'#fff',  //设置打印页面的背景颜色
      }
      //设置打印的文字颜色为黑色   
      // element.style.color="#000"
      html2Canvas(element, opts)
        .then((canvas) => {
            //恢复页面打印的颜色 
          // element.style.color="#fff"
          console.log(canvas)
         
          const contentWidth = canvas.width
          const contentHeight = canvas.height
          // 一页pdf显示html页面生成的canvas高度;
          const pageHeight = (contentWidth / 592.28) * 841.89
          // 未生成pdf的html页面高度
          let leftHeight = contentHeight
          // 页面偏移
          let position = 0
          // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
          const imgWidth = 595.28
          const imgHeight = (592.28 / contentWidth) * contentHeight
          const pageData = canvas.toDataURL('image/jpeg', 1.0)
          console.log(pageData)
          // a4纸纵向,一般默认使用;new JsPDF('landscape'); 横向页面
          const PDF = new JsPDF('', 'pt', 'a4')

          // 当内容未超过pdf一页显示的范围,无需分页
          if (leftHeight < pageHeight) {
            // addImage(pageData, 'JPEG', 左,上,宽度,高度)设置
            PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
          } else {
            // 超过一页时,分页打印(每页高度841.89)
            while (leftHeight > 0) {
              PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
              leftHeight -= pageHeight
              position -= 841.89
              if (leftHeight > 0) {
                PDF.addPage()
              }
            }
          }
          PDF.save(title + '.pdf')
           this.$message({
                        message: title+'下载中...',
                        type: 'success'
                    });
        })
        .catch((error) => {
           this.$message({
                            message: title+'下载失败,请稍后重试',
                            type: 'warning'
                        });
          console.log('打印失败', error)
        })
    }

三、批量下载

download: function () {
    
     // this.htmlToPdf('pdfDom', '个人报告')
        this.loading = true;
        let arr2=[];
        for(var i=0;i<this.pdfList.length;i++){
         
          const p = new Promise((resolve, reject) => {
              let temp = this.pdfList[i];
              //模拟接口时间
              setTimeout(() => { 
                  //此时i全是length值 , 需要在上面缓存i值
                  console.log(temp,i)           
                  this.htmlToPdf(temp, temp+'报告')
                  resolve('result');
              },
              3000);
          }) 
          arr2.push(p) 
        }
        Promise.all(arr2).then((result) => {
             this.loading = false;
          }).catch(err=>{
            this.$message({
              message: '请求失败,请稍后重试',
              type: 'warning'
            });
          })
    },

四、页面代码

<el-button
        type="primary"
        @click="download"
 >下载</el-button
 
 <div id="downloadWrap">
         <div v-for="item in pdfList" :key="item"> 
            //需要打印的报告内容
            <download-div :id="item" :post-title="item"></download-div>
        </div>
 </div>
export default {
  ...
  data () {
    return {
        loading:false,
        pdfList:[
            'reportA','reportB','reportC','reportD'
        ]      
    }
  },
  ...

五、参考网站

html2canvas :html2canvas.hertzen.com

jsPDF:artskydj.github.io/jsPDF/docs/…

六、参考文档

作者:issyqaaa
链接:juejin.cn/post/684490… 来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

作者:宜简
链接:juejin.cn/post/709036… 来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。