Vue使用jsPdf將頁(yè)面導(dǎo)出成pdf文件

一、添加模塊

npm install --save html2canvas(將頁(yè)面html轉(zhuǎn)化成圖片)
npm install jspdf --save(將圖片轉(zhuǎn)換成pdf)

二、定義全局函數(shù)..創(chuàng)建一個(gè)htmlToPdf.js文件在指定位置.我個(gè)人習(xí)慣放在('src/utils/htmlToPdf')

// 導(dǎo)出頁(yè)面為PDF格式

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')

      }

      )

    }

  }

三、在main.js中使用我們定義的函數(shù)文件

import htmlToPdf from '@/components/utils/htmlToPdf'

Vue.use(htmlToPdf)

四、在需要的導(dǎo)出的頁(yè)面..調(diào)用我們的getPdf方法即可.
<el-button @click="getPdf">導(dǎo)出PDF文件</el-button>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容