vercel / satori

Enlightened library to convert HTML and CSS to SVG
https://og-playground.vercel.app
Mozilla Public License 2.0
11.01k stars 242 forks source link

Dynamically load fonts for out-of-range characters from Google Fonts #36

Closed shuding closed 2 years ago

shuding commented 2 years ago

Goal

When rendering dynamic content, especially user input, it's possible that it contains some characters which are not included in the loaded fonts.

We want to solve this problem in both Node and Edge runtimes.

Proposal

To solve this, we can make use of Google Fonts' ?text API:

https://fonts.googleapis.com/css2?family=Noto+Sans+JP&text=あ

Make sure to request this API with curl so it won't return modern formats such as woff2. This gives us a small font file that we can use as the fallback to render the dynamic content.

As for font choice, Google's Noto font family can be a good built-in fallback, which supports almost all languages in the world:

The Noto fonts are perfect for harmonious, aesthetic, and typographically correct global communication, in more than 1,000 languages and over 150 writing systems.

Implementation

shuding commented 2 years ago

Found https://github.com/fontsource/google-font-metadata where contains the metadata (unicode-ranges) of all Google Fonts. However the raw data is too large (14.6 MB, can be optimized to <300 kB?).

Also a way to load the data for individual font: https://unpkg.com/browse/@fontsource/noto-sans-jp@4.5.5/unicode.json (82.2 kB).