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

Posted

技术标签:

【中文标题】如何在 Handlebars 和 Puppeteer 中使用自定义字体?【英文标题】:How to use custom fonts with Handlebars and Puppeteer? 【发布时间】:2021-05-15 04:49:23 【问题描述】:

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

目前我的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 时,会加载标准字体而不是自定义字体。

【问题讨论】:

查看相关的 github 问题以获取更多信息 - github.com/puppeteer/puppeteer/issues/422。 【参考方案1】:
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])

【讨论】:

以上是关于如何在 Handlebars 和 Puppeteer 中使用自定义字体?的主要内容,如果未能解决你的问题,请参考以下文章