How to covert multiple svg to png in single html page? - javascript

I used d3 and venn.js for creating this venn diagram.
The code goes here : Svg actually created inside div venn2 by these scripts.
<div id="venn2"></div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="js/venn.js"></script>
<script>
var sets = [
{sets:["A"], size: 12, label: "A"},
{sets:["B"], size:12, label: "B"},
{sets: ["A", "B"], size: 4, label: "AB"}
];
var chart = venn.VennDiagram()
.wrap(false)
.fontSize("14px")
.width(400)
.height(400);
function updateVenn(sets) {
var div = d3.select("#venn2").datum(sets);
var layout = chart(div),
textCentres = layout.textCentres;
div.selectAll(".label").style("fill", "white");
div.selectAll(".venn-circle path").style("fill-opacity", .6);
return layout;
}
</script>
The script I got here to convert svg to png via canvas.
<canvas id="canvas" ></canvas>
<div id="png-container" ></div>
<script>
var svgString = new XMLSerializer().serializeToString(document.querySelector('svg'));
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([svgString], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
var png = canvas.toDataURL("image/png");
document.querySelector('#png-container').innerHTML = '<img src="'+png+'"/>';
DOMURL.revokeObjectURL(png);
};
img.src = url;
</script>
So, the venn diagram as svg was created inside venn2 div by script 1 and svg then written as a png by script 2.
It worked perfectly fine for one svg image per page.
When I have more than one such svg venn diagrams on single html page. Only the first gets converted to png.
But I am unable to fetch the svg at position 2 and 3 or more to convert to png.
I am stuck at this code
var svgString = new XMLSerializer().serializeToString(querySelectorAll('svg'));
where 'svg' means only first svg i guess but not later.
I can't even create svgs with different "id" as svg is formed by d3 and venn.js scripts.
The question is that : How to convert all svg images in a html page
when I don't know their id to png images via above code?
I do not know how to parse this whole string var svgString to convert all to different png images?

In case someone else comes looking for sample code, I figured it out as follows.
My case: I had an svg with two layers drawn by plotly. I was only getting the first layer like the OP. Plotly drew into an element with id="chart". A new canvas already created with id="layer0".
Eventually I needed to send back to PHP as a dataURL so:
var nodes = document.getElementById("chart").querySelectorAll('svg');
for (var i = 0; i < nodes.length; i++) {
result = new XMLSerializer().serializeToString(nodes[i]);
eval('layer'+[i]+'chart').src = 'data:image/svg+xml;base64,' + btoa(result);
}
elem0 = document.getElementById("layer0");
ctx0 = elem0.getContext("2d");
layer0chart.onload = function() {
ctx0.drawImage(layer0chart,0,0,w*1.5,h*1.5);
ctx0.drawImage(layer1chart,0,0,w*1.5,h*1.5);
canvasdata = elem0.toDataURL();
console.log(canvasdata);
}
I appreciate the help from #BioDeveloper and #RobertLongson. The key for me ultimately was to also make sure the toDataURL was being called as an image was being loaded. Cheers.

Related

Compare two images and see the difference using pixelmatch - refreshing canvas fails

In my codepen i want to use pixelmatch to show the difference of two images in the browser. The function is used like this
// img1, img2 — ImageData.data of the images to compare
// output — ImageData to write the diff to, or null if don't need a diff image.
// width, height of the images - all 3 images need to have the same dimensions.
// calling pixelmatch looks like this
var numDiffPixels = pixelmatch(img1.data, img2.data
, imageDataOutput, wdth, hght, {threshold: 0.1});
I got this to work
create an ImageData-Object from an <img>-tag and retrieve the data as Uint8Array from the image
pass the Uint8Array for each image using imageData.data to the function pixelmatch
fill imageDataOutput and get a number of different pixels in numDiffixels
the HTML
<p>
<img id="imgBefore" src="./img/T1_Before.jpg">
<img id="imgAfter" src="./img/T1_After.jpg" >
</p>
<p>
<button id="diff" class="js-compareImages">compare images</button>
<canvas id="cnvDiff"></canvas>
</p>
<p id="result"> </p>
Helper Function
First a helper function to get a 'canvas' from an image
// Converts image to canvas; returns new canvas element
function convertImageToCanvas(imageID) {
var image = document.getElementById(imageID);
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
// image.style = "width: 400px";
return canvas;
}
The main function
The the main function to compare the images
function compareImages()
{
var cnvBefore = convertImageToCanvas("imgBefore");
var cnvAfter = convertImageToCanvas("imgAfter");
var ctxBefore = cnvBefore.getContext("2d");
var ctxAfter = cnvAfter.getContext("2d");
let imgDataBefore = ctxBefore.getImageData(0,0,cnvBefore.width, cnvBefore.height);
let imgDataAfter = ctxAfter.getImageData(0,0, cnvAfter.width, cnvAfter.height);
const hght = imgDataBefore.height;
const wdth = imgDataBefore.width;
var imgDataOutput = new ImageData(wdth, hght);
var numDiffPixels = pixelmatch(imgDataBefore.data, imgDataAfter.data,
imgDataOutput, wdth, hght, {threshold: 0.1});
// this line does not work
writeResultToPage(imgDataOutput)
}
What does not work
using the values from imgDataOutput to show the differences of the two images in a third image or on a canvas
What is not working: either a black image is created or the output-canvas is empty
This is the code that does not produce the desired result
function writeResultToPage(imgDataOutput)
{
var canvas = document.createElement("canvas"); // new HTMLCanvasElement();
var ctx = canvas.getContext("2d");
ctx.putImageData(imgDataOutput, 0, 0);
var result = document.getElementById("result");
result.appendChild(ctx.canvas);
}
Question
Why is the output-canvas from writeResultToPage(imgDataOutput) empty?
What do i have to change to put imgDataOutput on the page as either an <img> or as a <canvas>?
Here is my matching codepen
The problem is that you need to add ".data" to imgDataOutput here:
var numDiffPixels = pixelmatch(imgDataBefore.data, imgDataAfter.data,
imgDataOutput.data, wdth, hght, {threshold: 0.1});
I also added:
canvas.width = imgDataOutput.width;
canvas.height = imgDataOutput.height;
to writeResultToPage so that the canvas is the right size for the image.
Updated codepen: https://codepen.io/anon/pen/dEVNmv

How to handle SVG and canvas in pdfmake & html2pdfmake

I am using html2pdfmake to convert a div to pdf. My div contains tables and also contains some svg charts. But i am not getting the svg into the pdf. I tried converting it using base64 but is paste the base64 code into the pdf.
I converted my svg to base64 like :
var html = d3.select('#idOfSVG').select("svg").attr("version", 1.1).attr("xmlns", "http://www.w3.org/2000/svg").node().parentNode.innerHTML;
var imgsrc = 'data:image/svg+xml;base64,'+ btoa(html);
var base_image = new Image();
base_image.src = imgsrc;
canvas = document.createElement('canvas');
canvas.id = 'canvas'
document.body.appendChild(canvas);
canvas.width = 500;
canvas.height = 500;
canvas.getContext('2d').drawImage(base_image,0,0);
Then i added the same into the content.
Also when i used ParseHtml(content,document.getElementById("myPDFDiv"))
My div myPDFDiv gets deleted from the DOM.
Any help will be highly appreciated !!
You can use html2pdfmake, it iterates all the elements in the div and make JSON for the same which you can use with pdfmake.
You can add SVG support by adding a switch case for SVG like :
Case 'SVG' :
addImage(cnt,e);
function addImage (cnt,e) {
//Serialize the svg element and then put it in a canvas
//Then update the cnt object
var url = canvas.toDataURL('image/png');
cnt.push({image: url,
width: 200,
height: 250,
margin: [ 20, 0, 0, 0 ]
});
}
Hope it helps !!

Export external SVG file painted with Javascript to PNG image

I am using an svg map from an external file. I insert it to my html code using the "object" tag.
<object id="mymap" data="map.svg" width="884" height="760" type="image/svg+xml" ></object>
In javascript I paint paths of the svg map with some given colors. For example:
<script>
var path1 = document.getElementById('mymap').getSVGDocument().getElementById('path1');
path1.style.fill='#f00';
var path2 = document.getElementById('mymap').getSVGDocument().getElementById('path2');
path2.style.fill='#0f0';
</script>
How can I export the resulted coloured map as a PNG image?
--UPDATE-- : The question has been answered, and the LiveExample now includes the solution for future reference. You can view the source and get the solution. The example draws a map and saves drawn map in a canvas that you can then save as file
Example Solution Displaying the canvas
Example Solution Hiding the canvas with direct download to generated image
Solution is the following:
Based on my accepted solution I include the full javascript that manages all steps
Create a canvas
<canvas id="canvas" style="border:1px solid black;" width="884" height="760"></canvas>
Draw into that canvas the image from the painted svg
function drawCanvas(){
// create a canvas and context
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// define svgdocument and make blob containing its data
var svgDoc = document.getElementById('mymap').getSVGDocument();
var svg = new Blob([svgDoc.lastChild.outerHTML], {type: 'image/svg+xml;charset=utf-8'});
// create a new image
var DOMURL = window.URL || window.webkitURL || window;
var url = DOMURL.createObjectURL(svg);
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0,884,760);
DOMURL.revokeObjectURL(url);
};
img.src = url;
}
Example Solution Displaying the canvas
Example Solution Hiding the canvas with direct download to generated image
What about drawing the svg to the canvas, and then use the .toDataURL to get as PNG image?
--Update--
For a quick test, i run the below in the console from your live demo:
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var svgDoc = document.getElementById('mymap').getSVGDocument();
var svg = new Blob([svgDoc.lastChild.outerHTML], {type: 'image/svg+xml;charset=utf-8'});
var img = new Image();
img.onload = function(){ ctx.drawImage(img,0,0); };
img.src = url
you should see the url, which has the image draw, at this time just call the .toDataURL you should get the base64 image data

Export Highcharts to PDF (using javascript and local server - no internet connection)

I am using Highcharts in my application (without any internet connection)
I have multiple charts on a html page, and I want to generate a PDF report that contains all the charts from this page.
How can I do this without sending the data to any server on the internet ?
I will be thankful for any help or any example you can provide.
Thank you in advance :)
Yes this is possible but involves a few different libraries to get working. The first Library is jsPDF which allows the creation of PDF in the browser. The second is canvg which allows for the rendering and parsing of SVG's, the bit that is really cool though is it can render an svg on to canvas element. Lastly is Highcharts export module which will allow us to send the svg to the canvg to turn into a data URL which can then be given to jsPDF to turn into your pdf.
Here is an example http://fiddle.jshell.net/leighking2/dct9tfvn/ you can also see in there source files you will need to include in your project.
So to start highcharts provides an example of using canvg with it's export to save a chart as a png. because you want all the iamges in a pdf this has been slightly altered for our purpose to just return the data url
// create canvas function from highcharts example http://jsfiddle.net/highcharts/PDnmQ/
(function (H) {
H.Chart.prototype.createCanvas = function (divId) {
var svg = this.getSVG(),
width = parseInt(svg.match(/width="([0-9]+)"/)[1]),
height = parseInt(svg.match(/height="([0-9]+)"/)[1]),
canvas = document.createElement('canvas');
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
if (canvas.getContext && canvas.getContext('2d')) {
canvg(canvas, svg);
return canvas.toDataURL("image/jpeg");
} 
else {
alert("Your browser doesn't support this feature, please use a modern browser");
return false;
}
}
}(Highcharts));
Then for the example i have set up export on a button click. This will look for all elements of a certain class (so choose one to add to all of your chart elements) and then call their highcharts.createCanvas function.
$('#export_all').click(function () {
var doc = new jsPDF();
// chart height defined here so each chart can be palced
// in a different position
var chartHeight = 80;
// All units are in the set measurement for the document
// This can be changed to "pt" (points), "mm" (Default), "cm", "in"
doc.setFontSize(40);
doc.text(35, 25, "My Exported Charts");
//loop through each chart
$('.myChart').each(function (index) {
var imageData = $(this).highcharts().createCanvas();
// add image to doc, if you have lots of charts,
// you will need to check if you have gone bigger
// than a page and do doc.addPage() before adding
// another image.
/**
* addImage(imagedata, type, x, y, width, height)
*/
doc.addImage(imageData, 'JPEG', 45, (index * chartHeight) + 40, 120, chartHeight);
});
//save with name
doc.save('demo.pdf');
});
important to note here that if you have lots of charts you will need to handle placing them on a new page. The documentation for jsPDF looks really outdated (they do have a good demos page though just not a lot to explain all the options possible), there is an addPage() function and then you can just play with widths and heights until you find something that works.
the last part is to just setup the graphs with an extra option to not display the export button on each graph that would normally display.
//charts
$('#chart1').highcharts({
navigation: {
buttonOptions: {
enabled: false
}
},
//this is just normal highcharts setup form here for two graphs see fiddle for full details
The result isn't too bad i'm impressed with the quality of the graphs as I wasn't expecting much from this, with some playing of the pdf positions and sizes could look really good.
Here is a screen shot showing the network requests made before and after the export, when the export is made no requests are made http://i.imgur.com/ppML6Gk.jpg
here is an example of what the pdf looks like http://i.imgur.com/6fQxLZf.png (looks better when view as actual pdf)
quick example to be tried on local https://github.com/leighquince/HighChartLocalExport
You need to setup your own exporting server, locally like in the article
Here is an example using the library pdfmake:
html:
<div id="chart_exchange" style="width: 450px; height: 400px; margin: 0 auto"></div>
<button id="export">export</button>
<canvas id="chart_exchange_canvas" width="450" height="400" style="display: none;"></canvas>
javascript:
function drawInlineSVG(svgElement, canvas_id, callback) {
var can = document.getElementById(canvas_id);
var ctx = can.getContext('2d');
var img = new Image();
img.setAttribute('src', 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgElement))));
img.onload = function() {
ctx.drawImage(img, 0, 0);
callback(can.toDataURL("image/png"));
}
}
full working code:
https://jsfiddle.net/dimitrisscript/f6sbdsps/
Maybe this link can help you out.
http://bit.ly/1IYJIyF
Try refer to the exporting properties (fallbackToExportServer: false) and the necessary file that need to be include (offline-exporting.js).
Whereas for the export all at once part, currently I myself also still trying. Will update here if any.
This question is a bit old but was something i was working on myself recently and had some trouble with it.
I used the jsPDF library: https://github.com/MrRio/jsPDF
Issues i ran into involved jsPDF not supporting the SVG image exported by the high chart + images being blurry and low quality.
Below is the solution I used to get two charts into one pdf document:
function createPDF() {
var doc = new jsPDF('p', 'pt', 'a4'); //Create pdf
if ($('#chart1').length > 0) {
var chartSVG = $('#chart1').highcharts().getSVG();
var chartImg = new Image();
chartImg.onload = function () {
var w = 762;
var h = 600;
var chartCanvas = document.createElement('canvas');
chartCanvas.width = w * 2;
chartCanvas.height = h * 2;
chartCanvas.style.width = w + 'px';
chartCanvas.style.height = h + 'px';
var context = chartCanvas.getContext('2d');
chartCanvas.webkitImageSmoothingEnabled = true;
chartCanvas.mozImageSmoothingEnabled = true;
chartCanvas.imageSmoothingEnabled = true;
chartCanvas.imageSmoothingQuality = "high";
context.scale(2, 2);
chartCanvas.getContext('2d').drawImage(chartImg, 0, 0, 762, 600);
var chartImgData = chartCanvas.toDataURL("image/png");
doc.addImage(chartImgData, 'png', 40, 260, 250, 275);
if ($('#chart2').length > 0) {
var chart2SVG = $('#chart2').highcharts().getSVG(),
chart2Img = new Image();
chart2Img.onload = function () {
var chart2Canvas = document.createElement('canvas');
chart2Canvas.width = w * 2;
chart2Canvas.height = h * 2;
chart2Canvas.style.width = w + 'px';
chart2Canvas.style.height = h + 'px';
var context = chart2Canvas.getContext('2d');
chart2Canvas.webkitImageSmoothingEnabled = true;
chart2Canvas.mozImageSmoothingEnabled = true;
chart2Canvas.imageSmoothingEnabled = true;
chart2Canvas.imageSmoothingQuality = "high";
context.scale(2, 2);
chart2Canvas.getContext('2d').drawImage(chart2Img, 0, 0, 762, 600);
var chart2ImgData = chart2Canvas.toDataURL("image/png");
doc.addImage(chart2ImgData, 'PNG', 300, 260, 250, 275);
doc.save('ChartReport.pdf');
}
chart2Img.src = "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(chart2SVG)));
}
}
chartImg.src = "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(chartSVG)));
}
}
scripts to include:
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>

How do I save/export an SVG file after creating an SVG with D3.js (IE, safari and chrome)?

I currently have a website using D3 and I'd like the user to have the option to save the SVG as an SVG file. I'm using crowbar.js to do this, but it only works on chrome. Nothing happens of safari and IE gives an access denied on the click() method used in crowbar.js to download the file.
var e = document.createElement('script');
if (window.location.protocol === 'https:') {
e.setAttribute('src', 'https://raw.github.com/NYTimes/svg-crowbar/gh-pages/svg-crowbar.js');
} else {
e.setAttribute('src', 'http://nytimes.github.com/svg-crowbar/svg-crowbar.js');
}
e.setAttribute('class', 'svg-crowbar');
document.body.appendChild(e);
How do I download an SVG file based on the SVG element on my website in safari, IE and chrome?
There are 5 steps. I often use this method to output inline svg.
get inline svg element to output.
get svg source by XMLSerializer.
add name spaces of svg and xlink.
construct url data scheme of svg by encodeURIComponent method.
set this url to href attribute of some "a" element, and right click this link to download svg file.
//get svg element.
var svg = document.getElementById("svg");
//get svg source.
var serializer = new XMLSerializer();
var source = serializer.serializeToString(svg);
//add name spaces.
if(!source.match(/^<svg[^>]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)){
source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
}
if(!source.match(/^<svg[^>]+"http\:\/\/www\.w3\.org\/1999\/xlink"/)){
source = source.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
}
//add xml declaration
source = '<?xml version="1.0" standalone="no"?>\r\n' + source;
//convert svg source to URI data scheme.
var url = "data:image/svg+xml;charset=utf-8,"+encodeURIComponent(source);
//set url value to a element's href attribute.
document.getElementById("link").href = url;
//you can download svg file by right click menu.
I know this has already been answered, and that answer works well most of the time. However I found that it failed on Chrome (but not Firefox) if the svg image was large-ish (about 1MB). It works if you go back to using a Blob construct, as described here and here. The only difference is the type argument. In my code I wanted a single button press to download the svg for the user, which I accomplished with:
var svgData = $("#figureSvg")[0].outerHTML;
var svgBlob = new Blob([svgData], {type:"image/svg+xml;charset=utf-8"});
var svgUrl = URL.createObjectURL(svgBlob);
var downloadLink = document.createElement("a");
downloadLink.href = svgUrl;
downloadLink.download = "newesttree.svg";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
October 2019 edit:
Comments have indicated that this code will work even without appending downloadLink to document.body and subsequently removing it after click(). I believe that used to work on Firefox, but as of now it no longer does (Firefox requires that you append and then remove downloadLink). The code works on Chrome either way.
Combining Dave's and defghi1977 answers. Here is a reusable function:
function saveSvg(svgEl, name) {
svgEl.setAttribute("xmlns", "http://www.w3.org/2000/svg");
var svgData = svgEl.outerHTML;
var preface = '<?xml version="1.0" standalone="no"?>\r\n';
var svgBlob = new Blob([preface, svgData], {type:"image/svg+xml;charset=utf-8"});
var svgUrl = URL.createObjectURL(svgBlob);
var downloadLink = document.createElement("a");
downloadLink.href = svgUrl;
downloadLink.download = name;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
Invocation example:
saveSvg(svg, 'test.svg')
For this snippet to work you need FileSaver.js.
function save_as_svg(){
var svg_data = document.getElementById("svg").innerHTML //put id of your svg element here
var head = '<svg title="graph" version="1.1" xmlns="http://www.w3.org/2000/svg">'
//if you have some additional styling like graph edges put them inside <style> tag
var style = '<style>circle {cursor: pointer;stroke-width: 1.5px;}text {font: 10px arial;}path {stroke: DimGrey;stroke-width: 1.5px;}</style>'
var full_svg = head + style + svg_data + "</svg>"
var blob = new Blob([full_svg], {type: "image/svg+xml"});
saveAs(blob, "graph.svg");
};
I tryed every solution here and nothing worked for me. My picture was always smaller than my d3.js canvas.
I had to set the canvas width, height then do a clearRect on the context to make it works. Here is my working version
Export function:
var svgHtml = document.getElementById("d3-canvas"),
svgData = new XMLSerializer().serializeToString(svgHtml),
svgBlob = new Blob([svgData], {type:"image/svg+xml;charset=utf-8"}),
bounding = svgHtml.getBoundingClientRect(),
width = bounding.width * 2,
height = bounding.height * 2,
canvas = document.createElement("canvas"),
context = canvas.getContext("2d"),
exportFileName = 'd3-graph-image.png';
//Set the canvas width and height before loading the new Image
canvas.width = width;
canvas.height = height;
var image = new Image();
image.onload = function() {
//Clear the context
context.clearRect(0, 0, width, height);
context.drawImage(image, 0, 0, width, height);
//Create blob and save if with FileSaver.js
canvas.toBlob(function(blob) {
saveAs(blob, exportFileName);
});
};
var svgUrl = URL.createObjectURL(svgBlob);
image.src = svgUrl;
It use FileSaver.js to save the file.
This is my canvas creation, note that i solve the namespace issue here
d3.js canvas creation:
var canvas = d3.select("body")
.insert("svg")
.attr('id', 'd3-canvas')
//Solve the namespace issue (xmlns and xlink)
.attr("xmlns", "http://www.w3.org/2000/svg")
.attr("xmlns:xlink", "http://www.w3.org/1999/xlink")
.attr("width", width)
.attr("height", height);
While this question has been answered, I created a small library called SaveSVG which can help save D3.js generated SVG which use external stylesheets or external definition files (using <use> and def) tags.
Based on #vasyl-vaskivskyi 's answer.
<script src="../../assets/FileSaver.js"></script>
<script>
function save_as_svg(){
fetch('path/../assets/chart.css')
.then(response => response.text())
.then(text => {
var svg_data = document.getElementById("svg").innerHTML
var head = '<svg title="graph" version="1.1" xmlns="http://www.w3.org/2000/svg">'
var style = "<style>" + text + "</style>"
var full_svg = head + style + svg_data + "</svg>"
var blob = new Blob([full_svg], {type: "image/svg+xml"});
saveAs(blob, "graph.svg");
})
};
save_as_svg();
</script>
The above code read your chart.css and then embed the css code to your svg file.
I try this and worked for me.
function downloadSvg() {
var svg = document.getElementById("svg");
var serializer = new XMLSerializer();
var source = serializer.serializeToString(svg);
source = source.replace(/(\w+)?:?xlink=/g, 'xmlns:xlink='); // Fix root xlink without namespace
source = source.replace(/ns\d+:href/g, 'xlink:href'); // Safari NS namespace fix.
if (!source.match(/^<svg[^>]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)) {
source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
}
if (!source.match(/^<svg[^>]+"http\:\/\/www\.w3\.org\/1999\/xlink"/)) {
source = source.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
}
var preface = '<?xml version="1.0" standalone="no"?>\r\n';
var svgBlob = new Blob([preface, source], { type: "image/svg+xml;charset=utf-8" });
var svgUrl = URL.createObjectURL(svgBlob);
var downloadLink = document.createElement("a");
downloadLink.href = svgUrl;
downloadLink.download = name;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
In my scenario, I had to use some svg images created using D3.js in other projects. So I opened dev tools and inspected those svg and copied their content. Then created a new blank svg file and pasted the copied content there. Then I used those new svg files in other areas.
And if you want to do it programmatically, then we can use document.getElementById('svgId')
I know this is a basic approach but in case anyone find it useful.

Categories