2017-05-09 51 views
1

我已經使用echarts創建了一個圖表,並希望通過使用jspdf將其包含到pdf中。 I found這樣做的一種方式可能是使用畫布,將圖形轉移到圖像上,最後將圖像包含到pdf中。但是,我無法將圖形轉移到圖像上。代碼如下:使用echarts和jspdf將圖表轉換爲pdf

<!DOCTYPE html> 
<html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> 
    <title>Balken</title> 
    <script src="echarts.js"></script> 
<link rel="stylesheet" href="style.css"> 

    </head> 
    <body> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"></script> 
    <div id="body"> 
     <div id="chart"></div> 
    </div> 

     <!-- prepare a DOM container with width and height --> 
    <div id="main" style="width: 750px;height:500px;"></div> 
    <script type="text/javascript"> 
     // based on prepared DOM, initialize echarts instance 
     var myChart = echarts.init(document.getElementById('main')); 

     // specify chart configuration item and data 
     var 

option = { 
    color: ['#3398DB'], 
    tooltip : { 
     trigger: 'axis', 
     axisPointer : {    
      type : 'shadow'   
     } 
    }, 
    grid: { 
     left: '3%', 
     right: '4%', 
     bottom: '3%', 
     containLabel: true 
    }, 
    xAxis : [ 
     { 
      type : 'category', 
      data : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], 
      axisTick: { 
       alignWithLabel: true 
      } 
     } 
    ], 
    yAxis : [ 
     { 
      type : 'value' 
     } 
    ], 
    series : [ 
     { 
      name:'Salami', 
      type:'bar', 
      barWidth: '60%', 
      data:[10, 52, 200, 334, 390, 330, 220] 
     } 
    ] 
}; 
     // use configuration item and data specified to show chart 
     myChart.setOption(option); 

     var canvas = document.getElementById("main"); 
var dataURL = canvas.toDataURL(); 

//console.log(dataURL); 

$("#exportButton").click(function(){ 
    var pdf = new jsPDF(); 
    pdf.addImage(dataURL, 'JPEG', 0, 0); 
    pdf.save("download.pdf"); 
}); 


    </script> 
<button id="exportButton" type="button">Export as PDF</button> 

    </body> 
</html> 

有什麼建議嗎?

+0

你有任何解決方案將圖表導出爲PDF? –

回答

1

我會用工具箱,保存爲圖像:

 

     ..... 
     toolbox: { 
      feature: { 
       saveAsImage : {show: true} 
      } 
     } 
    ..... 

此選項,所有現有的中,會告訴你一個圖標,圖形保存爲圖像。

Quedaria ASI: enter image description here

對於工具箱更多的選擇:http://echarts.baidu.com/echarts2/doc/option-en.html#title~toolbox

我希望它可以幫助你。

+0

非常感謝,我做到了這一點,而PNG正是我正在尋找的東西,但是如何獲得PNG /圖像URL以便我可以自動將其包含到pdf(其他元素旁邊)中,而不是獲取工具箱下載圖像? – Martin

1

我也需要這個以及商業產品,所以我沒有放棄,直到我找到解決方案。

您無法使用圖表的ID來獲取圖像的URL,而是需要搜索畫布。

($('canvas')[0]).toDataURL("image/png"); 

的通知「[0]」意味着它會給你的第一個畫布,如果你有更多的圖表只是做:搜索的

($('canvas')[0]).toDataURL("image/png"); 
($('canvas')[1]).toDataURL("image/png"); 
($('canvas')[2]).toDataURL("image/png"); 

3小時,測試以及花:)

享受!

相關問題