Welcome folks today in this blog post we will be taking screenshot of html with css
to image using html-to-image
library in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to create a new react.js
project using the below command as shown below
npx create-react-app sampleapp
Now we need to install the libraries using the below command as shown below
npm i html-to-image
npm i file-saver
And after that you need to see the below directory structure of the react.js
app as shown below
Now we need to make an App.js
file and copy paste the below code
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import React, { useRef } from 'react'; import * as htmlToImage from 'html-to-image'; import { saveAs } from 'file-saver'; function App() { const nodeRef = useRef(null); return ( <div> <div style={{backgroundColor:"red"}} ref={nodeRef}> <p>This is the HTML element you want to take a screenshot of</p> <p>It can have any number of child elements and CSS styles applied to it</p> </div> <button onClick={handleScreenshot}>Take Screenshot</button> </div> ); } export default App; |
As you can see we are importing the useRef
hook and then we are importing the html-to-image
and the file-saver
library. And then we have written the html
in which we have the paragraph
and we have the background color set to red and then we have the button to export the html to png
image.
And now we need to write the handleScreenshot()
method when we hit the button to export the html to png image and download it as attachment.
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 36 37 38 39 40 41 |
import React, { useRef } from 'react'; import * as htmlToImage from 'html-to-image'; import { saveAs } from 'file-saver'; function App() { const nodeRef = useRef(null); const handleScreenshot = async () => { const image = await htmlToImage.toPng(nodeRef.current); // you can use this image in any way you want console.log(image) let file = convertBase64ToFile(image, "image.png"); saveAs(file, "image.png"); }; const convertBase64ToFile = (base64String, fileName) => { let arr = base64String.split(','); let mime = arr[0].match(/:(.*?);/)[1]; let bstr = atob(arr[1]); let n = bstr.length; let uint8Array = new Uint8Array(n); while (n--) { uint8Array[n] = bstr.charCodeAt(n); } let file = new File([uint8Array], fileName, { type: mime }); return file; } return ( <div> <div style={{backgroundColor:"red"}} ref={nodeRef}> <p>This is the HTML element you want to take a screenshot of</p> <p>It can have any number of child elements and CSS styles applied to it</p> </div> <button onClick={handleScreenshot}>Take Screenshot</button> </div> ); } export default App; |
As you can see we are exporting html to image
using the base64 code and then we are using the file-saver
library to export the image and download it as an attachment inside the browser.