nytimes / svg-crowbar

Extracts an SVG node and accompanying styles from an HTML document and allows you to download it all as an SVG file.
https://nytimes.github.io/svg-crowbar/
MIT License
839 stars 152 forks source link

Does not pull in external SVG elements (e.g. referenced in CSS) #8

Open msjgriffiths opened 10 years ago

msjgriffiths commented 10 years ago

If there are multiple SVG documents on a page, and one contains a node that can be used as a fill in CSS, the scripts does not pull that into the output.

For example, consider this example, which uses D3 to load a shapefile and create a world map. CSS and a SVG element in the page HTML are applied to style the dynamically created SVG element.

http://becausedata.com/tmp/svg-crowbar/radial-gradiant/

<style type="text/css">
.map {
        fill: url(#g489);
        stroke:#ddd;
        stroke-width:1px;
    }
</style>

<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"  preserveAspectRatio="none">
    <radialGradient id="g489" gradientUnits="objectBoundingBox" cx="50%" cy="50%" r="50%">
        <stop stop-color="#999" offset="10%"/>
        <stop stop-color="#666" offset="95%"/>
    </radialGradient>
</svg>

The browser will apply the radialGradient directly, but it will not be merged into the downloaded SVG document (unsurprisingly).

The easiest workaround is to include the contents of the second SVG element inside the dynamically created one, e.g. via .appendChild() after load. In general, this works pretty well, but it does require an extra step.

mchwalisz commented 10 years ago

It doesn't work for any external elements. The following example works in chrome (image is pulled and shown) but it shows ugly missing image icon when downloaded.

<svg width="796" height="455" viewBox="0 0 700 400" perserveaspectratio="xMinYMid" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <image x="0" y="0" width="700" height="400" opacity="0.5" type="image/svg+xml" xlink:href="/static/data/plan.svg"></image>
</svg>
eformx commented 8 years ago

This works great!

http://spin.atomicobject.com/2014/01/21/convert-svg-to-png/