从HTML下载数据表作为图像

问题描述 投票:1回答:1

我有一个数据表如下:

<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>

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

javascript php html-table
1个回答
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>  
© www.soinside.com 2019 - 2024. All rights reserved.