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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With