Reputation: 3272
I got a Handlebar
template that I convert to PDF using Puppeteer
. The question is how can I use custom fonts?
Currently I got a static folder in my app.js
file declared like so: app.use(express.static(path.join(__dirname, 'assets')));
. This contains the custom font.
In my Handlebar template I declare these fonts like so:
<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>
But when generating the pdf, a standard font is loaded and not the custom font.
Upvotes: 6
Views: 7215
Reputation: 329
Late to the party, but anyway I couldn't get my custom font to show in my hbs template through puppeteer. For me, converting the font to base64
fixed it:
// 1. run "npm run build" to add your font to the dist folder, then
const fontPath = path.join(
process.cwd(),
'dist/assets/your-custom-font.otf',
);
// 2. convert it to base64
const fontData = fs.readFileSync(fontPath).toString('base64');
// log it/copy it
console.log(`data:font/opentype;base64,${fontData}`);
then, in your hbs template, embed the base64 fontdata like so
<style>
@font-face {
font-family: 'YourFont';
src: url(data:font/opentype;base64,AAEAAA...) format('opentype'); // paste here the base64 encoded font
}
body {
font-family: 'YourFont', Arial, sans-serif;
...etc
</style>
After this operation you can of course remove the code of the the steps 1/2, as it's only needed to base64 encode your custom font.
Upvotes: 1
Reputation: 31
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();
})();
Adding { waitUntil: 'networkidle0' }
option works for me.
https://github.com/puppeteer/puppeteer/issues/422
Puppeteer - page.goto(url[, options])
Upvotes: 3