首页 > 解决方案 > 如何在 Handlebars 和 Puppeteer 中使用自定义字体?

问题描述

我有一个Handlebar模板,我使用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>

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

标签: javascriptnode.jshandlebars.jspuppeteergoogle-chrome-headless

解决方案


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();
})();

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

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

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


推荐阅读