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="" 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

.append('style') ...

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

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

and then appending this very tag in JS file


Is this what you mean?

No, add the style directly in your js:

   .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:

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

To encode Google fonts to base64 string check this page

1 Like


Thanks for sharing this! I didn’t know about


1 Like