Use a button on a Vue component to start a print dialog and print a specific section.
Setup
We will use a small library called ‘html2paper’.
First install the said library in your Vue project -
npm install vue-html-to-paper
Add library to your code in main.js -
// main.js
import Vue from "vue";
// ...
import VueHtmlToPaper from "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);
// ...
We will use a Vuetify example to demonstrate how this is used in Vue code, because - why not?
Create UI elements
Create a new component or modify the existing component that will house the content to be printed. Create a button and identify the section that needs printing.
You can have the section hard-coded or fetch the content from elsewhere. We have used v-html below to render the content fetched from an external system.
<!-- PrintStuff.vue -->
<template>
<v-card flat height="100%">
<v-toolbar dense
><div class="body-2">Print Stuff</div>
<v-spacer></v-spacer>
<v-btn small color="primary" @click="printSection">
<v-icon small class="mr-1">print</v-icon>Print
</v-btn>
</v-toolbar>
<v-flex xs12>
<div id="printSection">
<span v-html="printStuff"></span>
</div>
</v-flex>
</v-card>
</template>
<script>
export default {
methods: {
...mapActions("myModule", ["fetchPrintStuff"]),
printSection() {
this.$htmlToPaper("printSection");
}
},
mounted() {
this.fetchPrintStuff();
// a Vuex action to get stuff to print from server
}
};
</script>
Now, click the button to open a beautiful print dialog with only the relevant content.