0

Short summary of what I am trying to do:

  1. Have an svg with some text which needs to use a specific font.
  2. Have this svg appear as a single A4-page in a pdf document.

I need to do this in the browser with javascript.

After reading a bunch of thread and library documentation, it seems like the best way to get there is to first render the svg on a html canvas, create a png uri with canvas.toDataUrl(), and then finally insert this png into a pdf document (using pdf-lib).

All the step in the above mentioned pipeline work, except for one thing: the specified font is not used when drawing the svg on the canvas, and instead a fallback font is used.

A number of people on the web say the solution is to embed the font inside the svg; loading it in base64 format, or loading it by referencing the font via a url.

I have tried both versions to no avail.

My code looks like this without the extra fluff:

const MyComponent = () => {

  return (
    <svg height="100%" viewBox="0 0 100 100">
      <style>
        {`@font-face {
            font-family: "myFont",
            src: url("data:application/font-woff;char-set:utf-8;base64,${myFontBase64}"),
format("woff"); font-weight: normal;
        } `}
      </style>
      <text fontFamily="myFont">foobar</text>
    </svg>
  );
}

The interpolated myFontBase64 is a const containing the encoded font. I have also tried inserting this string directly in the src: url("... (unsucessfully)`, but resorted to this version, as the string is YUUUGE, and slows down my editor.

I don't know. Is there something wrong with the @font-face part of the code? Is this method of embedding fonts deprecated?

  • char-set is wrong, it's charset, the mime type looks to be wrong too: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types – Robert Longson Jan 20 '21 at 07:34
  • I got it working by using @Daniel Gruszczyk's answer from [this thread](https://stackoverflow.com/questions/48105468/including-fonts-when-converting-svg-to-png). I thought I was doing the same in my code, but I guess I must have had at least 1 typo somewhere. – Ludwig Nagelhus Jan 20 '21 at 07:36
  • Why was my answer deleted and made into a comment? How will I now accept an answer, and mark this as solved? – Ludwig Nagelhus Jan 20 '21 at 09:08
  • You don't need to, it's a duplicate by your own admission. – Robert Longson Jan 20 '21 at 09:31

0 Answers0