将html转为pdf()

需引入:  

import html2canvas from "html2canvas";
import JsPDF from "jspdf"; 

 注意:图片资源跨域时,将图片转为base64格式:https://blog.csdn.net/qq_37899792/article/details/102600293

/**
* Created by LiChenGuang on 2019/6/23
*/
<comment>
  # 组件注释
  生产报表模板
</comment>
<template>
  <div class="ReportCtainer">
    <div class="configBtn">
      <el-button type="success" size="small" @click="savecanvas" style="margin-left:15px">
        <i class="el-icon-download"></i> 下载
      </el-button>
    </div>

    <div id="ReportContent">
      <div class="canvas" id="printcontent" ref="canvas">
      </div>
    </div>
  </div>
</template>

<script>
  //reportDetail
  import {baseinUrl, reportDetail} from "../api/system_interface.js";
  import html2canvas from "html2canvas";
  import JsPDF from "jspdf";
  export default {
    name: "ReportContent",
    components: {
      StartEndPage,
      ContentPage,
      WorkLists,
      StatisticsCard,
      ProjectDetail,
      EchartsPage,
      subLine,
      subBar,
      subPie,
      subLineArea
    },
    props: {},
    data() {
      return {
        
        rowData: {}
      };
    },
    computed: {},
    created() {
    },
    mounted() {
    },
    watch: {},
    methods: {
      
      // 保存
      savecanvas() {
        const cntElem = this.$refs.canvas;
        let shareContent = cntElem; //需要截图的包裹的(原生的)DOM 对象
        let width = shareContent.offsetWidth; //获取dom 宽度
        let height = shareContent.offsetHeight; //获取dom 高度
        let canvas = document.createElement("canvas"); //创建一个canvas节点
        let scale = 2; //定义任意放大倍数 支持小数
        canvas.width = width * scale;
        canvas.height = height * scale;
        canvas.getContext("2d").scale(scale, scale); //获取context,设置scale
        let context = canvas.getContext("2d");
        context.translate(
          "-" + shareContent.offsetLeft,
          "-" + shareContent.offsetTop
        );
        let opts = {
          dpi: window.devicePixelRatio * scale,
          scale: scale, // 添加的scale 参数
          canvas: canvas, //自定义 canvas
          logging: false, //日志开关,便于查看html2canvas的内部执行流程
          width: width, //dom 原始宽度
          height: height,
          useCORS: true // 【重要】开启跨域配置
        };
        html2canvas(shareContent, opts).then(canvas => {
          let context = canvas.getContext("2d");
          // 【重要】关闭抗锯齿
          context.mozImageSmoothingEnabled = false;
          context.webkitImageSmoothingEnabled = false;
          context.msImageSmoothingEnabled = false;
          context.imageSmoothingEnabled = false;
          this.savePDF(canvas); //pdf
          // this.saveFile(canvas);//图片
        });
      },
      /**
       * 保存为图片下载
       * @param canvas
       */
      saveFile(canvas) {
        let type = "png";
        let imgData = canvas.toDataURL(type);
        // 照片格式处理
        let _fixType = function (type) {
          type = type.toLowerCase().replace(/jpg/i, "jpeg");
          let r = type.match(/png|jpeg|bmp|gif/)[0];
          return "image/" + r;
        };
        imgData = imgData.replace(_fixType(type), "image/octet-stream");
        let filename = "报表" + "." + type;
        let save_link = document.createElementNS(
          "http://www.w3.org/1999/xhtml",
          "a"
        );
        save_link.href = imgData;
        save_link.download = filename;
        let event = document.createEvent("MouseEvents");
        event.initMouseEvent(
          "click",
          true,
          false,
          window,
          0,
          0,
          0,
          0,
          0,
          false,
          false,
          false,
          false,
          0,
          null
        );
        save_link.dispatchEvent(event);
      },
      /**
       * 保存为pdf下载
       * @param canvas
       */
      savePDF(canvas) {
        console.log(canvas);
        let contentWidth = canvas.width;
        let contentHeight = canvas.height;
        let pageHeight = (contentWidth / 595) * 840;
        let leftHeight = contentHeight;
        let position = 0;
        let imgWidth = 595;
        let imgHeight = (595 / 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 -= 840;
            if (leftHeight > 0) {
              PDF.addPage();
            }
          }
        }
        PDF.save("生产报表(" + this.rowData.reportTimeRange + ").pdf");
      }
    },
    destroyed() {
    }
  };
</script>

<style lang="scss">
  .ReportCtainer {
    position: relative;
    .configBtn {
      position: absolute;
      top: -40px;
    }
  }

  #ReportContent {
    font-variant: normal;
    width: 100%;
    height: 700px;
    overflow-y: auto;
    margin-bottom: 10px;
    .canvas {
      width: 595px;
      height: auto;
      min-height: 840px;
    }
    .save_btn {
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      width: 300px;
      height: 50px;
      background: #333333;
      line-height: 1.44rem;
      text-align: center;
      font-size: 0.3733rem;
    }
  }

  .pdf {
    width: 595px;
    height: 840px;
    min-height: 840px;
  }

  .pdf-bg-1 {
    @include bg_color_1();
  }

  .pdf-bg-2 {
    @include bg_color_2();
    background-size: 100% 100%;
  }

  .over {
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
  }
</style>
发布了180 篇原创文章 · 获赞 23 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_37899792/article/details/102601152