How to fix Puppeteer font issues

contents

If you've been printing PDFs 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 are a few quick things you can do to fix your font in Puppeteer!

Use a special launch flag

The first thing to try out is to apply 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 very well intentioned, 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. You'll want to test the options 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 so puppeteer respects your font

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, it may break your font since puppeteer applies its own user-agent that renders these WebFonts useless. To prevent 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");

Further reading

With these three quick fixes, hopefully, your fonts should be looking great. For more advice around exporting PDFs with Puppeteer, check out this article:

How to generate PDFs with Puppeteer

If you're looking to generate PDFs without having to manage a headless browser, you should give our PDF API a shot! See more about that in our docs.

Then of course you'll need browsers to render your PDFs. Either read our guide about manging Chrome on AWS, or you can connect to our fleet of browsers which you can test Browserless with a free trial.

Share this article

Ready to try the benefits of Browserless?