Skip to content

Instantly share code, notes, and snippets.

@coolov
Last active February 21, 2022 21:07
Show Gist options
  • Save coolov/a4c0b9400db3d7cf61a0a20b3a8d980a to your computer and use it in GitHub Desktop.
Save coolov/a4c0b9400db3d7cf61a0a20b3a8d980a to your computer and use it in GitHub Desktop.
A script for inlining fonts into SVG documents. There is a better version of this script here: https://github.com/coolov/svgum
/*
!!!!!
USE THIS TOOL INSTEAD:
https://github.com/coolov/svgum
!!!!
If you use https://app.diagrams.net/ with google webfonts and export to svg and then
load that svg in an image tag you are in trouble! The browser cannot load the external
font resources.
Read more here: https://css-tricks.com/using-custom-fonts-with-svg-in-an-image-tag/
The solution is font embedding:
"To embed fonts in SVG, you first have to know what font families are used. Then
you need to find these font files and download them. Once downloaded, you have to
convert regular, bold, italics and bold italics to Base64 encoding."
https://css-tricks.com/using-custom-fonts-with-svg-in-an-image-tag/#font-embedding-to-the-rescue
The article proposes nano (https://vecta.io/nano) to handle this.
But nano costs $99 per year!!!!!!!
Here is a script that does the same thing for free (without some of the optimizations that nano offers)
When I find time I will turn this into something that can be `npm install -g` and maybe
add some optimizations (like subsetting for exampe)
For now, install using the steps below:
*/
// 1. change this to whatever svg you wanna use
const SVG_FILENAME = "many-fonts.svg";
// 2. install the dependencies
// npm init
// npm install node-fetch base64-arraybuffer
// 3. run the script. the new svg will be written to stdout
const fs = require("fs");
const fetch = require("node-fetch");
const base64arraybuffer = require("base64-arraybuffer");
// Google Fonts is doing some sneaky UA detection so we have to pretend that we are a browser
const fetchOptions = {
headers: {
"user-agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
},
};
async function inlineFontsAsBase64(cssString) {
let result = cssString;
// match all accorunces of css url functions:
// https://developer.mozilla.org/en-US/docs/Web/CSS/url()
// url(https://fonts.googleapis.com/css?family=Fira+Mono)
const matchedUrlFunctions = [...cssString.matchAll(/url\(([^'"]*)\)/gi)];
for (let match of matchedUrlFunctions) {
const [urlFunctionString, url] = match;
const res = await fetch(url);
const contentType = res.headers.get("content-type");
const buffer = await res.arrayBuffer();
const base64string = base64arraybuffer.encode(buffer);
// replace the url function with one that uses a base64 string
result = result.replace(
urlFunctionString,
`url('data:${contentType};base64,${base64string}')`
);
}
return result;
}
async function fetchAndInlineFonts(styleTag) {
let result = styleTag;
// match all css import rules:
// e.g. @import url(https://fonts.googleapis.com/css?family=Fira+Mono)
// https://developer.mozilla.org/en-US/docs/Web/CSS/@import
const matchedImportRules = [
...styleTag.matchAll(/\@import url\(([^'"\)]*)\)\;/gi),
];
for (let match of matchedImportRules) {
const [importRuleString, url] = match;
// fetch the fonts css file from google fonts, e.g
// https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap
//
// contains a bunch of font-face definitions:
//
// @font-face {
// font-family: 'Roboto';
// font-style: normal;
// font-weight: 100;
// font-display: swap;
// src: local('Roboto Thin'), local('Roboto-Thin'), url(https://fonts.gstatic.com/s/roboto/v20/KFOkCnqEu92Fr1MmgVxFIzIXKMnyrYk.woff2) format('woff2');
// unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
// }
const res = await fetch(url, fetchOptions);
const cssBody = await res.text();
const cssBodyWithEmbeddedFonts = await inlineFontsAsBase64(cssBody);
// replace the import rule with inline css that has the fonts embedded
result = result.replace(importRuleString, cssBodyWithEmbeddedFonts + "\n");
}
return result;
}
async function main() {
let svgString = fs.readFileSync(SVG_FILENAME).toString();
const matchedStyleTags = [
...svgString.matchAll(/\<style type="text\/css">(.*?)<\/style>/gi),
];
for (let match of matchedStyleTags) {
const [styleTag] = match;
const styleTagWithInlineFonts = await fetchAndInlineFonts(styleTag);
svgString = svgString.replace(styleTag, styleTagWithInlineFonts);
}
console.log(svgString);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment