Puppeteer结合Handlebars无法加载自定义字体求解决方案
在Puppeteer中结合Handlebars加载自定义字体失败的问题
我尝试在Handlebars模板中使用Puppeteer加载自定义字体,但始终无法成功。试过相关技术社区里的所有方案都无效,尝试过的方案包括:
- 使用
{waitUntil: 'networkidle0'}和{waitUntil: 'networkidle2'}等待策略 - 执行
await page.evaluateHandle('document.fonts.ready');等待字体加载完成 - 延时等待:
await new Promise(resolve => setTimeout(resolve, 500)); - 执行
await page.focus('body'); - 触发截图操作:
await page.screenshot({path: 'tester.png'}); - 等待页面导航完成:
const loaded = page.waitForNavigation({waitUntil: "load"});
我注意到那些成功加载字体的案例都没有使用Handlebars,有人提到内联HTML的方法,但Handlebars无法实现。本地和在线字体文件我都试过,都没成功。还有人建议用page.goto替代page.setContent,但我不知道怎么和Handlebars配合使用。我的运行环境是WSL+Visual Studio Code,不确定这会不会有影响。
有没有人成功在Puppeteer与Handlebars结合的场景中加载过在线或本地字体?
相关代码
app.js 静态文件夹配置
app.use(express.static(path.join(__dirname, 'modules')))
app.js 中的Puppeteer代码
async function convertToPDF() { const extData = await extensionListPDFOrganize(); const compile = async function() { const filePath = path.join(process.cwd(), 'extensionList.hbs'); const html = fs.readFileSync(filePath, {encoding:'utf8'}); return hbs.compile(html)(extData); } try { const browser = await puppeteer.launch({executablePath: '/usr/bin/google-chrome'}); const page = await browser.newPage(); const content = await compile(); await page.setContent(content); //此处插入上述列举的各种解决方案 await page.emulateMediaType('screen'); await page.pdf({ path: 'test.pdf', format: 'Letter', printBackground: true }) console.log('done'); await browser.close(); process.exit(); } catch (error) { console.log(error) return(error); }}
Handlebars中的CSS代码
<style type="text/css"> @font-face { font-family: 'Lasiver'; src: url("../modules/fonts/Lasiver.otf"); font-style: normal; } p { font-family: 'Lasiver'; } </style>
内容的提问来源于stack exchange,提问作者user1715916
相关产品推荐
相关产品推荐

