Posted over 3 years ago. Visible to the public.

How to fix broken font collisions in wkhtmltopdf

If you are using PDFKit / wkhtmltopdf, you might as well want to use custom fonts in your stylesheets. Usually this should not be a problem, but at times they include misleading Meta-information that leads to a strange error in the PDF.

The setup

  • The designer gave you two fonts named something like BrandonText-Regular and BrandonText-Bold. (With flawed Meta-information)
  • You have a HTML string to be rendered by PDFKit
  • For demonstration purposes, this string also contains CSS styles in a tag. They are referencing to your fonts.

The problems

  1. You are getting a deadlock since your local machine does not support parallel requests
  2. Even though you specified different fonts, the entire text uses one and the same
  3. You are having a hard time trying to serve the fonts from the local file system

The solutions

  1. You can use a Passenger standalone to get things running.
  2. I'm sorry that happened to you! But there is hope. WKHtmlToPdf seems to ignore the font-family tag if internal font attributes are matching. What I mean to say is that one of your fonts are probably slightly corrupted and must be fixed. Follow these steps:
    2.1 Install and run FontForge. Open the font that dominates over the other one.
    2.2 Go to Element -> Font Info -> TTF Names
    2.3 If the Entry "Preferred Family" is set to the same as it is on the other font, change it to equal its own name. If not, look out for other mismatching values.
    2.4 Go to File->Generate Fonts. Save the font with the same type it was and see if it works now.
    (2.5) If you are not successful, try embedding the SVG equivalents of your fonts. This may work, but result in non-selectable text in your PDF.
  3. If you are unable to serve the font using the local file system, you might want to choose using the controller. An other possibility is to embed your fonts with the Base64 encoding.

In the end, my font-faces looked like this:

Copy
@font-face { font-family: 'BrandonText'; src: url(data:font/opentype;base64,.....) format('opentype'); font-weight: normal; font-style: normal; } @font-face { font-family: 'BrandonText'; src: url(data:font/opentype;base64,.....) format('opentype'); font-weight: bold; font-style: normal; }

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Michael Leimstädtner
Last edit:
over 3 years ago
by Michael Leimstädtner
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Michael Leimstädtner to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more