Note

Font handling in html-to-image

The html-to-image package handles fonts as follows:

  1. Scan style rules: It scans all stylesheets loaded on the page (document.styleSheets) to find @font-face rules, in order to learn the font family names and the URLs of their corresponding font files (e.g., .woff2).
  2. Fetch and inline fonts: It then downloads the font files referenced by src in those @font-face rules and converts them into Base64 Data URIs.
  3. Generate an SVG with embedded fonts: Finally, it writes those @font-face rules with Data URIs into an internally generated SVG, paints that SVG onto a Canvas, and outputs a PNG or JPEG.

The problem lies in step 2: Google Fonts blocks script-initiated requests via CORS. You might notice “errors are thrown but the font still renders fine.” That’s because it ends up using fonts from the browser cache outside the render component. This introduces a race condition and isn’t reliable.

Solutions:

  1. Download the font files yourself and host them on your own domain.
  2. If you use Google Fonts, switch to BunnyCDN’s free compatible font host; they include Access-Control-Allow-Origin: *.

'25, Nov 19