1

I am creating a plot using d3js. I also want to give the ability to the user to save that plot locally at his computer. Therefore, I used a slightly changed version of the code mentioned at this question to create a downloadable picture of that plot.

So I have the following code:

$("svg").attr({ version: '1.1' , xmlns:"http://www.w3.org/2000/svg"});

var svg = $("#chart-main").html();  var b64 = btoa(unescape(encodeURIComponent(svg)));//Base64.encode(svg); // or use btoa if supported

// Works in recent Webkit(Chrome)  
$("body").append($("<img src='data:image/svg+xml;base64,\n"+b64+"' alt='file.svg'/>"));


 // Works in Firefox 3.6 and Webit and possibly any browser which supports the data-uri
  $("body").append($("<a href-lang='image/svg+xml' href='data:image/svg+xml;base64,\n"+b64+"' title='file.svg'>Download</a>"));

However, when I press on the download link I get the following error: This page contains the following errors:

error on line 6 at column 16:
Entity 'nbsp' not defined

The link is like data:image/svg+xml;base64,CgkJCQkJP....CgkJCQk=

How can I fix that?

Community
  • 1
  • 1
Jim Blum
  • 2,656
  • 5
  • 28
  • 37

1 Answers1

1

The problem is that &nbsp; is an HTML entity.

A stand-alone SVG file, as an XML format, only supports the five pre-defined XML entities: &amp;, &quot;, &apos;, &lt;, and &gt;.

To represent any other unicode character, however, you can use a character reference based on the unicode value. The code for a non-breaking space is &#160;. Use this to replace &nbsp; and your SVG file should validate.

P.S. I find FileFormat.info's character search site useful for looking up Unicode values.

AmeliaBR
  • 27,344
  • 6
  • 86
  • 119