【问题标题】:Python: copy svg string to "image/svg+xml" format in windows clipboard, so can paste it as an svg imagePython:在Windows剪贴板中将svg字符串复制为“image/svg+xml”格式,因此可以将其粘贴为svg图像
【发布时间】:2019-06-19 22:09:46
【问题描述】:

假设我有一个 svg 文件的 xml 内容,如下所示:

<?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">
...

我的问题是,如何将此字符串复制到 windows 剪贴板,而不是作为字符串,而是作为“image/svg+xml”数据类型,可以作为 svg 图像粘贴到 powerpoint 中?

【问题讨论】:

    标签: python string svg mime


    【解决方案1】:

    我所知道的唯一支持 Mime 类型的剪贴板库是 QtClipboard:https://doc.qt.io/qtforpython/PySide2/QtGui/QClipboard.html

    您可能想看看它。

    可能在您可以使用setMimeData 设置的 Mime 类型中,还有 image/svg+xml

    例子:

    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']
    

    从这里你可以把它带到 QClipboard。

    我引用文档:http://doc.qt.io/archives/qt-4.8/qclipboard.html

    setMimeData() 函数具有极致的灵活性:它允许 您可以将任何 QMimeData 添加到剪贴板中。

    【讨论】:

    • 能否详细说明“还有image/svg+xml”?
    • @Alex 我说可能,我不确定它是否属于受支持的 Mime 类型。
    • 我可能在 QtClipboard 中运气不佳。它只能采用由QImage 创建的image。其他类型也不起作用,例如text。无论如何,谢谢。
    • 我不确定你做了什么,但我只是尝试过并且它有效。我将用一个例子来编辑答案。
    • @Alex 没错,这就是 Mime 类型:只是对数据的描述。而对象 MimeData 只是一个围绕字节流和字符串描述(Mime Type)的包装器
    猜你喜欢
    • 2021-01-14
    • 2012-08-28
    • 2011-01-03
    • 2019-06-27
    • 2020-11-19
    • 2021-07-05
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    相关资源
    最近更新 更多