1. 程式人生 > >匯出PDF(四)Echarts統計圖匯出PDF檔案

匯出PDF(四)Echarts統計圖匯出PDF檔案

        根據網上所查資料顯示,目前不支援直接將Echarts統計圖匯出為PDF檔案,但是可以將統計圖轉成圖片,再將圖片轉成PDF檔案。此處使用了外掛html2canvas.min.jsjspdf.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