SVG download with Google fonts [SOLVED]

Hello, I created an SVG in D3.js.
For my text elements - I use one of the Google fonts, Roboto.
I wanted to download SVG having text elements displayed in the font.
I created a button to download SVG inspired by this approach

Here is what I see when I inspect SVG in a browser.
You can see the font is there as attribute, but unfortunately the text is displayed in some other random font.

<text xmlns="http://www.w3.org/2000/svg" class="legend" font-family="Roboto" text-anchor="middle" dy="0.75em" x="2.2713115968186246e-14" y="-370.93333333333334" style="font-size: 25px;"><tspan x="2.2713115968186246e-14" y="-370.93333333333334" dy="0.75em">Impact</tspan></text>

How to include Google fonts to SVG, when it’s saved?

If I understood your question correctly, you just would need to append the

@import url("googlefont")

directly in your svg defs

svg.append('defs')
.append('style') ...

@DanielSubat
hey, so you mean adding a style tag in html like this

<style>
@import url("/assets/Roboto/Roboto-Regular.ttf")
</style>

and then appending this very tag in JS file

svg.append('defs')
.append('style');

Is this what you mean?

No, add the style directly in your js:

svg.append('defs')
   .append('style')
   .attr('type', 'text/css')
   .text("@import url('googlefont')");

thank you very much. that works indeed, but only as long as you open the file in the browser and you’re online. Putting the path to a directory with the font to my local directory doesn’t work.

What shall I do, if a user wants to open the file in the Image Viewer?
Is there any way to attach the font to the SVG file?

If you want it to work in an image viewer, the font file would need to be in the same directory as the svg.
Or another approach you could convert your ttf to svg paths, but then you couldnt use <text anymore.

Thats the only two ideas that come to my mind right now :wink:

1 Like

Does anyone else have any idea? :thinking:

I found an answer here.

It’s a variation of your answer @DanielSubat in a way:

<defs>
  <style>
    /* all your parsed styles in here */
    @font-face {
     font-family: foo;
     src: url('data:application/font-woff;charset=utf-8;base64,...')
    }
  </style>
</defs>

To encode Google fonts to base64 string check this page

1 Like

@RadekKosiada

Thanks for sharing this! I didn’t know about

data:application/font-woff

1 Like