svgcross-browserclipboard

How to copy SVG images from the browser to the clipboard


I am developing a web application which takes user inputs and then shows a formatted report or graphic. 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.

Is there a consistent way to get an SVG element that is part of a larger DOM onto the clipboard, preferably using JavaScript?


Solution

  • 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 JavaScript. Your <img> tag ends up looking something like this:

    <img src="data:image/svg;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolf" width="..." height="..." alt="diagram" />
    

    Where R0lGODlhEAAQAMQ... is your Base64-encoded SVG.