Blog

Back to blog posts

Using custom fonts with wkhtmltopdf and Headless Chrome

Published Nov 12, 2018

Intro

Using custom fonts with wkhtmltopdf or Headless Chrome is pretty straight forward, but there are a few caveats. First, it is important to know what fonts Api2Pdf supports out of the box with both endpoints. By default, if you do nothing but go to the home page of Api2Pdf and print the below HTML in the Try It Out section, you will receive a wonderful PDF with samples of all of the fonts that we support.

 

<html lang="en">
<body>
<p>Hello World, no font family, defaults to Times New Roman</p>
<p style="font-family:Times New Roman;">Hello World, Times New Roman</p>
<p style="font-family:Arial;">Hello World, Arial</p>
<p style="font-family:Courier;">Hello World, Courier</p>
<p style="font-family:Verdana;">Hello World, Verdana</p>
<p style="font-family:Tahoma;">Hello World, Tahoma</p>
<p style="font-family:Arial Black;">Hello World, Arial Black</p>
<p style="font-family:Comic Sans MS;">Hello World, Comic Sans MS</p>
<p style="font-family:Georgia;">Hello World, Georgia</p>
<p style="font-family:Impact;">Hello World, Impact</p>
<p style="font-family:Palatino;">Hello World, Palatino</p>
<p style="font-family:Bookman;">Hello World, Bookman</p>
</body>
</html>

 

For those that do not feel like printing the PDF themselves, that’s okay – click this link to see it.

What it means to be a default font is that you can use the css right inside of the HTML to use that font. No external files necessary. Interestingly enough, these fonts are known to come standard as part of almost every Operating System on the planet, but we learned the hard way that AWS Lambda does not include any fonts by default. Shocker. Regardless, feel free to use those fonts as you see fit.

Google Fonts with wkhtmltopdf and Headless Chrome

You can include external fonts and css in your HTML so long as the urls to those resources are fully resolved, meaning they start with http / https://. Using Google fonts at fonts.google.com is quite common. The below example uses a Google font straight from the site.

 

<html style="color:green;" lang="en">
<head>
<link href="https://fonts.googleapis.com/css?family=Spicy+Rice" rel="stylesheet">
</head>
<body>
<p style="font-family:Spicy Rice, cursive;">Example of a custom font from fonts.google.com</p>
</body>
</html>

 

The resulting PDF can be viewed by clicking this link.

Completely Custom Fonts with wkhtmltopdf and Headless Chrome

If you are going 100% custom, you can upload your own font resource on your own servers and use it with css @fontface rules as described here: https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face — but once again, you must make sure the resource linked in the PDF starts with http:// or https://.