This page looks best with JavaScript enabled

Print a page section on button-click in Vue

 ·   ·  ☕ 2 min read

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 -

1
npm install vue-html-to-paper

Add library to your code in main.js -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// 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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!-- 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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things