17

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?

2 Answers 2

29

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This one is excellent and well maintained and has support for latest web standards!
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.

4 Comments

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
you can just write the html file and use a file URI instead (i.e: file:///home/user/path/to/your/file.html), it should work fine with chrome headless:
oh right, i didn't thought about the file uri thing. sounds good, thanks!
If you're already using headless chrome, why don't you simply take screenshots fron it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.