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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM