PDFKit is a Ruby gem used to generate PDFs based on HTML layouts. Usually, It is used to dynamically generate certificates, invoices etc in different websites. Example: Downloadable PDF Certificates that you get from online course websites.
So, I was using PDFKit recently for dynamically generating certificates for an app. PDFKit uses another library called wkhtmltopdf on the back-end which renders HTML using Webkit.
Designers had given a design for certificates which have custom fonts like Roboto and Roboto Slab. So I thought let’s use these fonts from Google fonts CDN. That is when the problem started!
PDFKit doesn’t wait till the page loads fonts from external CDN. So these custom fonts were not rendered. They just had default fonts!
Then I tried searching wkhtmltopdf’s Github issue to see if I can find something. Few issues mentioned using the base64 version of the font and embed them directly in the HTML page.
So I used an online tool to convert google font to Base64 – https://amio.github.io/embedded-google-fonts/ and embedded fonts into HTML file. But still it wasn’t working 😴
Finally, I had to use inline CSS for the elements with a custom font and then it worked 🎉
<p class="name" style="font-family: 'Roboto'">Coding is Love</p>
Embedded fonts look like this
<head> <style> @font-face { font-family: 'Roboto Slab'; src: url(data:application/font-woff2;charset=utf-8;base64,..........) font-weight: bold; font-style: normal; } </style> </head>
Here’s an example for Roboto and Roboto Slab – Roboto and Roboto Slab base64 font
Also, Remove the local property from src – local('Roboto'), local('Roboto')
In one line – Use base64 font, remove local property from src and use inline styles for elements with a custom font ✌️
- Flutter lookup failed in @fields error (solved) - July 14, 2023
- Free open source alternative to Notion along with AI - July 13, 2023
- Threads API for developers for programmatic access - July 12, 2023
I’m experiencing this issue myself, so t hanks for the article.
How/where do you put the font definition? Do you put it inside a tag? I’m not having much luck here, so an example of your finished html would be very helpful, thanks!
‘@font-face {
font-family: ‘Roboto Slab’;
src: url(data:application/font-woff2;charset=utf-8;base64,……….)
font-weight: bold;
font-style: normal;
}’
I am also having the same problem. Any update on this would be greatly appreciated.
Hi, I’ve updated the article. You should put the font definition in a style tag. Check the updated code above.
Hi, I’ve updated the article. You should put the font definition in a style tag. You can put that style tag inside the head or body. It is basic CSS. Check the updated code above.