从HTML下载数据表作为图像

时间:2018-12-13 08:43:47

标签: javascript php html-table

我有一个数据表,如下所示:

<table id="example2" class="table table-bordered table-striped table-fixed">
    <thead>
        <th>Key Account</th>
        <th>Key Account Code</th>
        <th>Potential Value</th>
        <th>Sales Value</th>
        <th>Penetration %</th>
        <th>Potential (H/M/L)</th>
        <th>Penetration (H/M/L)</th>
    </thead>
    <?php echo "Some data from database here";?>   
</table>

我有一个按钮

<button id="click" >Export Image </button>

单击按钮后如何将上述数据表下载为图像?

1 个答案:

答案 0 :(得分:2)

是的,您可以使用html2canvas。然后可以将其导出到图像。参见下面的脚本:

<html>
   <head>
   </head>
   <body>
      <table id="myTable" class="table table-bordered table-striped table-fixed">
         <thead>
            <th>Key Account</th>
            <th>Key Account Code</th>
            <th>Potential Value</th>
            <th>Sales Value</th>
            <th>Penetration %</th>
            <th>Potential (H/M/L)</th>
            <th>Penetration (H/M/L)</th>
         </thead>
         <?php echo "Some data from database here";?>   
      </table>
      <button id="convert">
      Convert to image
      </button>
      <div id="result">
         <!-- Result will appear be here -->
      </div>
      <script type="text/javascript" src="https://github.com/niklasvh/html2canvas/releases/download/0.5.0-alpha1/html2canvas.js"></script>
      <script>
         //convert table to image            
         function convertToImage() {
            var resultDiv = document.getElementById("result");
            html2canvas(document.getElementById("myTable"), {
                onrendered: function(canvas) {
                    var img = canvas.toDataURL("image/png");
                    result.innerHTML = '<a download="test.jpeg" href="'+img+'">test</a>';
                    }
            });
         }        
         //click event
         var convertBtn = document.getElementById("convert");
         convertBtn.addEventListener('click', convertToImage);
      </script>
   </body>
</html>  
相关问题