2017-05-09 784 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小时,测试以及花:)

享受!