How to convert HTML to image in Node.js

You can easily do it on frontend using html2canvas. On backend you can write the html on a file and access using a file URI (i.e: file:///home/user/path/to/your/file.html), it should work fine with chrome headless-browser and Nightmare (screenshot feature). Another option is to setup a simple HTTP server and access the url.


You can use a library called Puppeteer. Sample code snippet :

 const browser = await puppeteer.launch();
 const page = await browser.newPage();
 await page.setViewport({
     width: 960,
     height: 760,
     deviceScaleFactor: 1,
 });            
 await page.setContent(imgHTML);
 await page.screenshot({path: example.png});
 await browser.close();

This will save a screenshot of the HTML in the root directory.