加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:10:26 所属栏目:安全 来源:网络整理
导读:1. angular5 引入 npm install --save html2canvas 2. component或者service中使用(angular5使用typescript) import * as html2canvas from ‘html2canvas‘; 下载的方法实现如下:(es6 promise方式实现) #element: 页面某个元素 如div的class name=".report-

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,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; width: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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读