使用JQuery将表下载为PNG

时间:2016-07-17 21:07:09

标签: javascript jquery html download

我想下载一个html表格作为PNG图像,我找到了一种方法,使用JQuery将表格提取为图像,但它在新标签页中打开,不自动下载我必须使用右键单击然后保存为图像能够下载它。

有没有办法让它自动下载?

这是用于导出为PNG图像的JQuery

Intent intent = new Intent(MainActivity.this, NewScreenActivity.class);
startActivity(intent);

1 个答案:

答案 0 :(得分:2)

为了执行此操作并强制浏览器将数据作为文件下载,您必须将mime类型从data:image更改为data:application/octet-stream。您需要创建自己的html2canvas转化并手动处理onrendered事件。然后在onrendered事件处理函数内部,存储画布数据url。之后,使用正则表达式将base64数据mime类型从data:image更改为data:application/octet-stream。然后您可以使用window.open(uri)强制浏览器下载文件,但是如果要指定文件名,则需要创建一个锚链接元素并使用您想要的文件名设置下载属性:

<强> HTML:

<table id="preview-table">
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>


<button id="export">Table Export</button>

<强> CSS:

table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}

<强>使用Javascript:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="tableExport.jquery.plugin/html2canvas.js"></script>

<script type="text/javascript">

$('#export').on('click', function() {
    html2canvas($('#preview-table'), {
        onrendered: function(canvas) {                                      

            var saveAs = function(uri, filename) {
                var link = document.createElement('a');
                if (typeof link.download === 'string') {
                    document.body.appendChild(link); // Firefox requires the link to be in the body
                    link.download = filename;
                    link.href = uri;
                    link.click();
                    document.body.removeChild(link); // remove the link when done
                } else {
                    location.replace(uri);
                }
            };

            var img = canvas.toDataURL("image/png"),
                uri = img.replace(/^data:image\/[^;]/, 'data:application/octet-stream');

            saveAs(uri, 'tableExport.png');
        }
    }); 
});

</script>

您可以在这里找到一个有效的例子:http://zikro.gr/dbg/html/tableExport/

Check Rob W's answer on Browser/HTML Force download of image from src=“data:image/jpeg;base64…”Reddy's answer on Save file Javascript with file name [duplicate]