1.安装print.js插件:npm install print-js --save;
2.引入插件:import * as printJS from 'print-js';
3.定义按钮:
<button nz-button nzType="primary" (click)="printButton()" style="margin-left: 10px;">打印</button>
4.按钮的触发事件:
// 打印按钮
public printButton() {
$('#printImg').show();
printJS({
printable: 'printImg',
type: 'html',
// style: style,// 亦可使用引入的外部css;
// scanStyles: false
})
$('#printImg').hide();
}
5.图片元素:
<img src="" id="printImg" style="height: 50%;width:90%;display: none;" />
6.图表相关代码:
const chartEventsTotal = ech.init(<HTMLDivElement>(document.getElementById(id)), 'macarons');
chartEventsTotal.on('finished', function () {
var img = chartEventsTotal.getDataURL();
var printImgId = document.getElementById('printImg')
printImgId.setAttribute('src', img);
});
7.原理:
将echarts的图表转换成图片赋予我们一开始定义的img元素中,然后直接利用插件就可以打印。