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>
    
  • 相关阅读:
    C#中递归算法的总结
    C# 创建错误日志
    获取指定路径下所有PDF文件的总页数
    C# 将文件转为字符串和将字符串转为文件的方法
    如何获得应用程序的物理路径
    C#中获得文件夹下所有文件的两种方法
    C#中加密与解密
    MacOS系统使用Homebrew官方地址报错
    privoxy代理服务器配置
    Nginx 反向代理 502 permission denied 解决
  • 原文地址:https://www.cnblogs.com/miaSlady/p/13559411.html
Copyright © 2011-2022 走看看