uni-app点击导出pdf初体验

项目需求:打印手机端测试结果为测试报告

思路:以id为索引构建canvas,实现打印

方案:使用已封装好的组件:html2canvas、jspdf,实现html转canvas以及生成pdf

 

1.npm所需依赖:

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

2.定义全局函数,在main.js中引入,或者直接写在main中

import html2Canvas from ‘html2canvas‘
import JsPDF from ‘jspdf‘
export default{
  install (Vue, options) {
    Vue.prototype.getPdf = function () {
      var title = this.htmlTitle
      html2Canvas(document.querySelector(‘#pdfDom‘), {
        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‘)
      }
      )
    }
  }
}

3.在需要导出pdf的页面,给元素id为pdfDom(可在上方代码处修改,一一对应即可)

  <view >
        <view id="pdfDom">
            <view class="" >
                首页
            </view>
            <image src="../../static/BasicsBg.png" mode="widthFix" class="response"></image>
        </view>
        <button type="button" class="btn btn-primary"v-on:click="getPdf()">导出PDF</button>
    </view>

注意:

  1.页面data中需包含htmlTitle(导出文件名)

  2.id节点中不可包含网络图片地址,包含网络地址搜索说是要使用img的onload方法,等待图片加载完

  3.参考文档:”https://blog.csdn.net/weixin_44089042/article/details/115379621 

        https://blog.csdn.net/weixin_30668887/article/details/98822699

uni-app点击导出pdf初体验

上一篇:Allegro Inside ODB++ 安装


下一篇:mysql rename