如何将 Puppeteer 指向本地图像/字体?

bdr*_*sky 9 headless-browser puppeteer

我想使用 Puppeteer 从 HTML 字符串生成图像。现在我有这样的事情:

const html = _.template(`
<html>
<body>
  <div class="testing">
    <h1>Hello {{ test }}!</h1>
    <img src="./1.jpg" alt="alt text" />
  </div>
</body>
</html>
`)

const browser = await puppeteer.launch()
const page = await browser.newPage()
const data = html({
  test: 'World'
})
await page.setContent(data)
const take = await page.$('.testing')
await take.screenshot({
  path: 'screenshot.png',
  omitBackground: true
})
Run Code Online (Sandbox Code Playgroud)

问题是,Puppeteer 不加载图像,我不知道如何将它指向他?该图像与脚本位于同一目录中。

除了图像,我想加载自定义字体,怎么做?

vse*_*byt 9

页面 URL 是about:blankChrome 不允许在非本地页面中加载本地资源。

所以也许是这样的?

'use strict';

const { readFileSync } = require('fs');
const puppeteer = require('puppeteer');

(async function main() {
  try {
    const browser = await puppeteer.launch({ headless: false });
    const [page] = await browser.pages();

    const html = `
      <html>
      <body>
        <div class="testing">
          <h1>Hello World!</h1>
          <img src="data:image/jpeg;base64,${
            readFileSync('1.jpg').toString('base64')
          }" alt="alt text" />
        </div>
      </body>
      </html>
    `;

    await page.setContent(html);
    const take = await page.$('.testing');
    await take.screenshot({
      path: 'screenshot.png',
      omitBackground: true
    });

    // await browser.close();
  } catch (err) {
    console.error(err);
  }
})();
Run Code Online (Sandbox Code Playgroud)

  • 你是如何添加字体文件的?:( 我无法弄清楚。 (2认同)
  • @SubhenduKundu 对于 `src` 参数使用 `url("data:font/ttf;base64,${fs.readFileSync('./your-font-file.ttf').toString('base64')}")` 。确保使用正确的 mime 类型。 (2认同)