16

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?

niryo
  • 1,275
  • 4
  • 15
  • 26

2 Answers2

26

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
rudresh solanki
  • 925
  • 9
  • 4
7

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.

gnuns
  • 596
  • 5
  • 12
  • yea I thought about the option of using http server but it seems a bit strange...if no one will suggest a simpler solution ill accept yours because im starting to think there is no simpler solution, tnx – niryo Jun 26 '17 at 22:08
  • you can just write the html file and use a [file URI](https://en.wikipedia.org/wiki/File_URI_scheme) instead (i.e: `file:///home/user/path/to/your/file.html`), it should work fine with chrome headless: – gnuns Jun 27 '17 at 14:17
  • oh right, i didn't thought about the file uri thing. sounds good, thanks! – niryo Jun 28 '17 at 15:03
  • If you're already using headless chrome, why don't you simply take screenshots fron it? – std4453 Jun 30 '20 at 14:14