Skip to content

Instantly share code, notes, and snippets.

@bkamapantula
Created May 7, 2020 15:04
Show Gist options
  • Save bkamapantula/ae021fde2bb08279133ce1272a14d46a to your computer and use it in GitHub Desktop.
Save bkamapantula/ae021fde2bb08279133ce1272a14d46a to your computer and use it in GitHub Desktop.
Export SVG to image (SVG, PNG) formats

While external style definitions are retained for SVG they aren't for PNG export.

function export_chart(format) {
// https://stackoverflow.com/a/46403589
canvas.setAttribute('width', parseInt($('.chart').width()))
canvas.setAttribute('height', parseInt($('.chart').height()))
var imgURI, svgUrl
var el = document.querySelector('.chart svg')
if(format == 'svg') {
// https://stackoverflow.com/a/46403589
el.setAttribute("xmlns", "http://www.w3.org/2000/svg")
var svgData = el.outerHTML
var preface = css_flag ? `<?xml version="1.0" standalone="no"?><?xml-stylesheet type="text/css" href="https://gramener.com/gramexcharts/charts/${which_chart}/chart.css"?>\r\n` : '<?xml version="1.0" standalone="no"?><?xml-stylesheet type="text/css"?>\r\n'
var svgBlob = new Blob([preface, svgData], {type:"image/svg+xml;charset=utf-8"})
svgUrl = URL.createObjectURL(svgBlob)
var downloadLink = document.createElement("a")
downloadLink.href = svgUrl
downloadLink.download = `chart.${format}`
document.body.appendChild(downloadLink)
downloadLink.click()
document.body.removeChild(downloadLink)
} else {
// https://stackoverflow.com/questions/28226677/save-inline-svg-as-jpeg-png-svg
var svgData = (new XMLSerializer()).serializeToString(el)
var ccanvas = document.getElementById("chartCanvas")
var ctx = ccanvas.getContext("2d")
var svgBlob = new Blob([svgData], {type:"image/svg+xml;charset=utf-8"})
svgUrl = URL.createObjectURL(svgBlob)
var img = new Image()
img.onload = function() {
ctx.drawImage(img, 0, 0)
URL.revokeObjectURL(svgUrl)
imgURI = ccanvas.toDataURL('image/png')
.replace('image/png', 'image/octet-stream')
var evt = new MouseEvent('click', {
view: window,
bubbles: false,
cancelable: true
})
var a = document.createElement('a')
a.setAttribute('download', 'chart.png')
a.setAttribute('href', imgURI)
a.setAttribute('target', '_blank')
a.dispatchEvent(evt)
}
img.src = svgUrl
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment