Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
41
rated 0 times [  47] [ 6]  / answers: 1 / hits: 47671  / 6 Years ago, sat, september 15, 2018, 12:00:00

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:





new Vue({
el: '#app',
data() {
return {
dialog: false
}
},
methods: {
print() {
var prtContent = document.getElementById(print);
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
}
})

<!doctype html>
<html>

<head>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.2.0/vuetify.min.css />
</head>

<body>
<div id=app>
<v-app id=inspire>
<v-layout row justify-center>
<v-dialog v-model=dialog persistent max-width=290>
<v-btn slot=activator color=primary dark>Open Dialog</v-btn>
<v-card>
<v-card-title class=headline>Print This:</v-card-title>
<v-card-text id=print>Lorem ipsum dolor sit amet.</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn color=green darken-1 flat @click.native=print>Print</v-btn>
</v-card>
</v-dialog>
</v-layout>
</v-app>
</div>
<script src=https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.2.0/vuetify.min.js></script>
</body>

</html>





However,when I get prompted for the print, all the styles associated with it goes away. How can I print a vue component in such a way so that the components won't lose the associated styles?
I recommend to copy the snippet to your local machine for the best effect.


More From » vue.js

 Answers
46

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();

[#53487] Tuesday, September 11, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
payne

Total Points: 527
Total Questions: 108
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;