In order to do this and force the browser to download the data as file, you have to change the mime type from data:image
to data:application/octet-stream
. You need to create your own html2canvas
conversion and handle the onrendered
event manually. Then inside onrendered
event handler function, you store the canvas data url. After that, use regular expression to change the base64 data mime type from data:image
to data:application/octet-stream
. Then you can use window.open(uri)
to force the browser to download the file, but if you want to specify a filename, you need to create a anchor link element and set the download attribute with the filename you desire:
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>
Here you can find a working example: http://zikro.gr/dbg/html/tableExport/
Check Rob W's answer on Browser/HTML Force download of image from src=“data:image/jpeg;base64…” and Reddy's answer on Save file Javascript with file name [duplicate]