vue 将页面转为pdf 打印下载(即使有滚动也ok)

1.引入插件
"html2canvas": "^1.0.0-rc.7",
    "jspdf": "^2.0.0",
2.在src/components/utils/htmlToPdf
// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default{
  install (Vue) {
    Vue.prototype.getPdf = function (id,title) {
      html2Canvas(document.querySelector(id), {
        allowTaint: true
      }).then(function (canvas) {
        let contentWidth = canvas.width
        let contentHeight = canvas.height
        console.log(11,contentWidth,contentHeight);
        let pageHeight = contentWidth / 592.28 * 841.89
        let leftHeight = contentHeight
        console.log(22,pageHeight,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')
      }
      )
    }
  }
}
3.页面调用
<template>
  <div class="home">
    <button type="button" class="btn btn-primary" v-on:click="getPdf('#subOutputRank','我的pdf')">
      导出PDF
    </button>
    <div class="box">
      <div class="getPDF imgArea" id="subOutputRank" ref="custom_table">
        <p class="item">11</p>
        <p class="item">22</p>
        <p class="item">33</p>
        <p class="item">44</p>
      </div>
    </div>
    
  </div>
</template>


<script>
export default {
  data (){
    return {
    };
  },
  methods:{},
  mounted(){},
}

</script>

<style lang='less' scoped>
.box{
  overflow: scroll;
  height: 100vh;
}
.item{
   100%;
  height: 500px;
  font-size: 200px;
  margin-bottom:10px;
  background: pink;
}
</style>
原文地址:https://www.cnblogs.com/miaSlady/p/13559411.html