I am developing a web application which takes user inputs, does engineering calculations and then shows a formatted report or graphic. The graphics are engineering diagrams and not always standard graphs like Pie charts. The primary function of the application is to enable the user to copy these diagrams from the browser to a Word or Excel document.
I have to make a choice on using SVG generated in the client, or bitmaps generated on the server side. I prefer the SVG approach and the prototyping looks good, however, copying the SVG graph seems to be inconsistently supported across browsers, especially if the graph is shown in a div (i.e. the entire page is not .svg). For example, IE shows a "copy" on the dropdown, but copies only part of the SVG graphic to the clipboard. Chrome gives no copy option if I right click on the SVG graphic.
If I Google around, I am surprised to see how little information there is on the problem of getting an SVG image from a web application onto the clipboard.
My question for readers who have worked through this problem:
Is there a consistent way to get an SVG element that is part of a larger DOM onto the clipboard, preferably using JavaScript;
Any other recommendations given my requirement of getting graphics from browser onto clipboard?
SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document.
Once you're on a web page, click the extension's icon next to the URL bar and a new tab will open showing you all the SVG files it found on the page. You can copy an SVG file to your clipboard, download only the few you need, or click the 'Download all SVGs' button to add them all to a zipped file and download them.
All modern web browsers support viewing SVG files. That includes Chrome, Edge, Firefox, and Safari. So if you have an SVG and can't open it with anything else, open your favorite browser, select File > Open, then choose the SVG file you'd like to see. It will appear in your browser window.
Instead of displaying the svg
as an svg element display it with the img
tag. This has some limitations (you can't display custom fonts or embed scripts, but it seems this is not your use case). The upside is that is behaves exactly as you would expect from an image (you can drag and drop, right click and copy, etc).
To do this you need to encode it with base64. You can do it server side or client side with js. Your image tag ends up looking something like...
<img src="data:image/svg;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolf" width="..." height="..." alt="diagram" />
Where R0lGODlhEAAQAMQ...
is your base64 encoded svg.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With