Skip to content

Instantly share code, notes, and snippets.

@itzikbenh
Created December 10, 2017 16:34
Show Gist options
  • Save itzikbenh/adb6dd59da90f8f6f539e3a7cb4a5754 to your computer and use it in GitHub Desktop.
Save itzikbenh/adb6dd59da90f8f6f539e3a7cb4a5754 to your computer and use it in GitHub Desktop.
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