Introduction
I am working on a project in Vue, from which came the need to generate a client-side pdf, so after some research I discovered these two ways, which I found more comfortable, one of them uses a npm module and the other is root style with the window object.
Lets go to what matters
Assuming we have a component with a stylized table by boostrap:
<template>
<table class="table-striped">
<thead>
<tr>
<td colspan="10"> My action table </td>
</tr>
</thead>
<tbody>
<tr>
<td> Jump </td>
<td> Wash the dishes </td>
<td> Fix the computer</td>
</tr>
</tbody>
</table>
</template>
<script>
import './index.css'
export default{
methods: {
generatePDF(){
...our solution goes here
}
}
}
</script>
First Solution - NPM MODULE
For this we need to install the module jsPDF, and html2canvas as a dependecy.
NPM
npm i --save jspdf html2canvas
YARN
yarn add jspdf html2canvas
Applying the solution on the method generatePdf():
html2canvas is not explicitly depended on the jsPDF documentation to generate the pdf, because it converts our node element into a canvas and then generates the pdf for download, but also the possibility of adding a text, an image, you can see more here in jsPDF full documentation.
//...previous stuffs of the component
<script>
import './index.css'
import * as jsPDF from 'jspdf'
import html2canvas from 'html2canvas'
export default{
methods: {
generatePDF(){
window.html2canvas = html2canvas
let table = document.querySelector('table')
const doc = new jsPDF(); doc.html(table,{
callback: doc => {
doc.save('MyPdf.pdf')
}
}
}
}
}
</script>
Last Solution
This is the simplest and purest way to print, but it is a bit more work, since to get the background-color of an element you need to implement a polyfill with media query, because print() doesn't supports background-color π
Let's suppose you also have some element you don't want to appear in your print, you can set it to display none only when printing.
In your css or scss you need to add if you want a background-color in some element:
@media print {
thead{
box-shadow: inset 0 0 0 1000px #b9d1ea !important;
}
someElement{
display:none;
}
}
In your script:
//...previous stuffs of the component
<script>
import './index.css'
export default{
methods: {
generatePDF(){
window.print() //simple like that
}
}
}
</script>
The print() method prints the contents of the current window.
The print() method opens the Print Dialog Box, which lets the user to select preferred printing options.
Top comments (1)
Unfortunately jsPdf doesn't support unicode..π