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

4 Replies to “Custom font with PDF Kit or wkhtmltopdf issue (solved)”

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

    1. Hi, I’ve updated the article. You should put the font definition in a style tag. Check the updated code above.

    2. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *