|
| 1 | +export function exportSvg(svgElement, fileName = 'mySvg.svg') { |
| 2 | + if (!svgElement) return false |
| 3 | + |
| 4 | + const clone = svgElement.cloneNode(true) |
| 5 | + |
| 6 | + if (!clone.hasAttribute('xmlns')) { |
| 7 | + clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg') |
| 8 | + } |
| 9 | + |
| 10 | + const inlineImportantStyles = (el) => { |
| 11 | + try { |
| 12 | + const cs = window.getComputedStyle(el) |
| 13 | + const props = [ |
| 14 | + 'stroke', |
| 15 | + 'stroke-width', |
| 16 | + 'stroke-linecap', |
| 17 | + 'stroke-linejoin', |
| 18 | + 'fill', |
| 19 | + 'opacity', |
| 20 | + 'stroke-dasharray', |
| 21 | + 'stroke-dashoffset', |
| 22 | + 'color', |
| 23 | + 'font-size', |
| 24 | + ] |
| 25 | + props.forEach((p) => { |
| 26 | + const v = cs.getPropertyValue(p) |
| 27 | + if (v) el.setAttribute(p, v) |
| 28 | + }) |
| 29 | + } catch (e) { |
| 30 | + // ignore |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + ;[clone, ...Array.from(clone.querySelectorAll('*'))].forEach(inlineImportantStyles) |
| 35 | + |
| 36 | + const rect = svgElement.getBoundingClientRect() |
| 37 | + const width = clone.getAttribute('width') || rect.width || 300 |
| 38 | + const height = clone.getAttribute('height') || rect.height || 150 |
| 39 | + clone.setAttribute('width', width) |
| 40 | + clone.setAttribute('height', height) |
| 41 | + |
| 42 | + if (!clone.hasAttribute('viewBox')) { |
| 43 | + try { |
| 44 | + const bbox = clone.getBBox() |
| 45 | + if (bbox && bbox.width && bbox.height) { |
| 46 | + clone.setAttribute('viewBox', `${bbox.x} ${bbox.y} ${bbox.width} ${bbox.height}`) |
| 47 | + } else { |
| 48 | + clone.setAttribute('viewBox', `0 0 ${width} ${height}`) |
| 49 | + } |
| 50 | + } catch (e) { |
| 51 | + clone.setAttribute('viewBox', `0 0 ${width} ${height}`) |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + const svgContent = new XMLSerializer().serializeToString(clone) |
| 56 | + const blob = new Blob([svgContent], { type: 'image/svg+xml;charset=utf-8' }) |
| 57 | + const url = URL.createObjectURL(blob) |
| 58 | + const a = document.createElement('a') |
| 59 | + a.href = url |
| 60 | + a.download = fileName || 'mySvg.svg' |
| 61 | + document.body.appendChild(a) |
| 62 | + a.click() |
| 63 | + a.remove() |
| 64 | + URL.revokeObjectURL(url) |
| 65 | + return true |
| 66 | +} |
| 67 | + |
| 68 | +export default exportSvg |
0 commit comments