angular5 引入 html2canvas 组件库 实现下载和打印的功能

1. angular5 引入

  npm install --save html2canvas

2. component或者service中使用(angular5使用typescript)

import * as html2canvas from 'html2canvas';

下载的方法实现如下:(es6 promise方式实现)

#element: 页面某个元素 如div的class name=".report-view"

public download(element, fileName): void {

    html2canvas(document.querySelector(element)).then(canvas => {

      var img = canvas.toDataURL("image/png");

      let a = document.createElement("a");

      a.href = img;

      a.download = fileName + ".png";

      document.body.appendChild(a);

      a.click();

      a.remove();

    });

}

调用方式: 

download(".report-view", this.title);

打印功能的实现:

public print(element): void {

    let title = this.printTitle;

    var printWindow = window.open();

    html2canvas(document.querySelector(element)).then(canvas => {

      var compress = document.createElement('canvas');

      // change the image size

      compress.width = canvas.width;

      compress.height = canvas.height;

      var imageStr = canvas.toDataURL("image/png");

      var image = new Image();

      image.src = imageStr;

      image.onload = function () {

        compress.getContext("2d").drawImage(image, 0, 0, compress.width, compress.height);

        var imgString = compress.toDataURL("image/png");

        var iframe = '<iframe src="' + imgString + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; 100%; height:100%;" allowfullscreen></iframe>'

        printWindow.document.open();

        printWindow.document.write("<head><title>" + title +"</title></head>");

        printWindow.document.write(iframe);

        printWindow.document.close();

        printWindow.onload = function() {

          printWindow.print();

        };

        printWindow.focus();

      }

    });

}

调用方式: 

print(".report-view", this.title);

参考资料

1. http://html2canvas.hertzen.com

原文地址:https://www.cnblogs.com/vincegod/p/10552006.html