Welcome folks today in this blog post we will be exporting the canvas to pdf document
using html2canvas
in javascript and vue.js. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the jspdf
and html2canvas
library in the vue.js proejct as shown below
npm i jspdf
npm i html2canvas
And after that you need to make an App.vue
file and copy paste the html
code as shown below
App.vue
1 2 3 4 5 6 |
<template> <div id="app"> <canvas id="canvas" width="200" height="500"></canvas> <button @click="downloadPDF">Export to PDF</button> </div> </template> |
As you can see in the above html we have the canvas
element and we have attached width and height. And then we have the button to export to pdf document. We have attached a onclick event listener a method called downloadPDF()
Now we need to style the html using the below css code
1 2 3 4 5 |
<style scoped> canvas{ background-color:red } </style> |
As you can see we have changed the background Color of the canvas to red color as shown below
And now we will be writing thejavascript
code to export the canvas to pdf document as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<script> import jspdf from 'jspdf' import html2canvas from 'html2canvas' export default { name: "App", methods:{ downloadPDF(){ let canvas = document.getElementById('canvas') html2canvas(canvas).then((canvas) => { let img = canvas.toDataURL('image/jpeg') let doc = new jspdf() doc.addImage(img,10,10) doc.save("output.pdf") }) } } }; </script> |
As you can see we are taking the screenshot
of the canvas using the html2canvas library and then we are converting the canvas
to base64 image using the toDataURL()
method. And after that we are inserting the image in the pdf document using the addImage()
method using the jspdf library. And after that we are saving the pdf document using the save()
method