I have inline SVG with patterns. I need two different page layouts - one for "media print" another one for browsers. I am creating everything in #svgCanvas dynamically and I need it to appear at the bottom of my print layout.
My first idea was to clone whole svg, but then I ended up with things having same ID's and Firefox and Edge got really upset about it. What are the alternatives to achieve this?
I had a look at doing svg to html5 canvas conversion but for some reason that did not really work out for me so I though maybe there is another easier way like the one below? I know it is possible to do something like this:
<img src="external.svg">
so thought I should be able to do the same with inline svg.
<span class="media-print-only">
some stuff
<img src="#svgCanvas">
</span>
<span class="no-media-print">
some more stuff
<svg id="svgCanvas">
<defs> some <patterns> </defs>
some lines and rectangles that are using patterns in defs
</svg>
again more stuff
</span>
You can use
use
element for this purpose. When you create SVG graphic withid
, you can refer it in any place by usinguse
element, like this.Note:
Base
svg
element or its ancestor elements must not havedisplay:none
style orhidden
property, because they break reference to basesvg
. So I set size of containersvg
element to 0 to hide from screen.I found a workaround to this problem - use jquery to move svg to printable place just before window.print() method and put the svg back to its original place straight after the method:
HTML
JS
Tested on Chrome, Firefox and Edge. I really hope there exists a better solution since DOM modifications are almost never a good idea.