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 'html2canvas'
import JSPDF from 'jspdf'

export default {
  name: 'home',

  components: {
    chead
  },
  data () {
    return {
      msg: 'home'
    }
  },
  methods: {
    getPdf: () => {
      let pdfDom = document.querySelector('#home')
      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('123.pdf')
        }
      })
      html2canvas()
    }
  },
  mounted () {
    this.$nextTick(() => {
      window.addEventListener('resize', () => {
        this.getPdf()
      })
    })
  }
}

</script>

首先需要需要

yarn add html2canvas jspdf

转载于:https://my.oschina.net/xuexipython/blog/967543

    原文作者:chenglinzi2356
    原文地址: https://blog.csdn.net/chenglinzi2356/article/details/100909719
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞