由于项目需求,需要将html界面的报表转换成pdf输出下载。网上荡了很久,最终用的html2canvas和jspdf实现需求。
总结了下基本都是利用canvas将页面模块画成图片在转化为PDF文件。
自己实现过程中遇到一点小坑。在此将整个过程记录下来。
第一步:安装html2canvas和jspdf依赖

npm install html2canvas --save

上面一步只是安装了canvas画图工具的依赖,接着就是第一个坑了。
不知道你又没有跟我一样试了无数次的以下命令去安装jsPDF依赖
npm install jspdf --save
cnpm install jspdf --save
不管是npm,还是cnpm,结果都是:

npm ERR! path git
npm ERR! code ENOENT
npm ERR! errno ENOENT
npm ERR! syscall spawn git
npm ERR! enoent Error while executing:
npm ERR! enoent undefined ls-remote -h -t ssh://git@github.com/eligrey/FileSaver.js.git
npm ERR! enoent 
npm ERR! enoent 
npm ERR! enoent spawn git ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent 

npm ERR! A complete log of this run can be found in:
npm ERR!     E:\Program Files\nodejs\node_cache\_logs\2019-11-22T07_39_30_903Z-debug.log

上面是说,在刚开始下载资源的时候找不到对应文件。
我果断抛弃 npm install jspdf --save方式引入依赖
话不多说,cdn方式引入jspdf如下:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.debug.js"></script>

第二步 封装页面保存为PDF的全局函数
1.随便建立个js文件,代码如下[注:cpbg是页面中div的ID]

// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
//import JsPDF from 'jspdf'
export default{
  install (Vue, options) {
    Vue.prototype.getPdf = function () {
      var title = "高新技术企业认定测评报告";
      html2Canvas(document.querySelector('#cpbg'), {
        allowTaint: true
      }).then(function (canvas) {
        let contentWidth = canvas.width
        let contentHeight = canvas.height
        let pageHeight = contentWidth / 592.28 * 841.89
        let leftHeight = contentHeight
        let position = 0
        let imgWidth = 595.28
        let imgHeight = 592.28 / contentWidth * contentHeight
        let pageData = canvas.toDataURL('image/jpeg', 1.0)
        let PDF = new JsPDF('', 'pt', 'a4')
        if (leftHeight < pageHeight) {
          PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
        } else {
          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')
      }
      )
    }
  }
}

2.main.js中引入上面那个JS文件

import htmlToPdf from './components/heightTest/htmlToPdf'//页面转PDF
Vue.use(htmlToPdf)

第三步:组件中调用getPdf()即可使用

<el-button @click="getPdf()">保存为PDF</el-button>

本以为没毛病了,然而现实是残酷的。
在这里插入图片描述
在我们写的getPdf()函数中找不到JsPDF方法
精准而优雅,我打开下面链接查看源码。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.debug.js"></script>

发现了什么,JsPDF的J竟然是小写。(不能仅仅copy,也需要检查的,不过嘛,我是面向CV编程滴。)
在这里插入图片描述
就此结束啦。
温馨提示:
1、图片需要是base64格式的;
2、注意引入的pdf.js中的pdfjs方法名称大小写;
3、cdn引入的<script>这里直接在vue界面引入。

Logo

前往低代码交流专区

更多推荐