The html-to-image package handles fonts as follows:
- Scan style rules: It scans all stylesheets loaded on the page (
document.styleSheets) to find@font-facerules, in order to learn the font family names and the URLs of their corresponding font files (e.g.,.woff2). - Fetch and inline fonts: It then downloads the font files referenced by
srcin those@font-facerules and converts them into Base64 Data URIs. - Generate an SVG with embedded fonts: Finally, it writes those
@font-facerules 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:
- Download the font files yourself and host them on your own domain.
- If you use Google Fonts, switch to BunnyCDN’s free compatible font host; they include
Access-Control-Allow-Origin: *.