Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Print table
<template>
<a class="button" @click.stop="printTable">
<span class="icon is-small">
<i class="fa fa-print export-button table-export-print" aria-hidden="true"
title="Print"></i>
</span>
</a>
</template>
<script>
export default {
props: ['filename', 'data', 'columns'],
methods: {
/**
* Clone link and style tags, taking into account the need to change the source
* path.
*
* @param {node} el Element to convert
*/
styleToAbs(el) {
let clone = el.cloneNode(true);
if ( clone.nodeName.toLowerCase() === 'link' ) {
clone.href = this.relToAbs( clone.href );
}
return clone.outerHTML;
},
/**
* Convert a URL from a relative to an absolute address so it will work
* correctly in the popup window which has no base URL.
*
* @param {string} href URL
*/
relToAbs(href) {
let _link = document.createElement( 'a' );
// Assign to a link on the original page so the browser will do all the
// hard work of figuring out where the file actually is
_link.href = href;
let linkHost = _link.host;
// IE doesn't have a trailing slash on the host
// Chrome has it on the pathname
if ( linkHost.indexOf('/') === -1 && _link.pathname.indexOf('/') !== 0) {
linkHost += '/';
}
return _link.protocol+"//"+linkHost+_link.pathname+_link.search;
},
addRows() {
let tr = `<tr>`;
this.columns.forEach((column) => {
tr += `<th>${column.label}</th>`;
});
return tr + `</tr>`;
},
printTable() {
let html = `<table class="table is-bordered">`;
html += `<thead>${this.addRows()}</thead>`;
html += `<tbody>`;
this.data.forEach((obj) => {
html += `<tr>`;
this.columns.forEach((column, index) => {
if (column.exportData) {
html += `<td>${column.exportData(obj)}</td>`;
} else {
html += `<td>${obj[column.name] == null ? '' : obj[column.name]}</td>`;
}
});
html += `</tr>`;
});
html += `</tbody> </table>`;
// Open a new window for the printable table
let win = window.open( '', '' );
win.document.close();
let head = `<title>${this.filename}</title>`;
[...document.querySelectorAll('style')].forEach((elem) => {
head += this.styleToAbs(elem);
});
[...document.querySelectorAll('link')].forEach((elem) => {
head += this.styleToAbs(elem);
});
win.document.head.innerHTML = head;
// Inject the table and other surrounding information
win.document.body.innerHTML = html;
// Allow stylesheets time to load
setTimeout(function () {
win.print(); // blocking - so close will not
win.close(); // execute until this is done
}, 1000);
},
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment