如何在 Handlebars 和 Puppeteer 中使用自定义字体?

Rei*_*r68 5 javascript node.js handlebars.js google-chrome-headless puppeteer

我有一个Handlebar模板,我使用 转换为 PDF Puppeteer。问题是如何使用自定义字体?

目前,我的app.js文件中有一个静态文件夹,声明如下:app.use(express.static(path.join(__dirname, 'assets')));。这包含自定义字体。

在我的 Handlebar 模板中,我像这样声明这些字体:

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    @font-face {
      font-family: 'SourceSansPro';
      src: url("../assets/fonts/SourceSansPro-Regular.ttf");
      font-style: normal;
    }

    @font-face {
      font-family: 'SourceSansPro';
      src: url("../assets/fonts/SourceSansPro-Italic.ttf");
      font-style: italic;
    }

    @font-face {
      font-family: 'SourceSansPro';
      src: url("../assets/fonts/SourceSansPro-Bold.ttf");
      font-weight: 600;
    }

    body {
      font-family: 'SourceSansPro';
      font-stretch: normal;
    }
  </style>
</head>
Run Code Online (Sandbox Code Playgroud)

但生成 pdf 时,会加载标准字体,而不是自定义字体。

小智 3

const puppeteer = require('puppeteer');
(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('file://C:/Path/to/yours/index.html', { waitUntil: 'networkidle0' });
    await page.pdf({
        path: 'test.pdf',
        printBackground: true,
        //more custom options here
    });
    await browser.close();
})();
Run Code Online (Sandbox Code Playgroud)

添加{ waitUntil: 'networkidle0' }选项对我有用。

https://github.com/puppeteer/puppeteer/issues/422

Puppeteer - page.goto(url[, options])