整理文档,搜刮出一个vue中将网页打印成pdf的代码,稍微整理精简一下做下分享。

<template>
<div class="pdf-wrap" id="pdfWrap">
 <button v-on:click="getPdf">点击下载PDF</button>
 <div class="pdf-dom" id="pdfDom"></div>
</div>
</template>
<style lang="scss" scoped>

</style>
<script type="text/ecmascript-6">
 import html2Canvas from '@/components/html2canvas.js'
 import JsPDF from '@/components/jsPdf.debug.js'

 export default {
  methods: {
   getPdf: function () {
    let _this = this
    let pdfDom = document.querySelector('#pdfDom')
    html2Canvas(pdfDom, {
     onrendered: 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(_this.pdfData.title + '.pdf')
     }
    })
    html2Canvas()
   },
  }
 }
</script>

需要引入

html2canvas.js'

jsPdf.debug.js

这两个插件库可轻松百度到。如果eslint验证报错,可在eslintignore中设置不对这两个文件进行验证。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com