We have previously seen how a div
element can be saved to a file. In this post we will see how we can save div
tag contents as an image in Vue.
How do we print the div
?
Here are the steps at a high level -
- Draw contents of
div
to canvas. We use a library called html2canvas to create canvas from a specifieddiv
. - Generate image from canvas
- Download canvas as an image
The print
here is equivalent to “taking the screenshot” of a particular section of your app.
Code
The example code is on Codepen. Explanation below.
Create HTML
Create some html that includes content that needs to be printed.
|
|
The objective is to print all content within the div
with ref=printcontent
.
Script
First, we include reference to the HTML2Canvas CDN.
Next, create some Vue code -
|
|
The code is largely self-expanatory -
- Get reference to the element that needs to be printed -
const el = this.$refs.printcontent
- Generate canvas from element -
const printCanvas = await html2canvas(el, options);
- Convert canvas to an image
1 2 3
printCanvas .toDataURL("image/png") .replace("image/png", "image/octet-stream");
- Generate a link that will prompt user to download image when clicked -
const link = document.createElement("a");
. Point the link to the image generated in the previous step
End Result
That’s about it! Click on Print!
button to download image.
Note that the image in the content cannot be from another domain since that will taint the canvas (and the image will not be rendered).