0

I am using domtoimage to try to turn my html div into <svg>. The function from domtoimage returns the string:
data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="288" height="1920"> .......... </svg>

I can set this string as the src of an <img>, but the other plugin I'm using (jsPDF) cannot use that, it needs <svg>.

I figured I could strip the beginning part off and add just the svg tag to the document but this results in a really odd svg with "%0A" everywhere, which I cannot strip from the string.

enter image description here

Tyler N
  • 301
  • 2
  • 14
  • URIs are encoded as per [RFC3986](https://datatracker.ietf.org/doc/html/rfc3986#section-2.1) - when encountering percent encodings you need to decode them (JS provides `decodeURI()` for this). In this case `%0A` equals to a byte with the value 10, equalent to LF (line feed). In other words: those are linebreaks to beautify your SVG markup. – AmigoJack Jul 09 '21 at 21:19

1 Answers1

0

If this is your code; the problem is:

you are stuffing text into the append function which only accepts DOM nodes.

Only .innerHTML converts a string to HTML

If you feed the append function a string.. it will be displayed as a string.

https://developer.mozilla.org/en-US/docs/Web/API/Element/append

Note the documentation: DOMString objects are inserted as equivalent Text nodes.

Solution is to create an SVG DOM element

let svgElem = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svgElem.innerHTML = mySvg;
$('body').append(svgElem);
Danny '365CSI' Engelman
  • 16,526
  • 2
  • 32
  • 49