简体   繁体   中英

Saving d3js plot locally

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM