zoukankan      html  css  js  c++  java
  • 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>
    
  • 相关阅读:
    CSS知识点总结(一)
    HTML知识点总结(二)
    HTML/CSS 基础知识总结(一)
    Nodejs 发送邮件
    Nodejs 发送短信验证码
    Nodejs 上传下载功能的实现(同步)
    Nodejs报错集
    Nodejs的安装及配置
    nodejs+bootstrap实现分页效果
    切换Mac默认PHP版本为MAMP
  • 原文地址:https://www.cnblogs.com/miaSlady/p/13559411.html
Copyright © 2011-2022 走看看