Custom font with PDF Kit or wkhtmltopdf issue (solved)

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.

pdfkit ruby gem

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 ✌️

Ranjith kumar
5 1 vote
Article Rating
Subscribe
Notify of
guest

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Joe
Joe
5 years ago

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;
}’

Jamie
Jamie
5 years ago
Reply to  Joe

I am also having the same problem. Any update on this would be greatly appreciated.