user5675649
user5675649

Reputation: 187

Base64 encoded OpenType font-face using data URI

I want to add a base64 encoded OpenType font as a data URI in font-face.

I have this so far:

@font-face {
    font-family: 'test';
    src: url(data:font/otf;base64,
        // Base64 string here ...
    ) format('opentype');
}

But I believe it does not include the font correctly to my style.

Any help with this would be really appreciated.

Upvotes: 17

Views: 26852

Answers (2)

Christopher Vickers
Christopher Vickers

Reputation: 1953

Although not asked, I'm sure that someone will come here looking for the woff2 solution and will have the same issues I had. Upload the file using this site: https://base64.guru/converter/encode/file Ensure you use the option "Data URI". Replace the url() value with the code from the site.

For the CSS I had to use the following code:

@font-face {
    font-family: 'MYFONT'; /*This is what your font will be named*/
    src: local('MYFONT'), /* It will check the machine for a font matching this name, if it exists it will use this. Not needed when your are writing the woff2 file since you already sending all the data. */
             url('data:@file/octet-stream;base64,d09GMgABAAAAAK6kABIAAAABgQgAAK47AAA=') /*This is the base64 code copy pasted from the site*/
             format('woff2'); /*This ensures the browser treats it as a WOFF2 file. Notice there is no comma after the url() */
    }

To get your custom font to work you need to specify it:

<div style="font-family: MYFONT">
    My new font
</div>

The actual base64 code I have posted does not work. The woff2 file i was using is 50kb and didn't want page after page of base64 code.

Upvotes: 21

Peyman Mohamadpour
Peyman Mohamadpour

Reputation: 17964

Data URIs are always of this format:

data:[<mediatype>][;base64],<data>

The very first part of every data URI is the media-type, which in the case of an Open Type font is:

font/opentype

So, you may use it like this:

@font-face{
    font-family: test;
    src: url(data:font/opentype; base64, [base64 string here]);
}

Replacing

[base64 string here]

with the exact copy-pasted version of your base-64 encoded string.

Notes

Please note that:

  • you should use font/opentype for the data, not otf.
  • you should copy-paste the exact base-64 encode string, without any changes like added spaces, etc (I believe there are some spaces in it)

Online Encoding Tool

You may use this tool, to convert your font file to the encoded string.

Upvotes: 13

Related Questions