如何在Node.js中将HTML转换为图像 [英] How to convert HTML to image in Node.js
问题描述
我需要在Node服务器上将HTML模板转换为图像.服务器将以字符串形式接收HTML.我尝试了PhantomJS(使用一个名为Webshot的库),但是它不适用于flex box和现代CSS.我尝试使用Chrome浏览器浏览器,但它似乎没有解析HTML的API,仅解析URL.
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.
将HTML转换为图像的当前最佳方法是什么?
What is the currently best way to convert a piece of HTML into image?
有没有办法在模板模式而不是URL模式下使用无头Chrome?我的意思是,不要做类似的事情
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')
我需要类似的东西:
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?
推荐答案
您可以使用名为 Puppeteer的库.示例代码段:
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();
这会将HTML的屏幕截图保存在根目录中.
This will save a screenshot of the HTML in the root directory.
这篇关于如何在Node.js中将HTML转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!