testshapes.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. #!/bin/env python
  2. #Copyright ReportLab Europe Ltd. 2000-2017
  3. #see license.txt for license details
  4. #history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/testshapes.py
  5. # testshapes.py - draws shapes onto a PDF canvas.
  6. __version__ = ''' $Id $ '''
  7. __doc__='''Execute this script to see some test drawings.
  8. This contains a number of routines to generate test drawings
  9. for reportlab/graphics. For now many of them are contrived,
  10. but we will expand them to try and trip up any parser.
  11. Feel free to add more.
  12. '''
  13. import os, sys, base64
  14. from reportlab.lib import colors
  15. from reportlab.lib.units import cm
  16. from reportlab.lib.utils import asNative, base64_decodebytes
  17. from reportlab.pdfgen.canvas import Canvas
  18. from reportlab.pdfbase.pdfmetrics import stringWidth
  19. from reportlab.platypus import Flowable
  20. from reportlab.graphics.shapes import *
  21. from reportlab.graphics.renderPDF import _PDFRenderer
  22. import unittest
  23. _FONTS = ['Times-Roman','Vera','Times-BoldItalic',]
  24. def _setup():
  25. from reportlab.pdfbase import pdfmetrics, ttfonts
  26. pdfmetrics.registerFont(ttfonts.TTFont("Vera", "Vera.ttf"))
  27. pdfmetrics.registerFont(ttfonts.TTFont("VeraBd", "VeraBd.ttf"))
  28. pdfmetrics.registerFont(ttfonts.TTFont("VeraIt", "VeraIt.ttf"))
  29. pdfmetrics.registerFont(ttfonts.TTFont("VeraBI", "VeraBI.ttf"))
  30. F = ['Times-Roman','Courier','Helvetica','Vera', 'VeraBd', 'VeraIt', 'VeraBI']
  31. if sys.platform=='win32':
  32. for name, ttf in [
  33. ('Adventurer Light SF','Advlit.ttf'),('ArialMS','ARIAL.TTF'),
  34. ('Arial Unicode MS', 'ARIALUNI.TTF'),
  35. ('Book Antiqua','BKANT.TTF'),
  36. ('Century Gothic','GOTHIC.TTF'),
  37. ('Comic Sans MS', 'COMIC.TTF'),
  38. ('Elementary Heavy SF Bold','Vwagh.ttf'),
  39. ('Firenze SF','flot.ttf'),
  40. ('Garamond','GARA.TTF'),
  41. ('Jagger','Rols.ttf'),
  42. ('Monotype Corsiva','MTCORSVA.TTF'),
  43. ('Seabird SF','seag.ttf'),
  44. ('Tahoma','TAHOMA.TTF'),
  45. ('VerdanaMS','VERDANA.TTF'),
  46. ]:
  47. for D in (r'c:\WINNT',r'c:\Windows'):
  48. fn = os.path.join(D,'Fonts',ttf)
  49. if os.path.isfile(fn):
  50. try:
  51. f = ttfonts.TTFont(name, fn)
  52. pdfmetrics.registerFont(f)
  53. F.append(name)
  54. except:
  55. pass
  56. return F
  57. def resetFonts():
  58. for f in _setup():
  59. if f not in _FONTS:
  60. _FONTS.append(f)
  61. from reportlab.rl_config import register_reset
  62. register_reset(resetFonts)
  63. resetFonts()
  64. #########################################################
  65. #
  66. # Collections of shape drawings.
  67. #
  68. #########################################################
  69. def getFailedDrawing(funcName):
  70. """Generate a drawing in case something goes really wrong.
  71. This will create a drawing to be displayed whenever some
  72. other drawing could not be executed, because the generating
  73. function does something terribly wrong! The box contains
  74. an attention triangle, plus some error message.
  75. """
  76. D = Drawing(400, 200)
  77. points = [200,170, 140,80, 260,80]
  78. D.add(Polygon(points,
  79. strokeWidth=0.5*cm,
  80. strokeColor=colors.red,
  81. fillColor=colors.yellow))
  82. s = String(200, 40,
  83. "Error in generating function '%s'!" % funcName,
  84. textAnchor='middle')
  85. D.add(s)
  86. return D
  87. # These are the real drawings to be eye-balled.
  88. def getDrawing01():
  89. """Hello World, on a rectangular background.
  90. The rectangle's fillColor is yellow.
  91. The string's fillColor is red.
  92. """
  93. D = Drawing(400, 200)
  94. D.add(Rect(50, 50, 300, 100, fillColor=colors.yellow))
  95. D.add(String(180,100, 'Hello World', fillColor=colors.red))
  96. D.add(String(180,86, b'Special characters \xc2\xa2\xc2\xa9\xc2\xae\xc2\xa3\xce\xb1\xce\xb2', fillColor=colors.red))
  97. return D
  98. def getDrawing02():
  99. """Various Line shapes.
  100. The lines are blue and their strokeWidth is 5 mm.
  101. One line has a strokeDashArray set to [5, 10, 15].
  102. """
  103. D = Drawing(400, 200)
  104. D.add(Line(50,50, 300,100,
  105. strokeColor=colors.blue,
  106. strokeWidth=0.5*cm,
  107. ))
  108. D.add(Line(50,100, 300,50,
  109. strokeColor=colors.blue,
  110. strokeWidth=0.5*cm,
  111. strokeDashArray=[5, 10, 15],
  112. ))
  113. #x = 1/0 # Comment this to see the actual drawing!
  114. return D
  115. def getDrawing03():
  116. """Text strings in various sizes and different fonts.
  117. Font size increases from 12 to 36 and from bottom left
  118. to upper right corner. The first ones should be in
  119. Times-Roman. Finally, a solitary Courier string at
  120. the top right corner.
  121. """
  122. D = Drawing(400, 200)
  123. for size in range(12, 36, 4):
  124. D.add(String(10+size*2,
  125. 10+size*2,
  126. 'Hello World',
  127. fontName=_FONTS[0],
  128. fontSize=size))
  129. D.add(String(150, 150,
  130. 'Hello World',
  131. fontName=_FONTS[1],
  132. fontSize=36))
  133. return D
  134. def getDrawing04():
  135. """Text strings in various colours.
  136. Colours are blue, yellow and red from bottom left
  137. to upper right.
  138. """
  139. D = Drawing(400, 200)
  140. i = 0
  141. for color in (colors.blue, colors.yellow, colors.red):
  142. D.add(String(50+i*30, 50+i*30,
  143. 'Hello World', fillColor=color))
  144. i = i + 1
  145. return D
  146. def getDrawing05():
  147. """Text strings with various anchors (alignments).
  148. Text alignment conforms to the anchors in the left column.
  149. """
  150. D = Drawing(400, 200)
  151. lineX = 250
  152. D.add(Line(lineX,10, lineX,190, strokeColor=colors.gray))
  153. y = 130
  154. for anchor in ('start', 'middle', 'end'):
  155. D.add(String(lineX, y, 'Hello World', textAnchor=anchor))
  156. D.add(String(50, y, anchor + ':'))
  157. y = y - 30
  158. return D
  159. def getDrawing06():
  160. """This demonstrates all the basic shapes at once.
  161. There are no groups or references.
  162. Each solid shape should have a green fill.
  163. """
  164. green = colors.green
  165. D = Drawing(400, 200) #, fillColor=green)
  166. D.add(Line(10,10, 390,190))
  167. D.add(Circle(100,100,20, fillColor=green))
  168. D.add(Circle(200,100,40, fillColor=green))
  169. D.add(Circle(300,100,30, fillColor=green))
  170. D.add(Wedge(330,100,40, -10,40, fillColor=green))
  171. D.add(PolyLine([120,10, 130,20, 140,10, 150,20, 160,10,
  172. 170,20, 180,10, 190,20, 200,10], fillColor=green))
  173. D.add(Polygon([300,20, 350,20, 390,80, 300,75, 330,40], fillColor=green))
  174. D.add(Ellipse(50,150, 40, 20, fillColor=green))
  175. D.add(Rect(120,150, 60,30,
  176. strokeWidth=10,
  177. strokeColor=colors.yellow,
  178. fillColor=green)) #square corners
  179. D.add(Rect(220, 150, 60, 30, 10, 10, fillColor=green)) #round corners
  180. D.add(String(10,50, 'Basic Shapes', fillColor=colors.black, fontName='Helvetica'))
  181. return D
  182. def getDrawing07():
  183. """This tests the ability to translate and rotate groups. The first set of axes should be
  184. near the bottom left of the drawing. The second should be rotated counterclockwise
  185. by 15 degrees. The third should be rotated by 30 degrees."""
  186. D = Drawing(400, 200)
  187. Axis = Group(
  188. Line(0,0,100,0), #x axis
  189. Line(0,0,0,50), # y axis
  190. Line(0,10,10,10), #ticks on y axis
  191. Line(0,20,10,20),
  192. Line(0,30,10,30),
  193. Line(0,40,10,40),
  194. Line(10,0,10,10), #ticks on x axis
  195. Line(20,0,20,10),
  196. Line(30,0,30,10),
  197. Line(40,0,40,10),
  198. Line(50,0,50,10),
  199. Line(60,0,60,10),
  200. Line(70,0,70,10),
  201. Line(80,0,80,10),
  202. Line(90,0,90,10),
  203. String(20, 35, 'Axes', fill=colors.black)
  204. )
  205. firstAxisGroup = Group(Axis)
  206. firstAxisGroup.translate(10,10)
  207. D.add(firstAxisGroup)
  208. secondAxisGroup = Group(Axis)
  209. secondAxisGroup.translate(150,10)
  210. secondAxisGroup.rotate(15)
  211. D.add(secondAxisGroup)
  212. thirdAxisGroup = Group(Axis, transform=mmult(translate(300,10), rotate(30)))
  213. D.add(thirdAxisGroup)
  214. return D
  215. def getDrawing08():
  216. """This tests the ability to scale coordinates. The bottom left set of axes should be
  217. near the bottom left of the drawing. The bottom right should be stretched vertically
  218. by a factor of 2. The top left one should be stretched horizontally by a factor of 2.
  219. The top right should have the vertical axiss leaning over to the right by 30 degrees."""
  220. D = Drawing(400, 200)
  221. Axis = Group(
  222. Line(0,0,100,0), #x axis
  223. Line(0,0,0,50), # y axis
  224. Line(0,10,10,10), #ticks on y axis
  225. Line(0,20,10,20),
  226. Line(0,30,10,30),
  227. Line(0,40,10,40),
  228. Line(10,0,10,10), #ticks on x axis
  229. Line(20,0,20,10),
  230. Line(30,0,30,10),
  231. Line(40,0,40,10),
  232. Line(50,0,50,10),
  233. Line(60,0,60,10),
  234. Line(70,0,70,10),
  235. Line(80,0,80,10),
  236. Line(90,0,90,10),
  237. String(20, 35, 'Axes', fill=colors.black)
  238. )
  239. firstAxisGroup = Group(Axis)
  240. firstAxisGroup.translate(10,10)
  241. D.add(firstAxisGroup)
  242. secondAxisGroup = Group(Axis)
  243. secondAxisGroup.translate(150,10)
  244. secondAxisGroup.scale(1,2)
  245. D.add(secondAxisGroup)
  246. thirdAxisGroup = Group(Axis)
  247. thirdAxisGroup.translate(10,125)
  248. thirdAxisGroup.scale(2,1)
  249. D.add(thirdAxisGroup)
  250. fourthAxisGroup = Group(Axis)
  251. fourthAxisGroup.translate(250,125)
  252. fourthAxisGroup.skew(30,0)
  253. D.add(fourthAxisGroup)
  254. return D
  255. def getDrawing09():
  256. """This tests rotated strings
  257. Some renderers will have a separate mechanism for font drawing. This test
  258. just makes sure strings get transformed the same way as regular graphics."""
  259. D = Drawing(400, 200)
  260. fontName = _FONTS[0]
  261. fontSize = 12
  262. text = "I should be totally horizontal and enclosed in a box"
  263. textWidth = stringWidth(text, fontName, fontSize)
  264. g1 = Group(
  265. String(20, 20, text, fontName=fontName, fontSize = fontSize),
  266. Rect(18, 18, textWidth + 4, fontSize + 4, fillColor=None)
  267. )
  268. D.add(g1)
  269. text = "I should slope up by 15 degrees, so my right end is higher than my left"
  270. textWidth = stringWidth(text, fontName, fontSize)
  271. g2 = Group(
  272. String(20, 20, text, fontName=fontName, fontSize = fontSize),
  273. Rect(18, 18, textWidth + 4, fontSize + 4, fillColor=None)
  274. )
  275. g2.translate(0, 50)
  276. g2.rotate(15)
  277. D.add(g2)
  278. return D
  279. def getDrawing10():
  280. """This tests nested groups with multiple levels of coordinate transformation.
  281. Each box should be staggered up and to the right, moving by 25 points each time."""
  282. D = Drawing(400, 200)
  283. fontName = _FONTS[0]
  284. fontSize = 12
  285. g1 = Group(
  286. Rect(0, 0, 100, 20, fillColor=colors.yellow),
  287. String(5, 5, 'Text in the box', fontName=fontName, fontSize = fontSize)
  288. )
  289. D.add(g1)
  290. g2 = Group(g1, transform = translate(25,25))
  291. D.add(g2)
  292. g3 = Group(g2, transform = translate(25,25))
  293. D.add(g3)
  294. g4 = Group(g3, transform = translate(25,25))
  295. D.add(g4)
  296. return D
  297. from reportlab.graphics.widgets.signsandsymbols import SmileyFace
  298. def getDrawing11():
  299. '''test of anchoring'''
  300. def makeSmiley(x, y, size, color):
  301. "Make a smiley data item representation."
  302. d = size
  303. s = SmileyFace()
  304. s.fillColor = color
  305. s.x = x-d
  306. s.y = y-d
  307. s.size = d*2
  308. return s
  309. D = Drawing(400, 200) #, fillColor=colors.purple)
  310. g = Group(transform=(1,0,0,1,0,0))
  311. g.add(makeSmiley(100,100,10,colors.red))
  312. g.add(Line(90,100,110,100,strokeColor=colors.green))
  313. g.add(Line(100,90,100,110,strokeColor=colors.green))
  314. D.add(g)
  315. g = Group(transform=(2,0,0,2,100,-100))
  316. g.add(makeSmiley(100,100,10,colors.blue))
  317. g.add(Line(90,100,110,100,strokeColor=colors.green))
  318. g.add(Line(100,90,100,110,strokeColor=colors.green))
  319. D.add(g)
  320. g = Group(transform=(2,0,0,2,0,0))
  321. return D
  322. def getDrawing12():
  323. """Text strings in a non-standard font.
  324. All that is required is to place the .afm and .pfb files
  325. on the font patch given in rl_config.py,
  326. for example in reportlab/lib/fonts/.
  327. """
  328. faceName = "DarkGardenMK"
  329. D = Drawing(400, 200)
  330. for size in range(12, 36, 4):
  331. D.add(String(10+size*2,
  332. 10+size*2,
  333. 'Hello World',
  334. fontName=faceName,
  335. fontSize=size))
  336. return D
  337. def getDrawing13():
  338. 'Test Various TTF Fonts'
  339. def drawit(F,w=400,h=200,fontSize=12,slack=2,gap=5):
  340. D = Drawing(w,h)
  341. th = 2*gap + fontSize*1.2
  342. gh = gap + .2*fontSize
  343. y = h
  344. maxx = 0
  345. for fontName in F:
  346. y -= th
  347. text = fontName+asNative(b': I should be totally horizontal and enclosed in a box and end in alphabetagamma \xc2\xa2\xc2\xa9\xc2\xae\xc2\xa3\xca\xa5\xd0\x96\xd6\x83\xd7\x90\xd9\x82\xe0\xa6\x95\xce\xb1\xce\xb2\xce\xb3')
  348. textWidth = stringWidth(text, fontName, fontSize)
  349. maxx = max(maxx,textWidth+20)
  350. D.add(
  351. Group(Rect(8, y-gh, textWidth + 4, th, strokeColor=colors.red, strokeWidth=.5, fillColor=colors.lightgrey),
  352. String(10, y, text, fontName=fontName, fontSize = fontSize)))
  353. y -= 5
  354. return maxx, h-y+gap, D
  355. maxx, maxy, D = drawit(_FONTS)
  356. if maxx>400 or maxy>200: _,_,D = drawit(_FONTS,maxx,maxy)
  357. return D
  358. def smallArrow():
  359. '''create a small PIL image'''
  360. from reportlab.graphics.renderPM import _getImage
  361. from reportlab.lib.utils import getBytesIO
  362. b = base64_decodebytes(b'''R0lGODdhCgAHAIMAAP/////29v/d3f+ysv9/f/9VVf9MTP8iIv8ICP8AAAAAAAAAAAAAAAAAAAAA
  363. AAAAACwAAAAACgAHAAAIMwABCBxIsKABAQASFli4MAECAgEAJJhIceKBAQkyasx4YECBjx8TICAQ
  364. AIDJkwYEAFgZEAA7''')
  365. return _getImage().open(getBytesIO(b))
  366. def getDrawing14():
  367. '''test shapes.Image'''
  368. from reportlab.graphics.shapes import Image
  369. D = Drawing(400, 200)
  370. im0 = smallArrow()
  371. D.add(Image(x=0,y=0,width=None,height=None,path=im0))
  372. im1 = smallArrow()
  373. D.add(Image(x=400-20,y=200-14,width=20,height=14,path=im1))
  374. return D
  375. def getAllFunctionDrawingNames(doTTF=1):
  376. "Get a list of drawing function names from somewhere."
  377. funcNames = []
  378. # Here we get the names from the global name space.
  379. symbols = list(globals().keys())
  380. symbols.sort()
  381. for funcName in symbols:
  382. if funcName[0:10] == 'getDrawing':
  383. if doTTF or funcName!='getDrawing13':
  384. funcNames.append(funcName)
  385. return funcNames
  386. def _evalFuncDrawing(name, D, l=None, g=None):
  387. if g is None: g = globals()
  388. if l is None: l = locals()
  389. func = l.get(name,g.get(name,None))
  390. try:
  391. d = func()
  392. except:
  393. d = getFailedDrawing(name)
  394. D.append((d, getattr(func,'.__doc__',''), name[3:]))
  395. def getAllTestDrawings(doTTF=1):
  396. D = []
  397. for f in getAllFunctionDrawingNames(doTTF=doTTF):
  398. _evalFuncDrawing(f,D)
  399. return D
  400. def writePDF(drawings):
  401. "Create and save a PDF file containing some drawings."
  402. pdfPath = os.path.splitext(sys.argv[0])[0] + '.pdf'
  403. c = Canvas(pdfPath)
  404. c.setFont(_FONTS[0], 32)
  405. c.drawString(80, 750, 'ReportLab Graphics-Shapes Test')
  406. # Print drawings in a loop, with their doc strings.
  407. c.setFont(_FONTS[0], 12)
  408. y = 740
  409. i = 1
  410. for (drawing, docstring, funcname) in drawings:
  411. if y < 300: # Allows 5-6 lines of text.
  412. c.showPage()
  413. y = 740
  414. # Draw a title.
  415. y = y - 30
  416. c.setFont(_FONTS[2],12)
  417. c.drawString(80, y, '%s (#%d)' % (funcname, i))
  418. c.setFont(_FONTS[0],12)
  419. y = y - 14
  420. textObj = c.beginText(80, y)
  421. textObj.textLines(docstring)
  422. c.drawText(textObj)
  423. y = textObj.getY()
  424. y = y - drawing.height
  425. drawing.drawOn(c, 80, y)
  426. i = i + 1
  427. c.save()
  428. print('wrote %s ' % pdfPath)
  429. class ShapesTestCase(unittest.TestCase):
  430. "Test generating all kinds of shapes."
  431. def setUp(self):
  432. "Prepare some things before the tests start."
  433. self.funcNames = getAllFunctionDrawingNames()
  434. self.drawings = []
  435. def tearDown(self):
  436. "Do what has to be done after the tests are over."
  437. writePDF(self.drawings)
  438. # This should always succeed. If each drawing would be
  439. # wrapped in a dedicated test method like this one, it
  440. # would be possible to have a count for wrong tests
  441. # as well... Something like this is left for later...
  442. def testAllDrawings(self):
  443. "Make a list of drawings."
  444. for f in self.funcNames:
  445. if f[0:10] == 'getDrawing':
  446. # Make an instance and get its doc string.
  447. # If that fails, use a default error drawing.
  448. _evalFuncDrawing(f,self.drawings)
  449. def makeSuite():
  450. "Make a test suite for unit testing."
  451. suite = unittest.TestSuite()
  452. suite.addTest(ShapesTestCase('testAllDrawings'))
  453. return suite
  454. if __name__ == "__main__":
  455. unittest.TextTestRunner().run(makeSuite())