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
Here are the steps at a high level -
- Draw contents of
divto canvas. We use a library called html2canvas to create canvas from a specified
- Generate image from canvas
- Download canvas as an image
The example code is on Codepen. Explanation below.
Create some html that includes content that needs to be printed.
The objective is to print all content within the
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
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).