How To Print A Part Of A Vue Component Without Losing The Style
I want to print some content from a vue component. For example from the following snippet, I would like to print the v-card-text element which also has an id of #print: However,wh
Solution 1:
You need to copy over the styles from the original document. Try something like this:
// Get HTML to print from element
const prtHtml = document.getElementById('print').innerHTML;
// Get all stylesheets HTML
let stylesHtml = '';
for (const node of [...document.querySelectorAll('link[rel="stylesheet"], style')]) {
stylesHtml += node.outerHTML;
}
// Open the print window
const WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(`<!DOCTYPE html>
<html>
<head>
${stylesHtml}
</head>
<body>
${prtHtml}
</body>
</html>`);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
Solution 2:
Install this package vue-html-to-paper
npm install vue-html-to-paper
usage:
importVuefrom'vue';
importVueHtmlToPaperfrom'vue-html-to-paper';
const options = {
name: '_blank',
specs: [
'fullscreen=yes',
'titlebar=yes',
'scrollbars=yes'
],
styles: [
'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css',
'https://unpkg.com/kidlat-css/css/kidlat.css'
]
}
Vue.use(VueHtmlToPaper, options);
// or, using the defaults with no stylesheetVue.use(VueHtmlToPaper);
component:
<template><div><!-- SOURCE --><divid="printMe"><h1>Print me!</h1></div><!-- OUTPUT --><button @click="print"></button></div><template><script>exportdefault {
data () {
return {
output: null
}
},
methods: {
print () {
// Pass the element id herethis.$htmlToPaper('printMe');
}
}
}
</script>
for more detail check: https://randomcodetips.com/vue-html-to-paper/
Solution 3:
this answer for VUE ONLY. easiest way use this function. do not call the function directly from HTML tag will not work. code as below inside a function call window.print().
`printDoc() { window.print(); }`
`@media print {
//use your CSS over here customize your prints components.
::v-deep .right-sidebar,
::v-deep header {
display: none !important;
}
::v-deep footer {
display: none !important;
}
}
Post a Comment for "How To Print A Part Of A Vue Component Without Losing The Style"