Echarts批量导出pdf
Echarts批量导出pdf。通过html2canvas获取Echarts的canvas容器,转化base64图片导出pdf.
安装依赖
npm i html2canvas -S
npm i html2canvas -S npm i jspdf-S
封装utils
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
/**
* 多个Echarts导出pdf文件
* 两个异步过程:
* 1、html2Canvas解析canvas
* 2、pdf渲染base64
* @param canvas 绘制Echarts Document
*/
const getPdf = () => {
let pdf = new JsPDF('', 'pt', 'a4');
const canvas = Array.from(document.querySelectorAll('.scroll-echarts-pie'))
.map(ele => {
return new Promise((resolve, reject) => {
html2Canvas(ele)
.then(canvas => {
// 图片大小根据 A4 纸张大小转换
const contentWidth = canvas.width,
contentHeight = canvas.height,
imgWidth = 595.28,
imgHeight = 592.28 / contentWidth * contentHeight;
const Base64 = canvas.toDataURL('image/jpeg', 1.0);
resolve({
Base64,
imgWidth,
imgHeight
})
})
.catch(() => {
reject('html2Canvas解析错误')
})
})
})
Promise.allSettled(canvas)
.then((results) => {
results.forEach(({ value: {
Base64,
imgWidth,
imgHeight
}}) => {
pdf.addImage(Base64, 'JPEG', 0, 0, imgWidth, imgHeight);
pdf.addPage();
})
pdf.save('Echarts.pdf');
});
}
export {
getPdf
}