根据网上所查资料显示,目前不支持直接将Echarts统计图导出为PDF文件,但是可以将统计图
转成图片,再将图片转成PDF文件。此处使用了插件html2canvas.min.js及jspdf.min.js:
document.write("<script type='text/javascript' src='./topdf/html2canvas.min.js'></script>");
document.write("<script type='text/javascript' src='./topdf/jspdf.min.js'></script>");
document.write("<script type='text/javascript' src='./topdf/echarts.min.js'></script>");
var myChart = echarts.init(document.getElementById('main'));
var option = {
backgroundColor: 'white',
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'line',
data: [5, 20, 36, 10, 10, 20]
}]
};
myChart.setOption(option);
function convertCanvasToImage() {
html2canvas(document.getElementById('main'), {
onrendered: function(canvas) {
/* document.body.appendChild(canvas); */
createPDFObject(canvas.toDataURL("image/jpeg"));
}
});
}
function createPDFObject(imgData) {
//默认a4纸张
var doc = new jsPDF('p', 'pt',"a3");
doc.addImage(imgData, 5, 5, 600, 300, 'img');
doc.save('GCXDATA_PDF.pdf');
}
<div id="main" style="height:400px"></div>
<button onclick="convertCanvasToImage()">download pdf</button>
参考:https://segmentfault.com/a/1190000011478657
https://segmentfault.com/q/1010000013080174
补充在VUE中的使用情况:
在package.json文件中加入以下依赖:
"dependencies": {
"html2canvas": "^1.0.0-rc.5",
"jspdf": "^1.5.3"
}
代码段:
// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
function getPdf(title) {
html2Canvas(document.querySelector('#main'), {
allowTaint: true
}).then(function(canvas) {
let contentWidth = canvas.width
let contentHeight = canvas.height
let pageHeight = contentWidth / 592.28 * 841.89
let leftHeight = contentHeight
let position = 0
let imgWidth = 595.28
let imgHeight = 592.28 / contentWidth * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0)
let PDF = new JsPDF('', 'pt', 'a4')
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save(title + '.pdf')
})
}
export {
getPdf
}
将以上代码段封装成 getPdf.js 并在页面中引用:
import {
getPdf
} from '../../../assets/function/tool/htmlToPdf.js';
同时在页面按钮进行点击调用:
downloadReprot() {
// 下载过程中进行锁屏
const loading = this.$loading({
lock: true,
text: '请稍等,下载中.....',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
getPdf("巡检报告" + this.baseInfo.nowTime);
// 关闭锁屏
loading.close();
}