Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert HTML to image in Node.js

I need to convert an HTML template into an image, on a Node server. The server will receive the HTML as a string. I tried PhantomJS (using a library called Webshot), but it doesn't work well with flex box and modern CSS. I tried to use Chrome headless-browser but it doesn't seem to have an API for parsing html, only URL.

What is the currently best way to convert a piece of HTML into image?

Is there a way to use headless Chrome in a template mode instead of URL mode? I mean, instead of doing something like

chrome.goTo('http://test.com')

I need something like:

chrome.evaluate('<div>hello world</div>');

Another option, suggested here in the comments to this post, is to save the template in a file on the server and then serve it locally and do something like:

chrome.goTo('http://localhost/saved_template');

But this option sounds a bit awkward. Is there any other, more straightforward solution?

like image 237
niryo Avatar asked Jun 26 '17 21:06

niryo


People also ask

How do I convert HTML to JPG?

Open your HTML file in your browser or any viewable tool. Take a snapshot of an area with your screen capture tool (Snipping tool on Windows, for example). Click File > Save as. Select the location and select the Save as type as JPG.

How do I export an image from HTML?

Choose File > Export and select HTML from the Save As Type list. Specify the name and location of the HTML document, and then click Save. In the HTML Export Options dialog box, specify the desired options in the General, Image, and Advanced areas, and then click OK.

Can I use HTML with node js?

In Node. js and Express applications, res. sendFile() can be used to deliver files. Delivering HTML files using Express can be useful when you need a solution for serving static pages.


1 Answers

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.

like image 95
rudresh solanki Avatar answered Sep 22 '22 13:09

rudresh solanki