How to fix Puppeteer font issues

If you’ve been printing PDF’s in Puppeteer for some time, you’ve no doubt encountered issues where fonts don’t render properly. Blotchy, pixelated, or even plain incorrect renderings are common when using headless-browsers. Luckily, there’s a few quick things you can do to fix the problem!
Use a special launch flag
The first thing to try out is to applying a --font-render-hinting
flag. This value, which defaults to “full”, sets a font render hinting when running headless. Internally, this affects Skia rendering and whether glyph sub-pixel positioning is enabled. For the best possible experience, we recommend setting this to “none”, which can greatly improve kerning and letter spacing in your fonts.
//before
const browser = await puppeteer.launch();
//after
const browser = await puppeteer.launch({
args: ['--font-render-hinting=none'],
});
Set a color profile
Chromium tries to keep your ink budget light by using special color profiles for your PDF’s. This is a good thing for the most part, but can result in colors of your PDF’s not coming through properly. To fix this, specify another launch flag — this time using the --force-color-profile
switch.
Internally, this forces all monitors to be treated as though they have the specified color profile.u You’ll want to try a few to see what works best, and potential values are: srgb, generic-rgb, and color-spin-gamma24.
//before
const browser = await puppeteer.launch();
//after
const browser = await puppeteer.launch({
args: ['--force-color-profile=srgb'],
});
Set a standard user-agent header
If you’re using a font service, like Google Fonts, many check your user-agent string to see what fonts your browser supports. While this optimization is nice for the majority of users out there, puppeteer applies its own user-agent that renders these WebFonts useless. To counter that, simply set a legitimate user-agent header:
// before
const browser = await puppeteer.launch();
const page = await browser.newPage();
// after
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36");
Wrapping up
With these three quick fixes, hopefully your fonts are looking sharp in your PDF’s. If your looking to generate PDF’s in without having to manage a headless browser, you should give our PDF API a shot! See more about that here.