• 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

  • 相关阅读:
    ES6的Iterator,jquery Fn
    html4,xhtml,html5发展历史
    浏览器Range,Selection等选中文本对象
    高效的插入子节点DocumentFragment
    Vue 性能优化track-by
    JS中先有Object还是先有Function?
    Unicode 与(UTF-8,UTF-16,UTF-32,UCS-2)
    FormData、Blob、File、ArrayBuffer数据类型
    jQuery 2.0.3 源码分析 事件绑定
    记录:springmvc + mybatis + maven 搭建配置流程
  • 原文地址:https://www.cnblogs.com/vincegod/p/10552006.html
Copyright © 2020-2023  润新知