javascript - 从 HTML 下载数据表作为图像

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

点击按钮后如何将上面的数据表下载为图片?

最佳答案

是的你可以使用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>  

关于javascript - 从 HTML 下载数据表作为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53757970/

相关文章:

javascript - 获取 $.ajax jquery 成功后返回的数据

javascript - JS Unpacker via PHP - 函数(p,a,c,k,e,r)

javascript - ECMAScript6 AngularJS 过滤器

javascript - 粗箭头函数 (=>) 的语法,在主体周围使用或不使用 {}

PHP文件上传

php - 尝试创建新项目时出现 Symfony 错误 : Fatal error: Uncaught Symfony\Component\Dotenv\Exception\PathException: Unable to read . env

php - Magento - 在产品创建观察者之前获取商店 ID

html - 如何在没有移位标题的情况下将静态标题和可变文本设置到屏幕中心

html - CSS 表格默认填充或边距

html - Div 中的表 Div 中的表