Search code examples
pythonstringsvgmime

How do I copy an SVG XML string so I can paste it as an SVG image?


I have the XML contents of an SVG file:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
 "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Created with matplotlib (http://matplotlib.org/) -->
<svg height="344.88pt" version="1.1" viewBox="0 0 460.8 344.88" width="460.8pt"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
...

How to copy this string to Windows clipboard, not as string but as "image/svg+xml" data type so it can be pasted into PowerPoint as an SVG image?


Solution

  • The only clipboard library that I know of that supports Mime types is the QtClipboard: https://doc.qt.io/qtforpython/PySide2/QtGui/QClipboard.html

    You might want to take a look at it.

    Possibly among the Mime Types you can set with setMimeData there is also image/svg+xml

    Example:

    from PyQt5 import QtCore
    d = QtCore.QMimeData()
    print(d.formats())  # Now it is an empty list "[]" because you still didn't set the data and the mime type
    
    # Set data in the object with the required mime type
    d.setData("image/svg+xml", b'<?xml version="1.0" encoding="utf-8" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><!-- Created with matplotlib (http://matplotlib.org/) --><svg height="344.88pt" version="1.1" viewBox="0 0 460.8 344.88" width="460.8pt" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">')
    
    print(d.formats())  # Now it prints: ['image/svg+xml']
    

    From here you can take it to QClipboard.

    I quote the documentation: http://doc.qt.io/archives/qt-4.8/qclipboard.html

    The setMimeData() function is the ultimate in flexibility: it allows you to add any QMimeData into the clipboard.