前端实现html转pdf

  优秀文章:

前端实现 HTML 转 PDF 并导出 - 掘金 (juejin.cn)icon-default.png?t=N2N8https://juejin.cn/post/7012049739482923039

安装

npm install html2canvas jspdf --save

main.js导入:

import htmlToPdf from './utils/htmlToPdf'
Vue.use(htmlToPdf)

html2Canvas.js文件:

// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'

export default {
  install(Vue, options) {
    Vue.prototype.getPdf = function(callback) {
      var title = this.htmlTitle
      html2Canvas(document.querySelector('#pdfDom'), {
        allowTaint: true
      }).then(function(canvas) {
        let contentWidth = canvas.width
        let contentHeight = canvas.height
        // let contentHeight = canvas.height
        let pageHeight = (contentWidth / 592.28) * 841.89

        // console.log(pageHeight)
        // let pageHeight = 10000000
        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')
        if(callback){
          callback(PDF)
        }
      })
    }
  }
}

在要使用的vue组件中使用:

要导出pdf的html最外边设置id: 

 

按钮点击: 

 <a-button
        type="primary"
        v-on:click="exportPdf()"
        :loading="loading"
        style="float:right;marginTop:20px"
      >生成PDF</a-button>
    exportPdf() {
      debugger
      let callback = pdf => {
        const dataUri = pdf.output('dataurlstring')
        const base64 = dataUri.split('base64,')[1]
        const data = {
          data: base64,
          reportId: this.reportId
        }
        postAction('report-center/monthlyReport/uploadFile', data).then(res => {
          this.visible = false
          this.$i18n.locale = ZH
          this.$message.success('成功')
        })
      }
      this.getPdf(callback)
    },

猜你喜欢

转载自blog.csdn.net/qq_45530512/article/details/130103308