如何将 HTML 转换为 Node.js 中的图像

How to convert HTML to image in Node.js

我需要在节点服务器上将 HTML 模板转换为图像。 服务器将接收 HTML 作为字符串。我试过 PhantomJS(使用一个名为 Webshot 的库),但它不能很好地与 flex box 和现代 CSS 一起使用。我尝试使用 Chrome 无头浏览器,但它似乎没有用于解析 html 的 API,只有 URL.

将一张HTML转成图片目前最好的方法是什么?

有没有办法在模板模式下使用 headless Chrome 而不是 URL 模式?我的意思是,而不是做类似

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

我需要这样的东西:

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

在此 post 的评论中建议的另一个选项是 将模板保存在服务器上的文件中,然后在本地提供它并执行以下操作:

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

不过这个选项听起来有点别扭。还有其他更直接的解决方案吗?

您可以使用 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(屏幕截图功能)在前端轻松完成。另一种选择是设置一个简单的 HTTP 服务器并访问 url.

您可以使用名为 Puppeteer 的库。 示例代码片段:

 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 的屏幕截图。