renderSVG.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. __doc__="""An experimental SVG renderer for the ReportLab graphics framework.
  2. This will create SVG code from the ReportLab Graphics API (RLG).
  3. To read existing SVG code and convert it into ReportLab graphics
  4. objects download the svglib module here:
  5. http://python.net/~gherman/#svglib
  6. """
  7. import math, types, sys, os, codecs, base64
  8. from operator import getitem
  9. from reportlab.pdfbase.pdfmetrics import stringWidth # for font info
  10. from reportlab.lib.rl_accel import fp_str
  11. from reportlab.lib.colors import black
  12. from reportlab.lib.utils import asNative, getBytesIO
  13. from reportlab.graphics.renderbase import StateTracker, getStateDelta, Renderer, renderScaledDrawing
  14. from reportlab.graphics.shapes import STATE_DEFAULTS, Path, UserNode
  15. from reportlab.graphics.shapes import * # (only for test0)
  16. from reportlab import rl_config
  17. from reportlab.lib.utils import getStringIO, RLString, isUnicode, isBytes
  18. from reportlab.pdfgen.canvas import FILL_EVEN_ODD, FILL_NON_ZERO
  19. from .renderPM import _getImage
  20. from xml.dom import getDOMImplementation
  21. ### some constants ###
  22. sin = math.sin
  23. cos = math.cos
  24. pi = math.pi
  25. AREA_STYLES = 'stroke-width stroke-linecap stroke stroke-opacity fill fill-opacity stroke-dasharray stroke-dashoffset fill-rule id'.split()
  26. LINE_STYLES = 'stroke-width stroke-linecap stroke stroke-opacity stroke-dasharray stroke-dashoffset id'.split()
  27. TEXT_STYLES = 'font-family font-weight font-style font-variant font-size id'.split()
  28. EXTRA_STROKE_STYLES = 'stroke-width stroke-linecap stroke stroke-opacity stroke-dasharray stroke-dashoffset'.split()
  29. EXTRA_FILL_STYLES = 'fill fill-opacity'.split()
  30. ### top-level user function ###
  31. def drawToString(d, showBoundary=rl_config.showBoundary,**kwds):
  32. "Returns a SVG as a string in memory, without touching the disk"
  33. s = getStringIO()
  34. drawToFile(d, s, showBoundary=showBoundary,**kwds)
  35. return s.getvalue()
  36. def drawToFile(d, fn, showBoundary=rl_config.showBoundary,**kwds):
  37. d = renderScaledDrawing(d)
  38. c = SVGCanvas((d.width, d.height),**kwds)
  39. draw(d, c, 0, 0, showBoundary=showBoundary)
  40. c.save(fn)
  41. def draw(drawing, canvas, x=0, y=0, showBoundary=rl_config.showBoundary):
  42. """As it says."""
  43. r = _SVGRenderer()
  44. r.draw(renderScaledDrawing(drawing), canvas, x, y, showBoundary=showBoundary)
  45. ### helper functions ###
  46. def _pointsFromList(L):
  47. """
  48. given a list of coordinates [x0, y0, x1, y1....]
  49. produce a list of points [(x0,y0), (y1,y0),....]
  50. """
  51. P=[]
  52. for i in range(0,len(L), 2):
  53. P.append((L[i], L[i+1]))
  54. return P
  55. def transformNode(doc, newTag, node=None, **attrDict):
  56. """Transform a DOM node into new node and copy selected attributes.
  57. Creates a new DOM node with tag name 'newTag' for document 'doc'
  58. and copies selected attributes from an existing 'node' as provided
  59. in 'attrDict'. The source 'node' can be None. Attribute values will
  60. be converted to strings.
  61. E.g.
  62. n = transformNode(doc, "node1", x="0", y="1")
  63. -> DOM node for <node1 x="0" y="1"/>
  64. n = transformNode(doc, "node1", x=0, y=1+1)
  65. -> DOM node for <node1 x="0" y="2"/>
  66. n = transformNode(doc, "node1", node0, x="x0", y="x0", zoo=bar())
  67. -> DOM node for <node1 x="[node0.x0]" y="[node0.y0]" zoo="[bar()]"/>
  68. """
  69. newNode = doc.createElement(newTag)
  70. for newAttr, attr in attrDict.items():
  71. sattr = str(attr)
  72. if not node:
  73. newNode.setAttribute(newAttr, sattr)
  74. else:
  75. attrVal = node.getAttribute(sattr)
  76. newNode.setAttribute(newAttr, attrVal or sattr)
  77. return newNode
  78. class EncodedWriter(list):
  79. '''
  80. EncodedWriter(encoding) assumes .write will be called with
  81. either unicode or utf8 encoded bytes. it will accumulate
  82. unicode
  83. '''
  84. BOMS = {
  85. 'utf-32':codecs.BOM_UTF32,
  86. 'utf-32-be':codecs.BOM_UTF32_BE,
  87. 'utf-32-le':codecs.BOM_UTF32_LE,
  88. 'utf-16':codecs.BOM_UTF16,
  89. 'utf-16-be':codecs.BOM_UTF16_BE,
  90. 'utf-16-le':codecs.BOM_UTF16_LE,
  91. }
  92. def __init__(self,encoding,bom=False):
  93. list.__init__(self)
  94. self.encoding = encoding = codecs.lookup(encoding).name
  95. if bom and '16' in encoding or '32' in encoding:
  96. self.write(self.BOMS[encoding])
  97. def write(self,u):
  98. if isBytes(u):
  99. try:
  100. u = u.decode('utf-8')
  101. except:
  102. et, ev, tb = sys.exc_info()
  103. ev = str(ev)
  104. del et, tb
  105. raise ValueError("String %r not encoded as 'utf-8'\nerror=%s" % (u,ev))
  106. elif not isUnicode(u):
  107. raise ValueError("EncodedWriter.write(%s) argument should be 'utf-8' bytes or str" % ascii(u))
  108. self.append(u)
  109. def getvalue(self):
  110. r = ''.join(self)
  111. del self[:]
  112. return r
  113. _fillRuleMap = {
  114. FILL_NON_ZERO: 'nonzero',
  115. 'non-zero': 'nonzero',
  116. 'nonzero': 'nonzero',
  117. FILL_EVEN_ODD: 'evenodd',
  118. 'even-odd': 'evenodd',
  119. 'evenodd': 'evenodd',
  120. }
  121. def py_fp_str(*args):
  122. return ' '.join((('%f' % a).rstrip('0').rstrip('.') for a in args))
  123. ### classes ###
  124. class SVGCanvas:
  125. def __init__(self, size=(300,300), encoding='utf-8', verbose=0, bom=False, **kwds):
  126. '''
  127. verbose = 0 >0 means do verbose stuff
  128. useClip = False True means don't use a clipPath definition put the global clip into the clip property
  129. to get around an issue with safari
  130. extraXmlDecl = '' use to add extra xml declarations
  131. scaleGroupId = '' id of an extra group to add around the drawing to allow easy scaling
  132. svgAttrs = {} dictionary of attributes to be applied to the svg tag itself
  133. '''
  134. self.verbose = verbose
  135. self.encoding = codecs.lookup(encoding).name
  136. self.bom = bom
  137. useClip = kwds.pop('useClip',False)
  138. self.fontHacks = kwds.pop('fontHacks',{})
  139. self.extraXmlDecl = kwds.pop('extraXmlDecl','')
  140. scaleGroupId = kwds.pop('scaleGroupId','')
  141. self._fillMode = FILL_EVEN_ODD
  142. self.width, self.height = self.size = size
  143. # self.height = size[1]
  144. self.code = []
  145. self.style = {}
  146. self.path = ''
  147. self._strokeColor = self._fillColor = self._lineWidth = \
  148. self._font = self._fontSize = self._lineCap = \
  149. self._lineJoin = None
  150. if kwds.pop('use_fp_str',False):
  151. self.fp_str = fp_str
  152. else:
  153. self.fp_str = py_fp_str
  154. self.cfp_str = lambda *args: self.fp_str(*args).replace(' ',',')
  155. implementation = getDOMImplementation('minidom')
  156. #Based on official example here http://www.w3.org/TR/SVG10/linking.html want:
  157. #<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
  158. # "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
  159. #Thus,
  160. #doctype = implementation.createDocumentType("svg",
  161. # "-//W3C//DTD SVG 20010904//EN",
  162. # "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd")
  163. #
  164. #However, putting that example through http://validator.w3.org/ recommends:
  165. #<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
  166. # "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
  167. #So we'll use that for our SVG 1.0 output.
  168. doctype = implementation.createDocumentType("svg",
  169. "-//W3C//DTD SVG 1.0//EN",
  170. "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd")
  171. self.doc = implementation.createDocument(None,"svg",doctype)
  172. self.svg = self.doc.documentElement
  173. svgAttrs = dict(
  174. width = str(size[0]),
  175. height=str(self.height),
  176. preserveAspectRatio="xMinYMin meet",
  177. viewBox="0 0 %d %d" % (self.width, self.height),
  178. #baseProfile = "full", #disliked in V 1.0
  179. #these suggested by Tim Roberts, as updated by peter@maubp.freeserve.co.uk
  180. xmlns="http://www.w3.org/2000/svg",
  181. version="1.0",
  182. )
  183. svgAttrs['fill-rule'] = _fillRuleMap[self._fillMode]
  184. svgAttrs["xmlns:xlink"] = "http://www.w3.org/1999/xlink"
  185. svgAttrs.update(kwds.pop('svgAttrs',{}))
  186. for k,v in svgAttrs.items():
  187. self.svg.setAttribute(k,v)
  188. title = self.doc.createElement('title')
  189. text = self.doc.createTextNode('...')
  190. title.appendChild(text)
  191. self.svg.appendChild(title)
  192. desc = self.doc.createElement('desc')
  193. text = self.doc.createTextNode('...')
  194. desc.appendChild(text)
  195. self.svg.appendChild(desc)
  196. self.setFont(STATE_DEFAULTS['fontName'], STATE_DEFAULTS['fontSize'])
  197. self.setStrokeColor(STATE_DEFAULTS['strokeColor'])
  198. self.setLineCap(2)
  199. self.setLineJoin(0)
  200. self.setLineWidth(1)
  201. if not useClip:
  202. # Add a rectangular clipping path identical to view area.
  203. clipPath = transformNode(self.doc, "clipPath", id="clip")
  204. clipRect = transformNode(self.doc, "rect", x=0, y=0,
  205. width=self.width, height=self.height)
  206. clipPath.appendChild(clipRect)
  207. self.svg.appendChild(clipPath)
  208. gtkw = dict(style="clip-path: url(#clip)")
  209. else:
  210. gtkw = dict(clip="0 0 %d %d" % (self.width,self.height))
  211. self.groupTree = transformNode(self.doc, "g",
  212. id="group",
  213. transform="scale(1,-1) translate(0,-%d)" % self.height,
  214. **gtkw
  215. )
  216. if scaleGroupId:
  217. self.scaleTree = transformNode(self.doc, "g", id=scaleGroupId, transform="scale(1,1)")
  218. self.scaleTree.appendChild(self.groupTree)
  219. self.svg.appendChild(self.scaleTree)
  220. else:
  221. self.svg.appendChild(self.groupTree)
  222. self.currGroup = self.groupTree
  223. def save(self, fn=None):
  224. writer = EncodedWriter(self.encoding,bom=self.bom)
  225. self.doc.writexml(writer,addindent="\t",newl="\n",encoding=self.encoding)
  226. if hasattr(fn,'write'):
  227. f = fn
  228. else:
  229. f = open(fn, 'w',encoding=self.encoding)
  230. svg = writer.getvalue()
  231. exd = self.extraXmlDecl
  232. if exd:
  233. svg = svg.replace('?>','?>'+exd)
  234. f.write(svg)
  235. if f is not fn:
  236. f.close()
  237. ### helpers ###
  238. def NOTUSED_stringWidth(self, s, font=None, fontSize=None):
  239. """Return the logical width of the string if it were drawn
  240. in the current font (defaults to self.font).
  241. """
  242. font = font or self._font
  243. fontSize = fontSize or self._fontSize
  244. return stringWidth(s, font, fontSize)
  245. def _formatStyle(self, include=[], exclude='',**kwds):
  246. style = self.style.copy()
  247. style.update(kwds)
  248. keys = list(style.keys())
  249. if include:
  250. keys = [k for k in keys if k in include]
  251. if exclude:
  252. exclude = exclude.split()
  253. items = [k+': '+str(style[k]) for k in keys if k not in exclude]
  254. else:
  255. items = [k+': '+str(style[k]) for k in keys]
  256. return '; '.join(items) + ';'
  257. def _escape(self, s):
  258. '''I don't think this was ever needed; seems to have been copied from renderPS'''
  259. return s
  260. def _genArcCode(self, x1, y1, x2, y2, startAng, extent):
  261. """Calculate the path for an arc inscribed in rectangle defined
  262. by (x1,y1),(x2,y2)."""
  263. return
  264. #calculate semi-minor and semi-major axes of ellipse
  265. xScale = abs((x2-x1)/2.0)
  266. yScale = abs((y2-y1)/2.0)
  267. #calculate centre of ellipse
  268. x, y = (x1+x2)/2.0, (y1+y2)/2.0
  269. codeline = 'matrix currentmatrix %s %s translate %s %s scale 0 0 1 %s %s %s setmatrix'
  270. if extent >= 0:
  271. arc='arc'
  272. else:
  273. arc='arcn'
  274. data = (x,y, xScale, yScale, startAng, startAng+extent, arc)
  275. return codeline % data
  276. def _fillAndStroke(self, code, clip=0, link_info=None,styles=AREA_STYLES,fillMode=None):
  277. xtra = {}
  278. if fillMode:
  279. xtra['fill-rule'] = _fillRuleMap[fillMode]
  280. path = transformNode(self.doc, "path",
  281. d=self.path, style=self._formatStyle(styles),
  282. )
  283. if link_info :
  284. path = self._add_link(path, link_info)
  285. self.currGroup.appendChild(path)
  286. self.path = ''
  287. ### styles ###
  288. def setLineCap(self, v):
  289. vals = {0:'butt', 1:'round', 2:'square'}
  290. if self._lineCap != v:
  291. self._lineCap = v
  292. self.style['stroke-linecap'] = vals[v]
  293. def setLineJoin(self, v):
  294. vals = {0:'miter', 1:'round', 2:'bevel'}
  295. if self._lineJoin != v:
  296. self._lineJoin = v
  297. self.style['stroke-linecap'] = vals[v]
  298. def setDash(self, array=[], phase=0):
  299. """Two notations. Pass two numbers, or an array and phase."""
  300. if isinstance(array,(float,int)):
  301. self.style['stroke-dasharray'] = ', '.join(map(str, ([array, phase])))
  302. elif isinstance(array,(tuple,list)) and len(array) > 0:
  303. assert phase >= 0, "phase is a length in user space"
  304. self.style['stroke-dasharray'] = ', '.join(map(str, array))
  305. if phase>0:
  306. self.style['stroke-dashoffset'] = str(phase)
  307. def setStrokeColor(self, color):
  308. self._strokeColor = color
  309. if color == None:
  310. self.style['stroke'] = 'none'
  311. else:
  312. r, g, b = color.red, color.green, color.blue
  313. self.style['stroke'] = 'rgb(%d%%,%d%%,%d%%)' % (r*100, g*100, b*100)
  314. alpha = color.normalizedAlpha
  315. if alpha!=1:
  316. self.style['stroke-opacity'] = '%s' % alpha
  317. elif 'stroke-opacity' in self.style:
  318. del self.style['stroke-opacity']
  319. def setFillColor(self, color):
  320. self._fillColor = color
  321. if color == None:
  322. self.style['fill'] = 'none'
  323. else:
  324. r, g, b = color.red, color.green, color.blue
  325. self.style['fill'] = 'rgb(%d%%,%d%%,%d%%)' % (r*100, g*100, b*100)
  326. alpha = color.normalizedAlpha
  327. if alpha!=1:
  328. self.style['fill-opacity'] = '%s' % alpha
  329. elif 'fill-opacity' in self.style:
  330. del self.style['fill-opacity']
  331. def setFillMode(self, v):
  332. self._fillMode = v
  333. self.style['fill-rule'] = _fillRuleMap[v]
  334. def setLineWidth(self, width):
  335. if width != self._lineWidth:
  336. self._lineWidth = width
  337. self.style['stroke-width'] = width
  338. def setFont(self, font, fontSize):
  339. if self._font != font or self._fontSize != fontSize:
  340. self._font = font
  341. self._fontSize = fontSize
  342. style = self.style
  343. for k in TEXT_STYLES:
  344. if k in style:
  345. del style[k]
  346. svgAttrs = self.fontHacks[font] if font in self.fontHacks else {}
  347. if isinstance(font,RLString):
  348. svgAttrs.update(iter(font.svgAttrs.items()))
  349. if svgAttrs:
  350. for k,v in svgAttrs.items():
  351. a = 'font-'+k
  352. if a in TEXT_STYLES:
  353. style[a] = v
  354. if 'font-family' not in style:
  355. style['font-family'] = font
  356. style['font-size'] = '%spx' % fontSize
  357. def _add_link(self, dom_object, link_info) :
  358. assert isinstance(link_info, dict)
  359. link = transformNode(self.doc, "a", **link_info)
  360. link.appendChild(dom_object)
  361. return link
  362. ### shapes ###
  363. def rect(self, x1,y1, x2,y2, rx=8, ry=8, link_info=None, **_svgAttrs):
  364. "Draw a rectangle between x1,y1 and x2,y2."
  365. if self.verbose: print("+++ SVGCanvas.rect")
  366. x = min(x1,x2)
  367. y = min(y1,y2)
  368. kwds = {}
  369. rect = transformNode(self.doc, "rect",
  370. x=x, y=y, width=max(x1,x2)-x, height=max(y1,y2)-y,
  371. style=self._formatStyle(AREA_STYLES),**_svgAttrs)
  372. if link_info :
  373. rect = self._add_link(rect, link_info)
  374. self.currGroup.appendChild(rect)
  375. def roundRect(self, x1,y1, x2,y2, rx=8, ry=8, link_info=None, **_svgAttrs):
  376. """Draw a rounded rectangle between x1,y1 and x2,y2.
  377. Corners inset as ellipses with x-radius rx and y-radius ry.
  378. These should have x1<x2, y1<y2, rx>0, and ry>0.
  379. """
  380. rect = transformNode(self.doc, "rect",
  381. x=x1, y=y1, width=x2-x1, height=y2-y1, rx=rx, ry=ry,
  382. style=self._formatStyle(AREA_STYLES), **_svgAttrs)
  383. if link_info:
  384. rect = self._add_link(rect, link_info)
  385. self.currGroup.appendChild(rect)
  386. def drawString(self, s, x, y, angle=0, link_info=None, text_anchor='left', textRenderMode=0, **_svgAttrs):
  387. if textRenderMode==3: return #invisible
  388. s = asNative(s)
  389. if self.verbose: print("+++ SVGCanvas.drawString")
  390. needFill = textRenderMode==0 or textRenderMode==2 or textRenderMode==4 or textRenderMode==6
  391. needStroke = textRenderMode==1 or textRenderMode==2 or textRenderMode==5 or textRenderMode==6
  392. if (self._fillColor!=None and needFill) or (self._strokeColor!=None and needStroke):
  393. if not text_anchor in ['start', 'inherited', 'left']:
  394. textLen = stringWidth(s,self._font,self._fontSize)
  395. if text_anchor=='end':
  396. x -= textLen
  397. elif text_anchor=='middle':
  398. x -= textLen/2.
  399. elif text_anchor=='numeric':
  400. x -= numericXShift(text_anchor,s,textLen,self._font,self._fontSize)
  401. else:
  402. raise ValueError('bad value for text_anchor ' + str(text_anchor))
  403. s = self._escape(s)
  404. st = self._formatStyle(TEXT_STYLES)
  405. if angle != 0:
  406. st = st + " rotate(%s);" % self.fp_str(angle, x, y)
  407. if needFill:
  408. st += self._formatStyle(EXTRA_FILL_STYLES)
  409. else:
  410. st += " fill:none;"
  411. if needStroke:
  412. st += self._formatStyle(EXTRA_STROKE_STYLES)
  413. else:
  414. st += " stroke:none;"
  415. #if textRenderMode>=4:
  416. # _gstate_clipPathSetOrAddself, -1, 1, 0 /*we are adding*/
  417. text = transformNode(self.doc, "text",
  418. x=x, y=y, style=st,
  419. transform="translate(0,%d) scale(1,-1)" % (2*y),
  420. **_svgAttrs
  421. )
  422. content = self.doc.createTextNode(s)
  423. text.appendChild(content)
  424. if link_info:
  425. text = self._add_link(text, link_info)
  426. self.currGroup.appendChild(text)
  427. def drawCentredString(self, s, x, y, angle=0, text_anchor='middle',
  428. link_info=None, textRenderMode=0, **_svgAttrs):
  429. if self.verbose: print("+++ SVGCanvas.drawCentredString")
  430. self.drawString(s,x,y,angle=angle, link_info=link_info, text_anchor=text_anchor,
  431. textRenderMode=textRenderMode, **_svgAttrs)
  432. def drawRightString(self, text, x, y, angle=0,text_anchor='end',
  433. link_info=None, textRenderMode=0, **_svgAttrs):
  434. if self.verbose: print("+++ SVGCanvas.drawRightString")
  435. self.drawString(text,x,y,angle=angle, link_info=link_info, text_anchor=text_anchor,
  436. textRenderMode=textRenderMode, **_svgAttrs)
  437. def comment(self, data):
  438. "Add a comment."
  439. comment = self.doc.createComment(data)
  440. # self.currGroup.appendChild(comment)
  441. def drawImage(self, image, x, y, width, height, embed=True):
  442. buf = getBytesIO()
  443. image.save(buf,'png')
  444. buf = asNative(base64.b64encode(buf.getvalue()))
  445. self.currGroup.appendChild(
  446. transformNode(self.doc,'image',
  447. x=x,y=y,width=width,height=height,
  448. href="data:image/png;base64,"+buf,
  449. transform="matrix(%s)" % self.cfp_str(1,0,0,-1,0,height+2*y),
  450. )
  451. )
  452. def line(self, x1, y1, x2, y2):
  453. if self._strokeColor != None:
  454. if 0: # something is wrong with line in my SVG viewer...
  455. line = transformNode(self.doc, "line",
  456. x=x1, y=y1, x2=x2, y2=y2,
  457. style=self._formatStyle(LINE_STYLES))
  458. self.currGroup.appendChild(line)
  459. path = transformNode(self.doc, "path",
  460. d="M %s L %s Z" % (self.cfp_str(x1,y1),self.cfp_str(x2,y2)),
  461. style=self._formatStyle(LINE_STYLES))
  462. self.currGroup.appendChild(path)
  463. def ellipse(self, x1, y1, x2, y2, link_info=None):
  464. """Draw an orthogonal ellipse inscribed within the rectangle x1,y1,x2,y2.
  465. These should have x1<x2 and y1<y2.
  466. """
  467. ellipse = transformNode(self.doc, "ellipse",
  468. cx=(x1+x2)/2.0, cy=(y1+y2)/2.0, rx=(x2-x1)/2.0, ry=(y2-y1)/2.0,
  469. style=self._formatStyle(AREA_STYLES))
  470. if link_info:
  471. ellipse = self._add_link(ellipse, link_info)
  472. self.currGroup.appendChild(ellipse)
  473. def circle(self, xc, yc, r, link_info=None):
  474. circle = transformNode(self.doc, "circle",
  475. cx=xc, cy=yc, r=r,
  476. style=self._formatStyle(AREA_STYLES))
  477. if link_info:
  478. circle = self._add_link(circle, link_info)
  479. self.currGroup.appendChild(circle)
  480. def drawCurve(self, x1, y1, x2, y2, x3, y3, x4, y4, closed=0):
  481. pass
  482. return
  483. codeline = '%s m %s curveto'
  484. data = (fp_str(x1, y1), fp_str(x2, y2, x3, y3, x4, y4))
  485. if self._fillColor != None:
  486. self.code.append((codeline % data) + ' eofill')
  487. if self._strokeColor != None:
  488. self.code.append((codeline % data)
  489. + ((closed and ' closepath') or '')
  490. + ' stroke')
  491. def drawArc(self, x1,y1, x2,y2, startAng=0, extent=360, fromcenter=0):
  492. """Draw a partial ellipse inscribed within the rectangle x1,y1,x2,y2.
  493. Starting at startAng degrees and covering extent degrees. Angles
  494. start with 0 to the right (+x) and increase counter-clockwise.
  495. These should have x1<x2 and y1<y2.
  496. """
  497. cx, cy = (x1+x2)/2.0, (y1+y2)/2.0
  498. rx, ry = (x2-x1)/2.0, (y2-y1)/2.0
  499. mx = rx * cos(startAng*pi/180) + cx
  500. my = ry * sin(startAng*pi/180) + cy
  501. ax = rx * cos((startAng+extent)*pi/180) + cx
  502. ay = ry * sin((startAng+extent)*pi/180) + cy
  503. cfp_str = self.cfp_str
  504. s = [].append
  505. if fromcenter:
  506. s("M %s L %s" % (cfp_str(cx, cy), cfp_str(ax, ay)))
  507. if fromcenter:
  508. s("A %s %d %d %d %s" % \
  509. (cfp_str(rx, ry), 0, extent>=180, 0, cfp_str(mx, my)))
  510. else:
  511. s("M %s A %s %d %d %d %s Z" % \
  512. (cfp_str(mx, my), cfp_str(rx, ry), 0, extent>=180, 0, cfp_str(mx, my)))
  513. if fromcenter:
  514. s("L %s Z" % cfp_str(cx, cy))
  515. path = transformNode(self.doc, "path",
  516. d=' '.join(s.__self__), style=self._formatStyle())
  517. self.currGroup.appendChild(path)
  518. def polygon(self, points, closed=0, link_info=None):
  519. assert len(points) >= 2, 'Polygon must have 2 or more points'
  520. if self._strokeColor!=None or self._fillColor!=None:
  521. pts = ', '.join([fp_str(*p) for p in points])
  522. polyline = transformNode(self.doc, "polygon",
  523. points=pts, style=self._formatStyle(AREA_STYLES))
  524. if link_info:
  525. polyline = self._add_link(polyline, link_info)
  526. self.currGroup.appendChild(polyline)
  527. # self._fillAndStroke(polyCode)
  528. def lines(self, lineList, color=None, width=None):
  529. # print "### lineList", lineList
  530. return
  531. if self._strokeColor != None:
  532. codeline = '%s m %s l stroke'
  533. for line in lineList:
  534. self.code.append(codeline % (fp_str(line[0]), fp_str(line[1])))
  535. def polyLine(self, points):
  536. assert len(points) >= 1, 'Polyline must have 1 or more points'
  537. if self._strokeColor != None:
  538. pts = ', '.join([fp_str(*p) for p in points])
  539. polyline = transformNode(self.doc, "polyline",
  540. points=pts, style=self._formatStyle(AREA_STYLES,fill=None))
  541. self.currGroup.appendChild(polyline)
  542. ### groups ###
  543. def startGroup(self,attrDict=dict(transform="")):
  544. if self.verbose: print("+++ begin SVGCanvas.startGroup")
  545. currGroup = self.currGroup
  546. group = transformNode(self.doc, "g", **attrDict)
  547. currGroup.appendChild(group)
  548. self.currGroup = group
  549. if self.verbose: print("+++ end SVGCanvas.startGroup")
  550. return currGroup
  551. def endGroup(self,currGroup):
  552. if self.verbose: print("+++ begin SVGCanvas.endGroup")
  553. self.currGroup = currGroup
  554. if self.verbose: print("+++ end SVGCanvas.endGroup")
  555. def transform(self, a, b, c, d, e, f):
  556. if self.verbose: print("!!! begin SVGCanvas.transform", a, b, c, d, e, f)
  557. tr = self.currGroup.getAttribute("transform")
  558. if (a, b, c, d, e, f) != (1, 0, 0, 1, 0, 0):
  559. t = 'matrix(%s)' % self.cfp_str(a,b,c,d,e,f)
  560. self.currGroup.setAttribute("transform", "%s %s" % (tr, t))
  561. def translate(self, x, y):
  562. if (x,y) != (0,0):
  563. self.currGroup.setAttribute("transform", "%s %s"
  564. % (self.currGroup.getAttribute("transform"),
  565. 'translate(%s)' % self.cfp_str(x,y)))
  566. def scale(self, sx, sy):
  567. if (sx,sy) != (1,1):
  568. self.currGroup.setAttribute("transform", "%s %s"
  569. % (self.groups[-1].getAttribute("transform"),
  570. 'scale(%s)' % self.cfp_str(sx, sy)))
  571. ### paths ###
  572. def moveTo(self, x, y):
  573. self.path = self.path + 'M %s ' % self.fp_str(x, y)
  574. def lineTo(self, x, y):
  575. self.path = self.path + 'L %s ' % self.fp_str(x, y)
  576. def curveTo(self, x1, y1, x2, y2, x3, y3):
  577. self.path = self.path + 'C %s ' % self.fp_str(x1, y1, x2, y2, x3, y3)
  578. def closePath(self):
  579. self.path = self.path + 'Z '
  580. def saveState(self):
  581. pass
  582. def restoreState(self):
  583. pass
  584. class _SVGRenderer(Renderer):
  585. """This draws onto an SVG document.
  586. """
  587. def __init__(self):
  588. self.verbose = 0
  589. def drawNode(self, node):
  590. """This is the recursive method called for each node in the tree.
  591. """
  592. if self.verbose: print("### begin _SVGRenderer.drawNode(%r)" % node)
  593. self._canvas.comment('begin node %r'%node)
  594. style = self._canvas.style.copy()
  595. if not (isinstance(node, Path) and node.isClipPath):
  596. pass # self._canvas.saveState()
  597. #apply state changes
  598. deltas = getStateDelta(node)
  599. self._tracker.push(deltas)
  600. self.applyStateChanges(deltas, {})
  601. #draw the object, or recurse
  602. self.drawNodeDispatcher(node)
  603. rDeltas = self._tracker.pop()
  604. if not (isinstance(node, Path) and node.isClipPath):
  605. pass #self._canvas.restoreState()
  606. self._canvas.comment('end node %r'%node)
  607. #restore things we might have lost (without actually doing anything).
  608. for k, v in rDeltas.items():
  609. if k in self._restores:
  610. setattr(self._canvas,self._restores[k],v)
  611. self._canvas.style = style
  612. if self.verbose: print("### end _SVGRenderer.drawNode(%r)" % node)
  613. _restores = {'strokeColor':'_strokeColor','strokeWidth': '_lineWidth','strokeLineCap':'_lineCap',
  614. 'strokeLineJoin':'_lineJoin','fillColor':'_fillColor','fontName':'_font',
  615. 'fontSize':'_fontSize'}
  616. def _get_link_info_dict(self, obj):
  617. #We do not want None or False as the link, even if it is the
  618. #attribute's value - use the empty string instead.
  619. url = getattr(obj, "hrefURL", "") or ""
  620. title = getattr(obj, "hrefTitle", "") or ""
  621. if url :
  622. #Is it valid to have a link with no href? The XML requires
  623. #the xlink:href to be present, but you might just want a
  624. #tool tip shown (via the xlink:title attribute). Note that
  625. #giving an href of "" is equivalent to "the current page"
  626. #(a relative link saying go nowhere).
  627. return {"xlink:href":url, "xlink:title":title, "target":"_top"}
  628. #Currently of all the mainstream browsers I have tested, only Safari/webkit
  629. #will show SVG images embedded in HTML using a simple <img src="..." /> tag.
  630. #However, the links don't work (Safari 3.2.1 on the Mac).
  631. #
  632. #Therefore I use the following, which also works for Firefox, Opera, and
  633. #IE 6.0 with Adobe SVG Viewer 6 beta:
  634. #<object data="..." type="image/svg+xml" width="430" height="150" class="img">
  635. #
  636. #Once displayed, Firefox and Safari treat the SVG like a frame, and
  637. #by default clicking on links acts "in frame" and replaces the image.
  638. #Opera does what I expect, and replaces the whole page with the link.
  639. #
  640. #Therefore I use target="_top" to force the links to replace the whole page.
  641. #This now works as expected on Safari 3.2.1, Firefox 3.0.6, Opera 9.20.
  642. #Perhaps the target attribute should be an option, perhaps defaulting to
  643. #"_top" as used here?
  644. else :
  645. return None
  646. def drawGroup(self, group):
  647. if self.verbose: print("### begin _SVGRenderer.drawGroup")
  648. currGroup = self._canvas.startGroup()
  649. a, b, c, d, e, f = self._tracker.getState()['transform']
  650. for childNode in group.getContents():
  651. if isinstance(childNode, UserNode):
  652. node2 = childNode.provideNode()
  653. else:
  654. node2 = childNode
  655. self.drawNode(node2)
  656. self._canvas.transform(a, b, c, d, e, f)
  657. self._canvas.endGroup(currGroup)
  658. if self.verbose: print("### end _SVGRenderer.drawGroup")
  659. def drawRect(self, rect):
  660. link_info = self._get_link_info_dict(rect)
  661. svgAttrs = getattr(rect,'_svgAttrs',{})
  662. if rect.rx == rect.ry == 0:
  663. #plain old rectangle
  664. self._canvas.rect(
  665. rect.x, rect.y,
  666. rect.x+rect.width, rect.y+rect.height, link_info=link_info, **svgAttrs)
  667. else:
  668. #cheat and assume ry = rx; better to generalize
  669. #pdfgen roundRect function. TODO
  670. self._canvas.roundRect(
  671. rect.x, rect.y,
  672. rect.x+rect.width, rect.y+rect.height,
  673. rect.rx, rect.ry,
  674. link_info=link_info, **svgAttrs)
  675. def drawString(self, stringObj):
  676. S = self._tracker.getState()
  677. text_anchor, x, y, text = S['textAnchor'], stringObj.x, stringObj.y, stringObj.text
  678. self._canvas.drawString(text,x,y,link_info=self._get_link_info_dict(stringObj),
  679. text_anchor=text_anchor, textRenderMode=getattr(stringObj,'textRenderMode',0),
  680. **getattr(stringObj,'_svgAttrs',{}))
  681. def drawLine(self, line):
  682. if self._canvas._strokeColor:
  683. self._canvas.line(line.x1, line.y1, line.x2, line.y2)
  684. def drawCircle(self, circle):
  685. self._canvas.circle( circle.cx, circle.cy, circle.r, link_info=self._get_link_info_dict(circle))
  686. def drawWedge(self, wedge):
  687. yradius, radius1, yradius1 = wedge._xtraRadii()
  688. if (radius1==0 or radius1 is None) and (yradius1==0 or yradius1 is None) and not wedge.annular:
  689. centerx, centery, radius, startangledegrees, endangledegrees = \
  690. wedge.centerx, wedge.centery, wedge.radius, wedge.startangledegrees, wedge.endangledegrees
  691. yradius = wedge.yradius or wedge.radius
  692. (x1, y1) = (centerx-radius, centery-yradius)
  693. (x2, y2) = (centerx+radius, centery+yradius)
  694. extent = endangledegrees - startangledegrees
  695. self._canvas.drawArc(x1, y1, x2, y2, startangledegrees, extent, fromcenter=1)
  696. else:
  697. P = wedge.asPolygon()
  698. if isinstance(P,Path):
  699. self.drawPath(P)
  700. else:
  701. self.drawPolygon(P)
  702. def drawPolyLine(self, p):
  703. if self._canvas._strokeColor:
  704. self._canvas.polyLine(_pointsFromList(p.points))
  705. def drawEllipse(self, ellipse):
  706. #need to convert to pdfgen's bounding box representation
  707. x1 = ellipse.cx - ellipse.rx
  708. x2 = ellipse.cx + ellipse.rx
  709. y1 = ellipse.cy - ellipse.ry
  710. y2 = ellipse.cy + ellipse.ry
  711. self._canvas.ellipse(x1,y1,x2,y2, link_info=self._get_link_info_dict(ellipse))
  712. def drawPolygon(self, p):
  713. self._canvas.polygon(_pointsFromList(p.points), closed=1, link_info=self._get_link_info_dict(p))
  714. def drawPath(self, path, fillMode=FILL_EVEN_ODD):
  715. # print "### drawPath", path.points
  716. from reportlab.graphics.shapes import _renderPath
  717. c = self._canvas
  718. drawFuncs = (c.moveTo, c.lineTo, c.curveTo, c.closePath)
  719. if fillMode is None:
  720. fillMode = getattr(path,'fillMode',FILL_EVEN_ODD)
  721. link_info = self._get_link_info_dict(path)
  722. autoclose = getattr(path,'autoclose','')
  723. def rP(**kwds):
  724. return _renderPath(path, drawFuncs, **kwds)
  725. if autoclose=='svg':
  726. rP()
  727. c._fillAndStroke([], clip=path.isClipPath, link_info=link_info, fillMode=fillMode)
  728. elif autoclose=='pdf':
  729. rP(forceClose=True)
  730. c._fillAndStroke([], clip=path.isClipPath, link_info=link_info, fillMode=fillMode)
  731. else:
  732. isClosed = rP()
  733. if not isClosed:
  734. ofc = c._fillColor
  735. c.setFillColor(None)
  736. try:
  737. link_info = None
  738. c._fillAndStroke([], clip=path.isClipPath, link_info=link_info, fillMode=fillMode)
  739. finally:
  740. c.setFillColor(ofc)
  741. else:
  742. c._fillAndStroke([], clip=path.isClipPath, link_info=link_info, fillMode=fillMode)
  743. def drawImage(self, image):
  744. path = image.path
  745. if isinstance(path,str):
  746. if not (path and os.path.isfile(path)): return
  747. im = _getImage().open(path)
  748. elif hasattr(path,'convert'):
  749. im = path
  750. else:
  751. return
  752. srcW, srcH = im.size
  753. dstW, dstH = image.width, image.height
  754. if dstW is None: dstW = srcW
  755. if dstH is None: dstH = srcH
  756. self._canvas.drawImage(im, image.x, image.y, dstW, dstH, embed=True)
  757. def applyStateChanges(self, delta, newState):
  758. """This takes a set of states, and outputs the operators
  759. needed to set those properties"""
  760. for key, value in delta.items():
  761. if key == 'transform':
  762. pass
  763. #self._canvas.transform(value[0], value[1], value[2], value[3], value[4], value[5])
  764. elif key == 'strokeColor':
  765. self._canvas.setStrokeColor(value)
  766. elif key == 'strokeWidth':
  767. self._canvas.setLineWidth(value)
  768. elif key == 'strokeLineCap': #0,1,2
  769. self._canvas.setLineCap(value)
  770. elif key == 'strokeLineJoin':
  771. self._canvas.setLineJoin(value)
  772. elif key == 'strokeDashArray':
  773. if value:
  774. if isinstance(value,(list,tuple)) and len(value)==2 and isinstance(value[1],(tuple,list)):
  775. phase = value[0]
  776. value = value[1]
  777. else:
  778. phase = 0
  779. self._canvas.setDash(value,phase)
  780. else:
  781. self._canvas.setDash()
  782. elif key == 'fillColor':
  783. self._canvas.setFillColor(value)
  784. elif key in ['fontSize', 'fontName']:
  785. fontname = delta.get('fontName', self._canvas._font)
  786. fontsize = delta.get('fontSize', self._canvas._fontSize)
  787. self._canvas.setFont(fontname, fontsize)
  788. elif key == 'fillMode':
  789. self._canvas.setFillMode(value)
  790. def test(outDir='out-svg'):
  791. # print all drawings and their doc strings from the test
  792. # file
  793. if not os.path.isdir(outDir):
  794. os.mkdir(outDir)
  795. #grab all drawings from the test module
  796. from reportlab.graphics import testshapes
  797. drawings = []
  798. for funcname in dir(testshapes):
  799. if funcname[0:10] == 'getDrawing':
  800. func = getattr(testshapes,funcname)
  801. drawing = func()
  802. docstring = getattr(func,'__doc__','')
  803. drawings.append((drawing, docstring))
  804. i = 0
  805. for (d, docstring) in drawings:
  806. filename = os.path.join(outDir,'renderSVG_%d.svg' % i)
  807. drawToFile(d, filename)
  808. i += 1
  809. from reportlab.graphics.testshapes import getDrawing01
  810. d = getDrawing01()
  811. drawToFile(d, os.path.join(outDir,"test.svg"))
  812. from reportlab.lib.corp import RL_CorpLogo
  813. from reportlab.graphics.shapes import Drawing
  814. rl = RL_CorpLogo()
  815. d = Drawing(rl.width,rl.height)
  816. d.add(rl)
  817. drawToFile(d, os.path.join(outDir,"corplogo.svg"))
  818. if __name__=='__main__':
  819. test()