vue将HTML转PDF导出(纯干货)

第〇步:效果

返参格式

image.png

导出格式(此时为PDF文件)

image.png

步骤一

npm 安装 html2canvas 和 jspdf

npm install html2canvas jspdf --save

步骤二

在某文件夹中创建名为htmlToPdf.js的文件

image.png

htmlToPdf.js中的代码如下:

// 导出页面为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中按路径引入并注册

import htmlToPdf from '@/mixin/htmlToPdf.js'
// 使用Vue.use()方法就会调用工具方法中的install方法
Vue.use(htmlToPdf)

步骤四

绑定id,且在导出按钮上加入getPdf导出方法。在data中定义导出pdf文件名,及接收html代码变量:pageData

<div id="pdfDom">
    <div v-html="pageData"></div>
</div>
<el-button  @click="getPdf('#pdfDom')" size="mini" class="margin-3 width-80" plain>导出</el-button>
export default {
    data() {
        return {
            pageData:null,  //接收html格式代码
            htmlTitle: '导出PDF的标题',
        }
    }
}

大功告成,祝君成功。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容