How to fix broken font collisions in wkhtmltopdf

Updated . Posted . Visible to the public.

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 Show archive.org snapshot . 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 Show archive.org snapshot 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 Show archive.org snapshot encoding.

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

@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;
}
Michael Leimstädtner
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Michael Leimstädtner to makandra dev (2017-09-14 12:46)