Back

Technologies:

javascriptjavascript
csscss
avatar
Tolerim
21 hours ago

How do I import a font stored locally into an SVG file?

I have developed a tool that users can clone from Github and use on their own devices without requiring a web server. In order to use a specific font, I downloaded the .ttf file and employed the @font-face command to load it from the same directory as the .css file:
@font-face {
  font-family: 'Nunito Light';
  font-style: normal;
  font-weight: 400;
  font-display: swap;
  src: url('Nunito-Light.ttf') format('truetype');
}
When the tool is hosted on my web server, it displays correctly with the designated font. However, when I try to open it on my local machine, I receive a warning in Firefox's console about the CORS being blocked, and the page defaults to a sans-serif font installed on my device. I have researched potential solutions, but most advice pertains to loading fonts on a web server rather than on a user's local device. Does anyone know of a straightforward way to work around this issue? Thank you. As additional information, I have documented the problem and solution on my blog: https://www.edison23.net/css-webfonts-in-a-locally-hosted-html-web-page/.
Answers(1)
avatar
Tolerim
21 hours ago
Verified Answer
Since the font file is being loaded from the local file system and not from a web server, it is subject to the Same-Origin Policy which doesn't allow cross-origin requests. However, there are a couple of ways to get around this: 1. Enable CORS on your web server. This will allow the font file to be loaded from the server even when the page is being accessed locally. 2. Convert the font file into a Base64-encoded data URI and use it directly in your CSS without having to load it externally. This will avoid the Same-Origin Policy issue altogether. To do this: - Convert the font file to Base64 format using an online tool or a command-line utility like base64. - Create a new CSS rule for your font using the data: URL scheme, like this:
@font-face {
  font-family: 'Nunito Light';
  font-style: normal;
  font-weight: 400;
  src: url(data:application/x-font-ttf;charset=utf-8;base64,<<Base64-encoded font data>>) format('truetype');
}
Replace <> with the Base64-encoded font data you obtained from the font file. Note that embedding the font data directly in your CSS will make your CSS file larger and slow down its loading time, so consider using this method only for smaller font files.
;