svg.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. """ Defines utility functions for working with SVG documents in Qt.
  2. """
  3. # System library imports.
  4. from qtpy import QtCore, QtGui, QtSvg, QtWidgets
  5. # Our own imports
  6. from ipython_genutils.py3compat import unicode_type
  7. def save_svg(string, parent=None):
  8. """ Prompts the user to save an SVG document to disk.
  9. Parameters
  10. ----------
  11. string : basestring
  12. A Python string containing a SVG document.
  13. parent : QWidget, optional
  14. The parent to use for the file dialog.
  15. Returns
  16. -------
  17. The name of the file to which the document was saved, or None if the save
  18. was cancelled.
  19. """
  20. if isinstance(string, unicode_type):
  21. string = string.encode('utf-8')
  22. dialog = QtWidgets.QFileDialog(parent, 'Save SVG Document')
  23. dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
  24. dialog.setDefaultSuffix('svg')
  25. dialog.setNameFilter('SVG document (*.svg)')
  26. if dialog.exec_():
  27. filename = dialog.selectedFiles()[0]
  28. f = open(filename, 'wb')
  29. try:
  30. f.write(string)
  31. finally:
  32. f.close()
  33. return filename
  34. return None
  35. def svg_to_clipboard(string):
  36. """ Copy a SVG document to the clipboard.
  37. Parameters
  38. ----------
  39. string : basestring
  40. A Python string containing a SVG document.
  41. """
  42. if isinstance(string, unicode_type):
  43. string = string.encode('utf-8')
  44. mime_data = QtCore.QMimeData()
  45. mime_data.setData('image/svg+xml', string)
  46. QtWidgets.QApplication.clipboard().setMimeData(mime_data)
  47. def svg_to_image(string, size=None):
  48. """ Convert a SVG document to a QImage.
  49. Parameters
  50. ----------
  51. string : basestring
  52. A Python string containing a SVG document.
  53. size : QSize, optional
  54. The size of the image that is produced. If not specified, the SVG
  55. document's default size is used.
  56. Raises
  57. ------
  58. ValueError
  59. If an invalid SVG string is provided.
  60. Returns
  61. -------
  62. A QImage of format QImage.Format_ARGB32.
  63. """
  64. if isinstance(string, unicode_type):
  65. string = string.encode('utf-8')
  66. renderer = QtSvg.QSvgRenderer(QtCore.QByteArray(string))
  67. if not renderer.isValid():
  68. raise ValueError('Invalid SVG data.')
  69. if size is None:
  70. size = renderer.defaultSize()
  71. image = QtGui.QImage(size, QtGui.QImage.Format_ARGB32)
  72. image.fill(0)
  73. painter = QtGui.QPainter(image)
  74. renderer.render(painter)
  75. return image