##// END OF EJS Templates
fix UnicodeEncodeError writing SVG string to .svg file, fixes #489
Martin Spacek -
Show More
@@ -1,86 +1,86 b''
1 1 """ Defines utility functions for working with SVG documents in Qt.
2 2 """
3 3
4 4 # System library imports.
5 5 from IPython.external.qt import QtCore, QtGui, QtSvg
6 6
7 7
8 8 def save_svg(string, parent=None):
9 9 """ Prompts the user to save an SVG document to disk.
10 10
11 11 Parameters:
12 12 -----------
13 13 string : basestring
14 14 A Python string containing a SVG document.
15 15
16 16 parent : QWidget, optional
17 17 The parent to use for the file dialog.
18 18
19 19 Returns:
20 20 --------
21 21 The name of the file to which the document was saved, or None if the save
22 22 was cancelled.
23 23 """
24 24 dialog = QtGui.QFileDialog(parent, 'Save SVG Document')
25 25 dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
26 26 dialog.setDefaultSuffix('svg')
27 27 dialog.setNameFilter('SVG document (*.svg)')
28 28 if dialog.exec_():
29 29 filename = dialog.selectedFiles()[0]
30 30 f = open(filename, 'w')
31 31 try:
32 f.write(string)
32 f.write(string.encode('UTF-8'))
33 33 finally:
34 34 f.close()
35 35 return filename
36 36 return None
37 37
38 38 def svg_to_clipboard(string):
39 39 """ Copy a SVG document to the clipboard.
40 40
41 41 Parameters:
42 42 -----------
43 43 string : basestring
44 44 A Python string containing a SVG document.
45 45 """
46 46 if isinstance(string, unicode):
47 47 string = string.encode('utf-8')
48 48
49 49 mime_data = QtCore.QMimeData()
50 50 mime_data.setData('image/svg+xml', string)
51 51 QtGui.QApplication.clipboard().setMimeData(mime_data)
52 52
53 53 def svg_to_image(string, size=None):
54 54 """ Convert a SVG document to a QImage.
55 55
56 56 Parameters:
57 57 -----------
58 58 string : basestring
59 59 A Python string containing a SVG document.
60 60
61 61 size : QSize, optional
62 62 The size of the image that is produced. If not specified, the SVG
63 63 document's default size is used.
64 64
65 65 Raises:
66 66 -------
67 67 ValueError
68 68 If an invalid SVG string is provided.
69 69
70 70 Returns:
71 71 --------
72 72 A QImage of format QImage.Format_ARGB32.
73 73 """
74 74 if isinstance(string, unicode):
75 75 string = string.encode('utf-8')
76 76
77 77 renderer = QtSvg.QSvgRenderer(QtCore.QByteArray(string))
78 78 if not renderer.isValid():
79 79 raise ValueError('Invalid SVG data.')
80 80
81 81 if size is None:
82 82 size = renderer.defaultSize()
83 83 image = QtGui.QImage(size, QtGui.QImage.Format_ARGB32)
84 84 painter = QtGui.QPainter(image)
85 85 renderer.render(painter)
86 86 return image
General Comments 0
You need to be logged in to leave comments. Login now