Custom fonts with Wicked PDF on Rails

Well! We all have had a hard time getting through the custom fonts in our website or web-application. It has been easier with the @font-face implementation through CSS though this requires different formats of file integrated through it.

This implementation was OK until our client wanted to have the custom font implemented in the PDF generated by wicked_pdf in our Rails Application. This was not working right as intended, PDF using the default font rather than the custom font specified. And yes, we couldn’t even inspect element to diagnose the problem as could be done in webpage.

I also tried specifying the path to fonts explicity as mentioned here and below, but it still didn’t solve the problem.

# app/assets/styleshsheets/fonts.css.erb
@font-face {
  font-family: 'ITC Franklin Gothic STD';
  font-style: normal;
  font-weight: 300;
  src: url('<%= Rails.root.join('app', 'assets', 'fonts', 'itcfranklingothicstd-book.eot') %>') format('eot')

Searched through Google for some time and went through different articles to then sum up with the solution:

Solution: Base64 Encode @font-face

Yes, we can actually base64 encode the font-face and then use it through CSS @font-face to have it implemented in our website or web-application. This actually solves the problem of using custom fonts with Wicked PDF on Rails.

First, base64 encode ttf or otf of the font-face which can be done with CLI in Linux or Unix:

$ base64 /path/to/Verlag-Black-Italic.ttf > /just/to/save/verlag-black-italic.txt

Then copy the base64 encoded text from /just/to/save/verlag-black-italic.txt to paste it in the @font-face as mentioned below:

@font-face {

Wohoo!!! Now run the PDF generator with the CSS implemented for the font and see the magic happen with your custom font implemented in the PDF. This should make you and your client happy and smiling! 🙂

Do leave a comment below if this could be done in a better and/or easier way as Learning is endless…