canvas.py 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990
  1. #Copyright ReportLab Europe Ltd. 2000-2017
  2. #see license.txt for license details
  3. __version__='3.3.0'
  4. __doc__="""
  5. The Canvas object is the primary interface for creating PDF files. See
  6. doc/reportlab-userguide.pdf for copious examples.
  7. """
  8. __all__ = ['Canvas']
  9. ENABLE_TRACKING = 1 # turn this off to do profile testing w/o tracking
  10. import os
  11. import sys
  12. import re
  13. import hashlib
  14. from string import digits
  15. import tempfile
  16. from math import sin, cos, tan, pi, ceil
  17. from reportlab import rl_config
  18. from reportlab.pdfbase import pdfutils
  19. from reportlab.pdfbase import pdfdoc
  20. from reportlab.pdfbase import pdfmetrics
  21. from reportlab.pdfgen import pdfgeom, pathobject
  22. from reportlab.pdfgen.textobject import PDFTextObject, _PDFColorSetter
  23. from reportlab.lib.colors import black, _chooseEnforceColorSpace, Color, CMYKColor, toColor
  24. from reportlab.lib.utils import import_zlib, ImageReader, isSeq, isStr, isUnicode, _digester, asUnicode
  25. from reportlab.lib.rl_accel import fp_str, escapePDF
  26. from reportlab.lib.boxstuff import aspectRatioFix
  27. digitPat = re.compile(r'\d') #used in decimal alignment
  28. zlib = import_zlib()
  29. # Robert Kern
  30. # Constants for closing paths.
  31. # May be useful if one changes 'arc' and 'rect' to take a
  32. # default argument that tells how to close the path.
  33. # That way we can draw filled shapes.
  34. FILL_EVEN_ODD = 0
  35. FILL_NON_ZERO = 1
  36. #this is used by path-closing routines.
  37. #map stroke, fill, fillmode -> operator
  38. # fillmode: 1 = non-Zero (obviously), 0 = evenOdd
  39. PATH_OPS = {(0, 0, FILL_EVEN_ODD) : 'n', #no op
  40. (0, 0, FILL_NON_ZERO) : 'n', #no op
  41. (1, 0, FILL_EVEN_ODD) : 'S', #stroke only
  42. (1, 0, FILL_NON_ZERO) : 'S', #stroke only
  43. (0, 1, FILL_EVEN_ODD) : 'f*', #Fill only
  44. (0, 1, FILL_NON_ZERO) : 'f', #Fill only
  45. (1, 1, FILL_EVEN_ODD) : 'B*', #Stroke and Fill
  46. (1, 1, FILL_NON_ZERO) : 'B', #Stroke and Fill
  47. }
  48. def _annFormat(D,color,thickness,dashArray,hradius=0,vradius=0):
  49. from reportlab.pdfbase.pdfdoc import PDFArray, PDFDictionary
  50. if color and 'C' not in D:
  51. D["C"] = PDFArray([color.red, color.green, color.blue])
  52. if 'Border' not in D:
  53. border = [hradius,vradius,thickness or 0]
  54. if dashArray:
  55. border.append(PDFArray(dashArray))
  56. D["Border"] = PDFArray(border)
  57. # BS = PDFDictionary()
  58. # bss = 'S'
  59. # if dashArray:
  60. # BS['D'] = PDFArray(dashArray)
  61. # bss = 'D'
  62. # BS['W'] = thickness or 0
  63. # BS['S'] = bss
  64. # D['BS'] = BS
  65. # helpers to guess color space for gradients
  66. def _normalizeColor(aColor):
  67. if isinstance(aColor, CMYKColor):
  68. d = aColor.density
  69. return "DeviceCMYK", tuple(c*d for c in aColor.cmyk())
  70. elif isinstance(aColor, Color):
  71. return "DeviceRGB", aColor.rgb()
  72. elif isinstance(aColor, (tuple, list)):
  73. l = len(aColor)
  74. if l == 3:
  75. return "DeviceRGB", aColor
  76. elif l == 4:
  77. return "DeviceCMYK", aColor
  78. elif isinstance(aColor, str):
  79. return _normalizeColor(toColor(aColor))
  80. raise ValueError("Unknown color %r" % aColor)
  81. def _normalizeColors(colors):
  82. space = None
  83. outcolors = []
  84. for aColor in colors:
  85. nspace, outcolor = _normalizeColor(aColor)
  86. if space is not None and space != nspace:
  87. raise ValueError("Mismatch in color spaces: %s and %s" % (space, nspace))
  88. space = nspace
  89. outcolors.append(outcolor)
  90. return space, outcolors
  91. def _buildColorFunction(colors, positions):
  92. from reportlab.pdfbase.pdfdoc import PDFExponentialFunction, PDFStitchingFunction
  93. if positions is not None and len(positions) != len(colors):
  94. raise ValueError("need to have the same number of colors and positions")
  95. # simplified functions for edge cases
  96. if len(colors) == 1:
  97. # for completeness
  98. return PDFExponentialFunction(N=1, C0=colors[0], C1=colors[0])
  99. if len(colors) == 2:
  100. if positions is None or (positions[0] == 0 and positions[1] == 1):
  101. return PDFExponentialFunction(N=1, C0=colors[0], C1=colors[1])
  102. # equally distribute if positions not specified
  103. if positions is None:
  104. nc = len(colors)
  105. positions = [float(x)/(nc-1) for x in range(nc)]
  106. else:
  107. # sort positions and colors in increasing order
  108. poscolors = list(zip(positions, colors))
  109. poscolors.sort(key=lambda x: x[0])
  110. # add endpoint positions if not already present
  111. if poscolors[0][0] != 0:
  112. poscolors.insert(0, (0.0, poscolors[0][1]))
  113. if poscolors[-1][0] != 1:
  114. poscolors.append((1.0, poscolors[-1][1]))
  115. positions, colors = list(zip(*poscolors)) # unzip
  116. # build stitching function
  117. functions = []
  118. bounds = [pos for pos in positions[1:-1]]
  119. encode = []
  120. lastcolor = colors[0]
  121. for color in colors[1:]:
  122. functions.append(PDFExponentialFunction(N=1, C0=lastcolor, C1=color))
  123. lastcolor = color
  124. encode.append(0.0)
  125. encode.append(1.0)
  126. return PDFStitchingFunction(functions, bounds, encode, Domain="[0.0 1.0]")
  127. class ExtGState:
  128. defaults = dict(
  129. CA=1,
  130. ca=1,
  131. OP=False,
  132. op=False,
  133. OPM=0,
  134. BM='Normal',
  135. )
  136. allowed = dict(
  137. BM = {
  138. 'Normal', 'Multiply', 'Screen', 'Overlay',
  139. 'Darken', 'Lighten', 'ColorDodge', 'ColorBurn',
  140. 'HardLight', 'SoftLight', 'Difference', 'Exclusion',
  141. 'Hue', 'Saturation', 'Color', 'Luminosity',
  142. },
  143. )
  144. pdfNameValues = {'BM'}
  145. @staticmethod
  146. def _boolTransform(v):
  147. return str(v).lower()
  148. @staticmethod
  149. def _identityTransform(v):
  150. return v
  151. @staticmethod
  152. def _pdfNameTransform(v):
  153. return '/'+v
  154. def __init__(self):
  155. self._d = {}
  156. self._c = {}
  157. def set(self,canv,a,v):
  158. d = self.defaults[a]
  159. if isinstance(d,bool):
  160. v=bool(v)
  161. vTransform = self._boolTransform
  162. elif a in self.pdfNameValues:
  163. if v not in self.allowed[a]:
  164. raise ValueError('ExtGstate[%r] = %r not in allowed values %r' % (
  165. a,v,self.allowed[a]))
  166. vTransform = self._pdfNameTransform
  167. else:
  168. vTransform = self._identityTransform
  169. if v!=self._d.get(a,d) or (a=='op' and self.getValue('OP')!=d):
  170. self._d[a] = v
  171. t = a,vTransform(v)
  172. if t in self._c:
  173. name = self._c[t]
  174. else:
  175. name = 'gRLs'+str(len(self._c))
  176. self._c[t] = name
  177. canv._code.append('/%s gs' % name)
  178. def getValue(self,a):
  179. return self._d.get(a,self.defaults[a])
  180. def getState(self):
  181. S = {}
  182. for t,name in self._c.items():
  183. S[name] = pdfdoc.PDFDictionary(dict((t,)))
  184. return S and pdfdoc.PDFDictionary(S) or None
  185. def pushCopy(self):
  186. '''the states must be shared across push/pop, but the values not'''
  187. x = self.__class__()
  188. x._d = self._d.copy()
  189. x._c = self._c
  190. return x
  191. class Canvas(_PDFColorSetter):
  192. """This class is the programmer's interface to the PDF file format. Methods
  193. are (or will be) provided here to do just about everything PDF can do.
  194. The underlying model to the canvas concept is that of a graphics state machine
  195. that at any given point in time has a current font, fill color (for figure
  196. interiors), stroke color (for figure borders), line width and geometric transform, among
  197. many other characteristics.
  198. Canvas methods generally either draw something (like canvas.line) using the
  199. current state of the canvas or change some component of the canvas
  200. state (like canvas.setFont). The current state can be saved and restored
  201. using the saveState/restoreState methods.
  202. Objects are "painted" in the order they are drawn so if, for example
  203. two rectangles overlap the last draw will appear "on top". PDF form
  204. objects (supported here) are used to draw complex drawings only once,
  205. for possible repeated use.
  206. There are other features of canvas which are not visible when printed,
  207. such as outlines and bookmarks which are used for navigating a document
  208. in a viewer.
  209. Here is a very silly example usage which generates a Hello World pdf document.
  210. Example::
  211. from reportlab.pdfgen import canvas
  212. c = canvas.Canvas("hello.pdf")
  213. from reportlab.lib.units import inch
  214. # move the origin up and to the left
  215. c.translate(inch,inch)
  216. # define a large font
  217. c.setFont("Helvetica", 80)
  218. # choose some colors
  219. c.setStrokeColorRGB(0.2,0.5,0.3)
  220. c.setFillColorRGB(1,0,1)
  221. # draw a rectangle
  222. c.rect(inch,inch,6*inch,9*inch, fill=1)
  223. # make text go straight up
  224. c.rotate(90)
  225. # change color
  226. c.setFillColorRGB(0,0,0.77)
  227. # say hello (note after rotate the y coord needs to be negative!)
  228. c.drawString(3*inch, -3*inch, "Hello World")
  229. c.showPage()
  230. c.save()
  231. """
  232. def __init__(self,filename,
  233. pagesize=None,
  234. bottomup = 1,
  235. pageCompression=None,
  236. invariant = None,
  237. verbosity=0,
  238. encrypt=None,
  239. cropMarks=None,
  240. pdfVersion=None,
  241. enforceColorSpace=None,
  242. initialFontName=None,
  243. initialFontSize=None,
  244. initialLeading=None,
  245. cropBox=None,
  246. artBox=None,
  247. trimBox=None,
  248. bleedBox=None,
  249. lang=None,
  250. ):
  251. """Create a canvas of a given size. etc.
  252. You may pass a file-like object to filename as an alternative to
  253. a string.
  254. For more information about the encrypt parameter refer to the setEncrypt method.
  255. Most of the attributes are private - we will use set/get methods
  256. as the preferred interface. Default page size is A4.
  257. cropMarks may be True/False or an object with parameters borderWidth, markColor, markWidth
  258. and markLength
  259. if enforceColorSpace is in ('cmyk', 'rgb', 'sep','sep_black','sep_cmyk') then one of
  260. the standard _PDFColorSetter callables will be used to enforce appropriate color settings.
  261. If it is a callable then that will be used.
  262. """
  263. if pagesize is None: pagesize = rl_config.defaultPageSize
  264. if invariant is None: invariant = rl_config.invariant
  265. self._initialFontName = initialFontName if initialFontName else rl_config.canvas_basefontname
  266. self._initialFontSize = initialFontSize if initialFontSize is not None else 12
  267. self._initialLeading = initialLeading if initialLeading is not None else self._initialFontSize*1.2
  268. self._filename = filename
  269. self._doc = pdfdoc.PDFDocument(compression=pageCompression,
  270. invariant=invariant, filename=filename,
  271. pdfVersion=pdfVersion or pdfdoc.PDF_VERSION_DEFAULT,
  272. lang=lang
  273. )
  274. self._enforceColorSpace = _chooseEnforceColorSpace(enforceColorSpace)
  275. #this only controls whether it prints 'saved ...' - 0 disables
  276. self._verbosity = verbosity
  277. #this is called each time a page is output if non-null
  278. self._onPage = None
  279. self._cropMarks = cropMarks
  280. self._pagesize = pagesize
  281. self._hanging_pagesize = None
  282. self._pageRotation = 0
  283. #self._currentPageHasImages = 0
  284. self._pageTransition = None
  285. self._pageDuration = None
  286. self._destinations = {} # dictionary of destinations for cross indexing.
  287. self.setPageCompression(pageCompression)
  288. self._pageNumber = 1 # keep a count
  289. # when we create a form we need to save operations not in the form
  290. self._codeStack = []
  291. self._restartAccumulators() # restart all accumulation state (generalized, arw)
  292. self._annotationCount = 0
  293. self._outlines = [] # list for a name tree
  294. self._psCommandsBeforePage = [] #for postscript tray/font commands
  295. self._psCommandsAfterPage = [] #for postscript tray/font commands
  296. #PostScript has the origin at bottom left. It is easy to achieve a top-
  297. #down coord system by translating to the top of the page and setting y
  298. #scale to -1, but then text is inverted. So self.bottomup is used
  299. #to also set the text matrix accordingly. You can now choose your
  300. #drawing coordinates.
  301. self.bottomup = bottomup
  302. self.imageCaching = rl_config.defaultImageCaching
  303. self._cropBox = cropBox #we don't do semantics for these at all
  304. self._artBox = artBox
  305. self._trimBox = trimBox
  306. self._bleedBox = bleedBox
  307. self.init_graphics_state()
  308. self._make_preamble()
  309. self.state_stack = []
  310. self.setEncrypt(encrypt)
  311. def setEncrypt(self, encrypt):
  312. '''
  313. Set the encryption used for the pdf generated by this canvas.
  314. If encrypt is a string object, it is used as the user password for the pdf.
  315. If encrypt is an instance of reportlab.lib.pdfencrypt.StandardEncryption, this object is
  316. used to encrypt the pdf. This allows more finegrained control over the encryption settings.
  317. '''
  318. if encrypt:
  319. from reportlab.lib import pdfencrypt
  320. if isStr(encrypt): #encrypt is the password itself
  321. if isUnicode(encrypt):
  322. encrypt = encrypt.encode('utf-8')
  323. encrypt = pdfencrypt.StandardEncryption(encrypt) #now it's the encrypt object
  324. encrypt.setAllPermissions(1)
  325. elif not isinstance(encrypt, pdfencrypt.StandardEncryption):
  326. raise TypeError('Expected string or instance of reportlab.lib.pdfencrypt.StandardEncryption as encrypt parameter but got %r' % encrypt)
  327. self._doc.encrypt = encrypt
  328. else:
  329. try:
  330. del self._doc.encrypt
  331. except AttributeError:
  332. pass
  333. def init_graphics_state(self):
  334. #initial graphics state, never modify any of these in place
  335. self._x = 0
  336. self._y = 0
  337. self._fontname = self._initialFontName
  338. self._fontsize = self._initialFontSize
  339. self._textMode = 0 #track if between BT/ET
  340. self._leading = self._initialLeading
  341. self._currentMatrix = (1., 0., 0., 1., 0., 0.)
  342. self._fillMode = FILL_EVEN_ODD
  343. #text state
  344. self._charSpace = 0
  345. self._wordSpace = 0
  346. self._horizScale = 100
  347. self._textRenderMode = 0
  348. self._rise = 0
  349. self._textLineMatrix = (1., 0., 0., 1., 0., 0.)
  350. self._textMatrix = (1., 0., 0., 1., 0., 0.)
  351. # line drawing
  352. self._lineCap = 0
  353. self._lineJoin = 0
  354. self._lineDash = None #not done
  355. self._lineWidth = 1
  356. self._mitreLimit = 0
  357. self._fillColorObj = self._strokeColorObj = rl_config.canvas_baseColor or (0,0,0)
  358. self._extgstate = ExtGState()
  359. def push_state_stack(self):
  360. state = {}
  361. d = self.__dict__
  362. for name in self.STATE_ATTRIBUTES:
  363. state[name] = d[name] #getattr(self, name)
  364. self.state_stack.append(state)
  365. self._extgstate = self._extgstate.pushCopy()
  366. def pop_state_stack(self):
  367. self.__dict__.update(self.state_stack.pop())
  368. STATE_ATTRIBUTES = """_x _y _fontname _fontsize _textMode _leading _currentMatrix _fillMode
  369. _charSpace _wordSpace _horizScale _textRenderMode _rise _textLineMatrix
  370. _textMatrix _lineCap _lineJoin _lineDash _lineWidth _mitreLimit _fillColorObj
  371. _strokeColorObj _extgstate""".split()
  372. STATE_RANGE = list(range(len(STATE_ATTRIBUTES)))
  373. #self._addStandardFonts()
  374. def _make_preamble(self):
  375. P = [].append
  376. if self.bottomup:
  377. P('1 0 0 1 0 0 cm')
  378. else:
  379. P('1 0 0 -1 0 %s cm' % fp_str(self._pagesize[1]))
  380. C = self._code
  381. n = len(C)
  382. if self._fillColorObj != (0,0,0):
  383. self.setFillColor(self._fillColorObj)
  384. if self._strokeColorObj != (0,0,0):
  385. self.setStrokeColor(self._strokeColorObj)
  386. P(' '.join(C[n:]))
  387. del C[n:]
  388. font = pdfmetrics.getFont(self._fontname)
  389. if not font._dynamicFont:
  390. #set an initial font
  391. if font.face.builtIn or not getattr(self,'_drawTextAsPath',False):
  392. P('BT %s 12 Tf 14.4 TL ET' % self._doc.getInternalFontName(self._fontname))
  393. self._preamble = ' '.join(P.__self__)
  394. def _escape(self, s):
  395. return escapePDF(s)
  396. #info functions - non-standard
  397. def setAuthor(self, author):
  398. """identify the author for invisible embedding inside the PDF document.
  399. the author annotation will appear in the the text of the file but will
  400. not automatically be seen when the document is viewed, but is visible
  401. in document properties etc etc."""
  402. self._doc.setAuthor(author)
  403. def setDateFormatter(self, dateFormatter):
  404. """accepts a func(yyyy,mm,dd,hh,m,s) used to create embedded formatted date"""
  405. self._doc.setDateFormatter(dateFormatter)
  406. def addOutlineEntry(self, title, key, level=0, closed=None):
  407. """Adds a new entry to the outline at given level. If LEVEL not specified,
  408. entry goes at the top level. If level specified, it must be
  409. no more than 1 greater than the outline level in the last call.
  410. The key must be the (unique) name of a bookmark.
  411. the title is the (non-unique) name to be displayed for the entry.
  412. If closed is set then the entry should show no subsections by default
  413. when displayed.
  414. Example::
  415. c.addOutlineEntry("first section", "section1")
  416. c.addOutlineEntry("introduction", "s1s1", 1, closed=1)
  417. c.addOutlineEntry("body", "s1s2", 1)
  418. c.addOutlineEntry("detail1", "s1s2s1", 2)
  419. c.addOutlineEntry("detail2", "s1s2s2", 2)
  420. c.addOutlineEntry("conclusion", "s1s3", 1)
  421. c.addOutlineEntry("further reading", "s1s3s1", 2)
  422. c.addOutlineEntry("second section", "section1")
  423. c.addOutlineEntry("introduction", "s2s1", 1)
  424. c.addOutlineEntry("body", "s2s2", 1, closed=1)
  425. c.addOutlineEntry("detail1", "s2s2s1", 2)
  426. c.addOutlineEntry("detail2", "s2s2s2", 2)
  427. c.addOutlineEntry("conclusion", "s2s3", 1)
  428. c.addOutlineEntry("further reading", "s2s3s1", 2)
  429. generated outline looks like::
  430. - first section
  431. |- introduction
  432. |- body
  433. | |- detail1
  434. | |- detail2
  435. |- conclusion
  436. | |- further reading
  437. - second section
  438. |- introduction
  439. |+ body
  440. |- conclusion
  441. | |- further reading
  442. Note that the second "body" is closed.
  443. Note that you can jump from level 5 to level 3 but not
  444. from 3 to 5: instead you need to provide all intervening
  445. levels going down (4 in this case). Note that titles can
  446. collide but keys cannot.
  447. """
  448. #to be completed
  449. #self._outlines.append(title)
  450. self._doc.outline.addOutlineEntry(key, level, title, closed=closed)
  451. def setOutlineNames0(self, *nametree): # keep this for now (?)
  452. """nametree should can be a recursive tree like so::
  453. c.setOutlineNames(
  454. "chapter1dest",
  455. ("chapter2dest",
  456. ["chapter2section1dest",
  457. "chapter2section2dest",
  458. "chapter2conclusiondest"]
  459. ), # end of chapter2 description
  460. "chapter3dest",
  461. ("chapter4dest", ["c4s1", "c4s2"])
  462. )
  463. each of the string names inside must be bound to a bookmark
  464. before the document is generated.
  465. """
  466. self._doc.outline.setNames(*((self,)+nametree))
  467. def setTitle(self, title):
  468. """write a title into the PDF file that won't automatically display
  469. in the document itself."""
  470. self._doc.setTitle(title)
  471. def setSubject(self, subject):
  472. """write a subject into the PDF file that won't automatically display
  473. in the document itself."""
  474. self._doc.setSubject(subject)
  475. def setCreator(self, creator):
  476. """write a creator into the PDF file that won't automatically display
  477. in the document itself. This should be used to name the original app
  478. which is passing data into ReportLab, if you wish to name it."""
  479. self._doc.setCreator(creator)
  480. def setProducer(self, producer):
  481. """change the default producer value"""
  482. self._doc.setProducer(producer)
  483. def setKeywords(self, keywords):
  484. """write a list of keywords into the PDF file which shows in document properties.
  485. Either submit a single string or a list/tuple"""
  486. if isinstance(keywords,(list,tuple)):
  487. keywords = ', '.join(keywords)
  488. self._doc.setKeywords(keywords)
  489. def pageHasData(self):
  490. "Info function - app can call it after showPage to see if it needs a save"
  491. return len(self._code) == 0
  492. def showOutline(self):
  493. """Specify that Acrobat Reader should start with the outline tree visible.
  494. showFullScreen() and showOutline() conflict; the one called last
  495. wins."""
  496. self._doc._catalog.showOutline()
  497. def showFullScreen0(self):
  498. """Specify that Acrobat Reader should start in full screen mode.
  499. showFullScreen() and showOutline() conflict; the one called last
  500. wins."""
  501. self._doc._catalog.showFullScreen()
  502. def _setStrokeAlpha(self,v):
  503. """
  504. Define the transparency/opacity of strokes. 0 is fully
  505. transparent, 1 is fully opaque.
  506. Note that calling this function will cause a version 1.4 PDF
  507. to be generated (rather than 1.3).
  508. """
  509. self._doc.ensureMinPdfVersion('transparency')
  510. self._extgstate.set(self,'CA',v)
  511. def _setFillAlpha(self,v):
  512. """
  513. Define the transparency/opacity of non-strokes. 0 is fully
  514. transparent, 1 is fully opaque.
  515. Note that calling this function will cause a version 1.4 PDF
  516. to be generated (rather than 1.3).
  517. """
  518. self._doc.ensureMinPdfVersion('transparency')
  519. self._extgstate.set(self,'ca',v)
  520. def _setStrokeOverprint(self,v):
  521. self._extgstate.set(self,'OP',v)
  522. def _setFillOverprint(self,v):
  523. self._extgstate.set(self,'op',v)
  524. def _setOverprintMask(self,v):
  525. self._extgstate.set(self,'OPM',v and 1 or 0)
  526. def setBlendMode(self, v):
  527. self._extgstate.set(self,'BM',v)
  528. def _getCmShift(self):
  529. cM = self._cropMarks
  530. if cM:
  531. bleedW = max(0,getattr(cM,'bleedWidth',0))
  532. bw = max(0,getattr(cM,'borderWidth',36))
  533. if bleedW:
  534. bw -= bleedW
  535. return bw
  536. def showPage(self):
  537. """Close the current page and possibly start on a new page."""
  538. # ensure a space at the end of the stream - Acrobat does
  539. # not mind, but Ghostscript dislikes 'Qendstream' even if
  540. # the length marker finishes after 'Q'
  541. pageWidth = self._pagesize[0]
  542. pageHeight = self._pagesize[1]
  543. cM = self._cropMarks
  544. code = self._code
  545. if cM:
  546. bw = max(0,getattr(cM,'borderWidth',36))
  547. if bw:
  548. markLast = getattr(cM,'markLast',1)
  549. ml = min(bw,max(0,getattr(cM,'markLength',18)))
  550. mw = getattr(cM,'markWidth',0.5)
  551. mc = getattr(cM,'markColor',black)
  552. mg = 2*bw-ml
  553. cx0 = len(code)
  554. if ml and mc:
  555. self.saveState()
  556. self.setStrokeColor(mc)
  557. self.setLineWidth(mw)
  558. self.lines([
  559. (bw,0,bw,ml),
  560. (pageWidth+bw,0,pageWidth+bw,ml),
  561. (bw,pageHeight+mg,bw,pageHeight+2*bw),
  562. (pageWidth+bw,pageHeight+mg,pageWidth+bw,pageHeight+2*bw),
  563. (0,bw,ml,bw),
  564. (pageWidth+mg,bw,pageWidth+2*bw,bw),
  565. (0,pageHeight+bw,ml,pageHeight+bw),
  566. (pageWidth+mg,pageHeight+bw,pageWidth+2*bw,pageHeight+bw),
  567. ])
  568. self.restoreState()
  569. if markLast:
  570. #if the marks are to be drawn after the content
  571. #save the code we just drew for later use
  572. L = code[cx0:]
  573. del code[cx0:]
  574. cx0 = len(code)
  575. bleedW = max(0,getattr(cM,'bleedWidth',0))
  576. self.saveState()
  577. self.translate(bw-bleedW,bw-bleedW)
  578. if bleedW:
  579. #scale everything
  580. self.scale(1+(2.0*bleedW)/pageWidth,1+(2.0*bleedW)/pageHeight)
  581. #move our translation/expansion code to the beginning
  582. C = code[cx0:]
  583. del code[cx0:]
  584. code[0:0] = C
  585. self.restoreState()
  586. if markLast:
  587. code.extend(L)
  588. pageWidth = 2*bw + pageWidth
  589. pageHeight = 2*bw + pageHeight
  590. code.append(' ')
  591. page = pdfdoc.PDFPage()
  592. page.pagewidth = pageWidth
  593. page.pageheight = pageHeight
  594. page.Rotate = self._pageRotation
  595. page.hasImages = self._currentPageHasImages
  596. page.setPageTransition(self._pageTransition)
  597. page.setCompression(self._pageCompression)
  598. for box in ('crop','art','bleed','trim'):
  599. size = getattr(self,'_%sBox'%box,None)
  600. if size:
  601. setattr(page,box.capitalize()+'Box',pdfdoc.PDFArray(size))
  602. if self._pageDuration is not None:
  603. page.Dur = self._pageDuration
  604. strm = self._psCommandsBeforePage + [self._preamble] + code + self._psCommandsAfterPage
  605. page.setStream(strm)
  606. self._setColorSpace(page)
  607. self._setExtGState(page)
  608. self._setXObjects(page)
  609. self._setShadingUsed(page)
  610. self._setAnnotations(page)
  611. self._doc.addPage(page)
  612. if self._onPage: self._onPage(self._pageNumber)
  613. self._startPage()
  614. def _startPage(self):
  615. #now get ready for the next one
  616. if self._hanging_pagesize:
  617. self.setPageSize(self._hanging_pagesize)
  618. self._hanging_pagesize = None
  619. self._pageNumber += 1
  620. self._restartAccumulators()
  621. self.init_graphics_state()
  622. self.state_stack = []
  623. def setPageCallBack(self, func):
  624. """func(pageNum) will be called on each page end.
  625. This is mainly a hook for progress monitoring.
  626. Call setPageCallback(None) to clear a callback."""
  627. self._onPage = func
  628. def _setAnnotations(self,page):
  629. page.Annots = self._annotationrefs
  630. def _setColorSpace(self,obj):
  631. obj._colorsUsed = self._colorsUsed
  632. def _setShadingUsed(self, page):
  633. page._shadingUsed = self._shadingUsed
  634. def _setXObjects(self, thing):
  635. """for pages and forms, define the XObject dictionary for resources, if needed"""
  636. forms = self._formsinuse
  637. if forms:
  638. xobjectsdict = self._doc.xobjDict(forms)
  639. thing.XObjects = xobjectsdict
  640. else:
  641. thing.XObjects = None
  642. def _bookmarkReference(self, name):
  643. """get a reference to a (possibly undefined, possibly unbound) bookmark"""
  644. d = self._destinations
  645. try:
  646. return d[name]
  647. except:
  648. result = d[name] = pdfdoc.Destination(name) # newly defined, unbound
  649. return result
  650. def bookmarkPage(self, key,
  651. fit="Fit",
  652. left=None,
  653. top=None,
  654. bottom=None,
  655. right=None,
  656. zoom=None
  657. ):
  658. """
  659. This creates a bookmark to the current page which can
  660. be referred to with the given key elsewhere.
  661. PDF offers very fine grained control over how Acrobat
  662. reader is zoomed when people link to this. The default
  663. is to keep the user's current zoom settings. the last
  664. arguments may or may not be needed depending on the
  665. choice of 'fitType'.
  666. Fit types and the other arguments they use are:
  667. - XYZ left top zoom - fine grained control. null
  668. or zero for any of the parameters means 'leave
  669. as is', so "0,0,0" will keep the reader's settings.
  670. NB. Adobe Reader appears to prefer "null" to 0's.
  671. - Fit - entire page fits in window
  672. - FitH top - top coord at top of window, width scaled
  673. to fit.
  674. - FitV left - left coord at left of window, height
  675. scaled to fit
  676. - FitR left bottom right top - scale window to fit
  677. the specified rectangle
  678. (question: do we support /FitB, FitBH and /FitBV
  679. which are hangovers from version 1.1 / Acrobat 3.0?)"""
  680. dest = self._bookmarkReference(key)
  681. self._doc.inPage() # try to enable page-only features
  682. pageref = self._doc.thisPageRef()
  683. #None = "null" for PDF
  684. if left is None:
  685. left = "null"
  686. if top is None:
  687. top = "null"
  688. if bottom is None:
  689. bottom = "null"
  690. if right is None:
  691. right = "null"
  692. if zoom is None:
  693. zoom = "null"
  694. if fit == "XYZ":
  695. dest.xyz(left,top,zoom)
  696. elif fit == "Fit":
  697. dest.fit()
  698. elif fit == "FitH":
  699. dest.fith(top)
  700. elif fit == "FitV":
  701. dest.fitv(left)
  702. elif fit == "FitR":
  703. dest.fitr(left,bottom,right,top)
  704. #Do we need these (version 1.1 / Acrobat 3 versions)?
  705. elif fit == "FitB":
  706. dest.fitb()
  707. elif fit == "FitBH":
  708. dest.fitbh(top)
  709. elif fit == "FitBV":
  710. dest.fitbv(left)
  711. else:
  712. raise ValueError("Unknown Fit type %s" % ascii(fit))
  713. dest.setPage(pageref)
  714. return dest
  715. def bookmarkHorizontalAbsolute(self, key, top, left=0, fit='XYZ', **kw):
  716. """Bind a bookmark (destination) to the current page at a horizontal position.
  717. Note that the yhorizontal of the book mark is with respect to the default
  718. user space (where the origin is at the lower left corner of the page)
  719. and completely ignores any transform (translation, scale, skew, rotation,
  720. etcetera) in effect for the current graphics state. The programmer is
  721. responsible for making sure the bookmark matches an appropriate item on
  722. the page."""
  723. #This method should probably be deprecated since it is just a sub-set of bookmarkPage
  724. return self.bookmarkPage(key, fit=fit, top=top, left=left, zoom=0)
  725. def bookmarkHorizontal(self, key, relativeX, relativeY, **kw):
  726. """w.r.t. the current transformation, bookmark this horizontal."""
  727. (left, top) = self.absolutePosition(relativeX,relativeY)
  728. self.bookmarkHorizontalAbsolute(key, top, left=left, **kw)
  729. #def _inPage0(self): disallowed!
  730. # """declare a page, enable page features"""
  731. # self._doc.inPage()
  732. #def _inForm0(self):
  733. # "deprecated in favore of beginForm...endForm"
  734. # self._doc.inForm()
  735. def doForm(self, name):
  736. """use a form XObj in current operation stream.
  737. The form should either have been defined previously using
  738. beginForm ... endForm, or may be defined later. If it is not
  739. defined at save time, an exception will be raised. The form
  740. will be drawn within the context of the current graphics
  741. state."""
  742. self._code.append("/%s Do" % self._doc.getXObjectName(name))
  743. self._formsinuse.append(name)
  744. def hasForm(self, name):
  745. """Query whether form XObj really exists yet."""
  746. return self._doc.hasForm(name)
  747. ######################################################
  748. #
  749. # Image routines
  750. #
  751. ######################################################
  752. def drawInlineImage(self, image, x,y, width=None,height=None,
  753. preserveAspectRatio=False,anchor='c', anchorAtXY=False, showBoundary=False):
  754. """See drawImage, which should normally be used instead...
  755. drawInlineImage behaves like drawImage, but stores the image content
  756. within the graphics stream for the page. This means that the mask
  757. parameter for transparency is not available. It also means that there
  758. is no saving in file size or time if the same image is reused.
  759. In theory it allows images to be displayed slightly faster; however,
  760. we doubt if the difference is noticeable to any human user these days.
  761. Only use this if you have studied the PDF specification and know the
  762. implications.
  763. """
  764. self._currentPageHasImages = 1
  765. from reportlab.pdfgen.pdfimages import PDFImage
  766. img_obj = PDFImage(image, x,y, width, height)
  767. img_obj.drawInlineImage(self,
  768. preserveAspectRatio=preserveAspectRatio,
  769. anchor=anchor,anchorAtXY=anchorAtXY,showBoundary=showBoundary)
  770. return (img_obj.width, img_obj.height)
  771. def drawImage(self, image, x, y, width=None, height=None, mask=None,
  772. preserveAspectRatio=False, anchor='c', anchorAtXY=False, showBoundary=False):
  773. """Draws the image (ImageReader object or filename) as specified.
  774. "image" may be an image filename or an ImageReader object.
  775. x and y define the lower left corner of the image you wish to
  776. draw (or of its bounding box, if using preserveAspectRation below).
  777. If width and height are not given, the width and height of the
  778. image in pixels is used at a scale of 1 point to 1 pixel.
  779. If width and height are given, the image will be stretched to fill
  780. the given rectangle bounded by (x, y, x+width, y-height).
  781. If you supply negative widths and/or heights, it inverts them and adjusts
  782. x and y accordingly.
  783. The method returns the width and height of the underlying image, since
  784. this is often useful for layout algorithms and saves you work if you have
  785. not specified them yourself.
  786. The mask parameter supports transparent backgrounds. It takes 6 numbers
  787. and defines the range of RGB values which will be masked out or treated
  788. as transparent. For example with [0,2,40,42,136,139], it will mask out
  789. any pixels with a Red value from 0-2, Green from 40-42 and
  790. Blue from 136-139 (on a scale of 0-255).
  791. New post version 2.0: drawImage can center an image in a box you
  792. provide, while preserving its aspect ratio. For example, you might
  793. have a fixed square box in your design, and a collection of photos
  794. which might be landscape or portrait that you want to appear within
  795. the box. If preserveAspectRatio is true, your image will appear within
  796. the box specified.
  797. If preserveAspectRatio is True, the anchor property can be used to
  798. specify how images should fit into the given box. It should
  799. be set to one of the following values, taken from the points of
  800. the compass (plus 'c' for 'centre'):
  801. nw n ne
  802. w c e
  803. sw s se
  804. The default value is 'c' for 'centre'. Thus, if you want your
  805. bitmaps to always be centred and appear at the top of the given box,
  806. set anchor='n'. There are good examples of this in the output
  807. of test_pdfgen_general.py
  808. Unlike drawInlineImage, this creates 'external images' which
  809. are only stored once in the PDF file but can be drawn many times.
  810. If you give it the same filename twice, even at different locations
  811. and sizes, it will reuse the first occurrence, resulting in a saving
  812. in file size and generation time. If you use ImageReader objects,
  813. it tests whether the image content has changed before deciding
  814. whether to reuse it.
  815. In general you should use drawImage in preference to drawInlineImage
  816. unless you have read the PDF Spec and understand the tradeoffs."""
  817. self._currentPageHasImages = 1
  818. # first, generate a unique name/signature for the image. If ANYTHING
  819. # is different, even the mask, this should be different.
  820. if isinstance(image,ImageReader):
  821. rawdata = image.getRGBData()
  822. smask = image._dataA
  823. if mask=='auto' and smask:
  824. mdata = smask.getRGBData()
  825. else:
  826. mdata = str(mask)
  827. if isUnicode(mdata):
  828. mdata = mdata.encode('utf8')
  829. name = _digester(rawdata+mdata)
  830. else:
  831. #filename, use it
  832. s = '%s%s' % (image, mask)
  833. if isUnicode(s):
  834. s = s.encode('utf-8')
  835. name = _digester(s)
  836. # in the pdf document, this will be prefixed with something to
  837. # say it is an XObject. Does it exist yet?
  838. regName = self._doc.getXObjectName(name)
  839. imgObj = self._doc.idToObject.get(regName, None)
  840. if not imgObj:
  841. #first time seen, create and register the PDFImageXobject
  842. imgObj = pdfdoc.PDFImageXObject(name, image, mask=mask)
  843. imgObj.name = name
  844. self._setXObjects(imgObj)
  845. self._doc.Reference(imgObj, regName)
  846. self._doc.addForm(name, imgObj)
  847. smask = getattr(imgObj,'_smask',None)
  848. if smask: #set up the softmask obtained above
  849. mRegName = self._doc.getXObjectName(smask.name)
  850. mImgObj = self._doc.idToObject.get(mRegName, None)
  851. if not mImgObj:
  852. self._setXObjects(smask)
  853. imgObj.smask = self._doc.Reference(smask,mRegName)
  854. else:
  855. imgObj.smask = pdfdoc.PDFObjectReference(mRegName)
  856. del imgObj._smask
  857. # ensure we have a size, as PDF will make it 1x1 pixel otherwise!
  858. x,y,width,height,scaled = aspectRatioFix(preserveAspectRatio,anchor,x,y,width,height,imgObj.width,imgObj.height,anchorAtXY)
  859. # scale and draw
  860. self.saveState()
  861. self.translate(x, y)
  862. self.scale(width, height)
  863. self._code.append("/%s Do" % regName)
  864. self.restoreState()
  865. if showBoundary:
  866. self.rect(x,y,width,height,stroke=1,fill=0)
  867. # track what's been used on this page
  868. self._formsinuse.append(name)
  869. return (imgObj.width, imgObj.height)
  870. def _restartAccumulators(self):
  871. if self._codeStack:
  872. # restore the saved code
  873. self._code, self._formsinuse, self._annotationrefs, self._formData,self._colorsUsed, self._shadingUsed = self._codeStack.pop(-1)
  874. else:
  875. self._code = [] # ready for more...
  876. self._psCommandsAfterPage = []
  877. self._psCommandsBeforePage = []
  878. self._currentPageHasImages = 1 # for safety...
  879. self._formsinuse = []
  880. self._annotationrefs = []
  881. self._formData = None
  882. self._colorsUsed = {}
  883. self._shadingUsed = {}
  884. def _pushAccumulators(self):
  885. "when you enter a form, save accumulator info not related to the form for page (if any)"
  886. saved = (self._code, self._formsinuse, self._annotationrefs, self._formData, self._colorsUsed, self._shadingUsed)
  887. self._codeStack.append(saved)
  888. self._code = [] # ready for more...
  889. self._currentPageHasImages = 1 # for safety...
  890. self._formsinuse = []
  891. self._annotationrefs = []
  892. self._formData = None
  893. self._colorsUsed = {}
  894. self._shadingUsed = {}
  895. def _setExtGState(self, obj):
  896. obj.ExtGState = self._extgstate.getState()
  897. def beginForm(self, name, lowerx=0, lowery=0, upperx=None, uppery=None):
  898. """declare the current graphics stream to be a named form.
  899. A graphics stream can either be a page or a form, not both.
  900. Some operations (like bookmarking) are permitted for pages
  901. but not forms. The form will not automatically be shown in the
  902. document but must be explicitly referenced using doForm in pages
  903. that require the form."""
  904. self.push_state_stack()
  905. self.init_graphics_state()
  906. if self._code or self._formData:
  907. # save the code that is not in the formf
  908. self._pushAccumulators()
  909. #self._codeStack.append(self._code)
  910. #self._code = []
  911. self._formData = (name, lowerx, lowery, upperx, uppery)
  912. self._doc.inForm()
  913. #self._inForm0()
  914. def endForm(self,**extra_attributes):
  915. """emit the current collection of graphics operations as a Form
  916. as declared previously in beginForm."""
  917. (name, lowerx, lowery, upperx, uppery) = self._formData
  918. #self.makeForm0(name, lowerx, lowery, upperx, uppery)
  919. # fall through! makeForm0 disallowed
  920. #def makeForm0(self, name, lowerx=0, lowery=0, upperx=None, uppery=None):
  921. """Like showpage, but make a form using accumulated operations instead"""
  922. # deprecated in favor or beginForm(...)... endForm()
  923. (w,h) = self._pagesize
  924. if upperx is None: upperx=w
  925. if uppery is None: uppery=h
  926. form = pdfdoc.PDFFormXObject(lowerx=lowerx, lowery=lowery, upperx=upperx, uppery=uppery)
  927. form.compression = self._pageCompression
  928. form.setStreamList([self._preamble] + self._code) # ??? minus preamble (seems to be needed!)
  929. for k, v in extra_attributes.items():
  930. setattr(form,k,v)
  931. self._setColorSpace(form)
  932. self._setExtGState(form)
  933. self._setXObjects(form)
  934. self._setAnnotations(form)
  935. self._doc.addForm(name, form)
  936. self._restartAccumulators()
  937. self.pop_state_stack()
  938. def addPostScriptCommand(self, command, position=1):
  939. """Embed literal Postscript in the document.
  940. With position=0, it goes at very beginning of page stream;
  941. with position=1, at current point; and
  942. with position=2, at very end of page stream. What that does
  943. to the resulting Postscript depends on Adobe's header :-)
  944. Use with extreme caution, but sometimes needed for printer tray commands.
  945. Acrobat 4.0 will export Postscript to a printer or file containing
  946. the given commands. Adobe Reader 6.0 no longer does as this feature is
  947. deprecated. 5.0, I don't know about (please let us know!). This was
  948. funded by Bob Marshall of Vector.co.uk and tested on a Lexmark 750.
  949. See test_pdfbase_postscript.py for 2 test cases - one will work on
  950. any Postscript device, the other uses a 'setpapertray' command which
  951. will error in Distiller but work on printers supporting it.
  952. """
  953. #check if we've done this one already...
  954. if isUnicode(command):
  955. rawName = 'PS' + hashlib.md5(command.encode('utf-8')).hexdigest()
  956. else:
  957. rawName = 'PS' + hashlib.md5(command).hexdigest()
  958. regName = self._doc.getXObjectName(rawName)
  959. psObj = self._doc.idToObject.get(regName, None)
  960. if not psObj:
  961. #first use of this chunk of Postscript, make an object
  962. psObj = pdfdoc.PDFPostScriptXObject(command + '\n')
  963. self._setXObjects(psObj)
  964. self._doc.Reference(psObj, regName)
  965. self._doc.addForm(rawName, psObj)
  966. if position == 0:
  967. self._psCommandsBeforePage.append("/%s Do" % regName)
  968. elif position==1:
  969. self._code.append("/%s Do" % regName)
  970. else:
  971. self._psCommandsAfterPage.append("/%s Do" % regName)
  972. self._formsinuse.append(rawName)
  973. def _absRect(self,rect,relative=0):
  974. if not rect:
  975. w,h = self._pagesize
  976. rect = (0,0,w,h)
  977. elif relative:
  978. lx, ly, ux, uy = rect
  979. xll,yll = self.absolutePosition(lx,ly)
  980. xur,yur = self.absolutePosition(ux, uy)
  981. xul,yul = self.absolutePosition(lx, uy)
  982. xlr,ylr = self.absolutePosition(ux, ly)
  983. xs = xll, xur, xul, xlr
  984. ys = yll, yur, yul, ylr
  985. xmin, ymin = min(xs), min(ys)
  986. xmax, ymax = max(xs), max(ys)
  987. rect = xmin, ymin, xmax, ymax
  988. bw = self._getCmShift()
  989. if bw:
  990. rect = rect[0]+bw,rect[1]+bw,rect[2]+bw,rect[3]+bw
  991. return rect
  992. def freeTextAnnotation(self, contents, DA, Rect=None, addtopage=1, name=None, relative=0, **kw):
  993. """DA is the default appearance string???"""
  994. Rect = self._absRect(Rect,relative)
  995. self._addAnnotation(pdfdoc.FreeTextAnnotation(Rect, contents, DA, **kw), name, addtopage)
  996. def textAnnotation(self, contents, Rect=None, addtopage=1, name=None, relative=0, **kw):
  997. """Experimental, but works.
  998. """
  999. Rect = self._absRect(Rect,relative)
  1000. self._addAnnotation(pdfdoc.TextAnnotation(Rect, contents, **kw), name, addtopage)
  1001. textAnnotation0 = textAnnotation #deprecated
  1002. def highlightAnnotation(self, contents, Rect, QuadPoints=None, Color=[0.83, 0.89, 0.95], addtopage=1,
  1003. name=None, relative=0, **kw):
  1004. """
  1005. Allows adding of a highlighted annotation.
  1006. Rect: Mouseover area to show contents of annotation
  1007. QuadPoints: List of four x/y points [TOP-LEFT, TOP-RIGHT, BOTTOM-LEFT, BOTTOM-RIGHT]
  1008. These points outline the areas to highlight.
  1009. You can have multiple groups of four to allow multiple highlighted areas.
  1010. Is in the format [x1, y1, x2, y2, x3, y3, x4, y4, x1, y1, x2, y2, x3, y3, x4, y4] etc
  1011. QuadPoints defaults to be area inside of passed in Rect
  1012. Color: The color of the highlighting.
  1013. """
  1014. Rect = self._absRect(Rect, relative)
  1015. if not QuadPoints:
  1016. QuadPoints = pdfdoc.rect_to_quad(Rect)
  1017. self._addAnnotation(pdfdoc.HighlightAnnotation(Rect, contents, QuadPoints, Color, **kw), name, addtopage)
  1018. def inkAnnotation(self, contents, InkList=None, Rect=None, addtopage=1, name=None, relative=0, **kw):
  1019. raise NotImplementedError
  1020. "Experimental"
  1021. Rect = self._absRect(Rect,relative)
  1022. if not InkList:
  1023. InkList = ((100,100,100,h-100,w-100,h-100,w-100,100),)
  1024. self._addAnnotation(pdfdoc.InkAnnotation(Rect, contents, InkList, **kw), name, addtopage)
  1025. inkAnnotation0 = inkAnnotation #deprecated
  1026. def linkAbsolute(self, contents, destinationname, Rect=None, addtopage=1, name=None,
  1027. thickness=0, color=None, dashArray=None, **kw):
  1028. """rectangular link annotation positioned wrt the default user space.
  1029. The identified rectangle on the page becomes a "hot link" which
  1030. when clicked will send the viewer to the page and position identified
  1031. by the destination.
  1032. Rect identifies (lowerx, lowery, upperx, uppery) for lower left
  1033. and upperright points of the rectangle. Translations and other transforms
  1034. are IGNORED (the rectangular position is given with respect
  1035. to the default user space.
  1036. destinationname should be the name of a bookmark (which may be defined later
  1037. but must be defined before the document is generated).
  1038. You may want to use the keyword argument Border='[0 0 0]' to
  1039. suppress the visible rectangle around the during viewing link."""
  1040. return self.linkRect(contents, destinationname, Rect, addtopage, name, relative=0,
  1041. thickness=thickness, color=color, dashArray=dashArray, **kw)
  1042. def linkRect(self, contents, destinationname, Rect=None, addtopage=1, name=None, relative=1,
  1043. thickness=0, color=None, dashArray=None, **kw):
  1044. """rectangular link annotation w.r.t the current user transform.
  1045. if the transform is skewed/rotated the absolute rectangle will use the max/min x/y
  1046. """
  1047. destination = self._bookmarkReference(destinationname) # permitted to be undefined... must bind later...
  1048. Rect = self._absRect(Rect,relative)
  1049. kw["Rect"] = Rect
  1050. kw["Contents"] = contents
  1051. kw["Destination"] = destination
  1052. _annFormat(kw,color,thickness,dashArray)
  1053. return self._addAnnotation(pdfdoc.LinkAnnotation(**kw), name, addtopage)
  1054. def linkURL(self, url, rect, relative=0, thickness=0, color=None, dashArray=None, kind="URI", **kw):
  1055. """Create a rectangular URL 'hotspot' in the given rectangle.
  1056. if relative=1, this is in the current coord system, otherwise
  1057. in absolute page space.
  1058. The remaining options affect the border appearance; the border is
  1059. drawn by Acrobat, not us. Set thickness to zero to hide it.
  1060. Any border drawn this way is NOT part of the page stream and
  1061. will not show when printed to a Postscript printer or distilled;
  1062. it is safest to draw your own."""
  1063. from reportlab.pdfbase.pdfdoc import PDFDictionary, PDFName, PDFArray, PDFString
  1064. #tried the documented BS element in the pdf spec but it
  1065. #does not work, and Acrobat itself does not appear to use it!
  1066. ann = PDFDictionary(dict=kw)
  1067. ann["Type"] = PDFName("Annot")
  1068. ann["Subtype"] = PDFName("Link")
  1069. ann["Rect"] = PDFArray(self._absRect(rect,relative)) # the whole page for testing
  1070. # the action is a separate dictionary
  1071. A = PDFDictionary()
  1072. A["Type"] = PDFName("Action") # not needed?
  1073. uri = PDFString(url)
  1074. A['S'] = PDFName(kind)
  1075. if kind=="URI":
  1076. A["URI"] = uri
  1077. elif kind=='GoToR':
  1078. A["F"] = uri
  1079. A["D"] = "[ 0 /XYZ null null null ]"
  1080. else:
  1081. raise ValueError("Unknown linkURI kind '%s'" % kind)
  1082. ann["A"] = A
  1083. _annFormat(ann,color,thickness,dashArray)
  1084. self._addAnnotation(ann)
  1085. def _addAnnotation(self, annotation, name=None, addtopage=1):
  1086. count = self._annotationCount = self._annotationCount+1
  1087. if not name: name="NUMBER"+repr(count)
  1088. self._doc.addAnnotation(name, annotation)
  1089. if addtopage:
  1090. self._annotatePage(name)
  1091. def _annotatePage(self, name):
  1092. ref = self._doc.refAnnotation(name)
  1093. self._annotationrefs.append(ref)
  1094. def getPageNumber(self):
  1095. "get the page number for the current page being generated."
  1096. return self._pageNumber
  1097. def save(self):
  1098. """Saves and close the PDF document in the file.
  1099. If there is current data a ShowPage is executed automatically.
  1100. After this operation the canvas must not be used further."""
  1101. if len(self._code): self.showPage()
  1102. self._doc.SaveToFile(self._filename, self)
  1103. def getpdfdata(self):
  1104. """Returns the PDF data that would normally be written to a file.
  1105. If there is current data a ShowPage is executed automatically.
  1106. After this operation the canvas must not be used further."""
  1107. if len(self._code): self.showPage()
  1108. s = self._doc.GetPDFData(self)
  1109. if isUnicode(s):
  1110. s = s.encode('utf-8')
  1111. return s
  1112. def setPageSize(self, size):
  1113. """accepts a 2-tuple in points for paper size for this
  1114. and subsequent pages"""
  1115. self._pagesize = size
  1116. self._make_preamble()
  1117. def setCropBox(self, size, name='crop'):
  1118. """accepts a 2-tuple in points for name+'Box' size for this and subsequent pages"""
  1119. name = name.lower()
  1120. if name.endswith('box'): name = name[:-3]
  1121. if name not in ('crop','art','trim','bleed'):
  1122. raise ValueError('unknown box name: %r' % name)
  1123. setattr(self,'_%sBox' % name, size)
  1124. def setTrimBox(self,size):
  1125. self.setCropBox(size,name='trim')
  1126. def setArtBox(self,size):
  1127. self.setCropBox(size,name='art')
  1128. def setBleedBox(self,size):
  1129. self.setCropBox(size,name='bleed')
  1130. def setPageRotation(self, rot):
  1131. """Instruct display device that this page is to be rotated"""
  1132. assert rot % 90.0 == 0.0, "Rotation must be a multiple of 90 degrees"
  1133. self._pageRotation = rot
  1134. def addLiteral(self, s, escaped=1):
  1135. """introduce the literal text of PDF operations s into the current stream.
  1136. Only use this if you are an expert in the PDF file format."""
  1137. s = str(s) # make sure its a string
  1138. if escaped==0:
  1139. s = self._escape(s) # convert to string for safety
  1140. self._code.append(s)
  1141. ######################################################################
  1142. #
  1143. # coordinate transformations
  1144. #
  1145. ######################################################################
  1146. def resetTransforms(self):
  1147. """I want to draw something (eg, string underlines) w.r.t. the default user space.
  1148. Reset the matrix! This should be used usually as follows::
  1149. canv.saveState()
  1150. canv.resetTransforms()
  1151. #...draw some stuff in default space coords...
  1152. canv.restoreState() # go back!
  1153. """
  1154. # we have to adjoin the inverse, since reset is not a basic operation (without save/restore)
  1155. (selfa, selfb, selfc, selfd, selfe, selff) = self._currentMatrix
  1156. det = selfa*selfd - selfc*selfb
  1157. resulta = selfd/det
  1158. resultc = -selfc/det
  1159. resulte = (selfc*selff - selfd*selfe)/det
  1160. resultd = selfa/det
  1161. resultb = -selfb/det
  1162. resultf = (selfe*selfb - selff*selfa)/det
  1163. self.transform(resulta, resultb, resultc, resultd, resulte, resultf)
  1164. def transform(self, a,b,c,d,e,f):
  1165. """adjoin a mathematical transform to the current graphics state matrix.
  1166. Not recommended for beginners."""
  1167. #How can Python track this?
  1168. if ENABLE_TRACKING:
  1169. a0,b0,c0,d0,e0,f0 = self._currentMatrix
  1170. self._currentMatrix = (a0*a+c0*b, b0*a+d0*b,
  1171. a0*c+c0*d, b0*c+d0*d,
  1172. a0*e+c0*f+e0, b0*e+d0*f+f0)
  1173. if self._code and self._code[-1][-3:]==' cm':
  1174. L = self._code[-1].split()
  1175. a0, b0, c0, d0, e0, f0 = list(map(float,L[-7:-1]))
  1176. s = len(L)>7 and join(L)+ ' %s cm' or '%s cm'
  1177. self._code[-1] = s % fp_str(a0*a+c0*b,b0*a+d0*b,a0*c+c0*d,b0*c+d0*d,a0*e+c0*f+e0,b0*e+d0*f+f0)
  1178. else:
  1179. self._code.append('%s cm' % fp_str(a,b,c,d,e,f))
  1180. def absolutePosition(self, x, y):
  1181. """return the absolute position of x,y in user space w.r.t. default user space"""
  1182. if not ENABLE_TRACKING:
  1183. raise ValueError("tracking not enabled! (canvas.ENABLE_TRACKING=0)")
  1184. (a,b,c,d,e,f) = self._currentMatrix
  1185. xp = a*x + c*y + e
  1186. yp = b*x + d*y + f
  1187. return (xp, yp)
  1188. def translate(self, dx, dy):
  1189. """move the origin from the current (0,0) point to the (dx,dy) point
  1190. (with respect to the current graphics state)."""
  1191. self.transform(1,0,0,1,dx,dy)
  1192. def scale(self, x, y):
  1193. """Scale the horizontal dimension by x and the vertical by y
  1194. (with respect to the current graphics state).
  1195. For example canvas.scale(2.0, 0.5) will make everything short and fat."""
  1196. self.transform(x,0,0,y,0,0)
  1197. def rotate(self, theta):
  1198. """Canvas.rotate(theta)
  1199. Rotate the canvas by the angle theta (in degrees)."""
  1200. c = cos(theta * pi / 180)
  1201. s = sin(theta * pi / 180)
  1202. self.transform(c, s, -s, c, 0, 0)
  1203. def skew(self, alpha, beta):
  1204. tanAlpha = tan(alpha * pi / 180)
  1205. tanBeta = tan(beta * pi / 180)
  1206. self.transform(1, tanAlpha, tanBeta, 1, 0, 0)
  1207. ######################################################################
  1208. #
  1209. # graphics state management
  1210. #
  1211. ######################################################################
  1212. def saveState(self):
  1213. """Save the current graphics state to be restored later by restoreState.
  1214. For example:
  1215. canvas.setFont("Helvetica", 20)
  1216. canvas.saveState()
  1217. ...
  1218. canvas.setFont("Courier", 9)
  1219. ...
  1220. canvas.restoreState()
  1221. # if the save/restore pairs match then font is Helvetica 20 again.
  1222. """
  1223. self.push_state_stack()
  1224. self._code.append('q')
  1225. def restoreState(self):
  1226. """restore the graphics state to the matching saved state (see saveState)."""
  1227. self._code.append('Q')
  1228. self.pop_state_stack()
  1229. ###############################################################
  1230. #
  1231. # Drawing methods. These draw things directly without
  1232. # fiddling around with Path objects. We can add any geometry
  1233. # methods we wish as long as their meaning is precise and
  1234. # they are of general use.
  1235. #
  1236. # In general there are two patterns. Closed shapes
  1237. # have the pattern shape(self, args, stroke=1, fill=0);
  1238. # by default they draw an outline only. Line segments come
  1239. # in three flavours: line, bezier, arc (which is a segment
  1240. # of an elliptical arc, approximated by up to four bezier
  1241. # curves, one for each quadrant.
  1242. #
  1243. # In the case of lines, we provide a 'plural' to unroll
  1244. # the inner loop; it is useful for drawing big grids
  1245. ################################################################
  1246. #--------first the line drawing methods-----------------------
  1247. def line(self, x1,y1, x2,y2):
  1248. """draw a line segment from (x1,y1) to (x2,y2) (with color, thickness and
  1249. other attributes determined by the current graphics state)."""
  1250. self._code.append('n %s m %s l S' % (fp_str(x1, y1), fp_str(x2, y2)))
  1251. def lines(self, linelist):
  1252. """Like line(), permits many lines to be drawn in one call.
  1253. for example for the figure::
  1254. |
  1255. -- --
  1256. |
  1257. crosshairs = [(20,0,20,10), (20,30,20,40), (0,20,10,20), (30,20,40,20)]
  1258. canvas.lines(crosshairs)
  1259. """
  1260. self._code.append('n')
  1261. for (x1,y1,x2,y2) in linelist:
  1262. self._code.append('%s m %s l' % (fp_str(x1, y1), fp_str(x2, y2)))
  1263. self._code.append('S')
  1264. def cross(self, x, y, size=5, gap=1, text=None, strokeColor=None, strokeWidth=None, fontSize=3):
  1265. size *= 0.5
  1266. gap *= 0.5
  1267. crosshairs = [(x,y-size,x,y-gap),(x,y+gap,x,y+size), (x-size,y,x-gap,y),(x+gap,y,x+size,y)]
  1268. self.saveState()
  1269. if strokeColor:
  1270. self.setStrokeColor(strokeColor)
  1271. if text:
  1272. self.setFillColor(strokeColor)
  1273. if strokeWidth:
  1274. self.setLineWidth(StrokeWidth)
  1275. self.lines(crosshairs)
  1276. if text:
  1277. if fontSize is not None: self.setFontSize(fontSize)
  1278. self.drawRightString(x-size, y, text)
  1279. self.restoreState()
  1280. def grid(self, xlist, ylist):
  1281. """Lays out a grid in current line style. Supply list of
  1282. x an y positions."""
  1283. assert len(xlist) > 1, "x coordinate list must have 2+ items"
  1284. assert len(ylist) > 1, "y coordinate list must have 2+ items"
  1285. lines = []
  1286. y0, y1 = ylist[0], ylist[-1]
  1287. x0, x1 = xlist[0], xlist[-1]
  1288. for x in xlist:
  1289. lines.append((x,y0,x,y1))
  1290. for y in ylist:
  1291. lines.append((x0,y,x1,y))
  1292. self.lines(lines)
  1293. def bezier(self, x1, y1, x2, y2, x3, y3, x4, y4):
  1294. "Bezier curve with the four given control points"
  1295. self._code.append('n %s m %s c S' %
  1296. (fp_str(x1, y1), fp_str(x2, y2, x3, y3, x4, y4))
  1297. )
  1298. def arc(self, x1,y1, x2,y2, startAng=0, extent=90):
  1299. """Draw a partial ellipse inscribed within the rectangle x1,y1,x2,y2,
  1300. starting at startAng degrees and covering extent degrees. Angles
  1301. start with 0 to the right (+x) and increase counter-clockwise.
  1302. These should have x1<x2 and y1<y2."""
  1303. pathobject.PDFPathObject(code=self._code).arc(x1,y1,x2,y2,startAng,extent)
  1304. self._strokeAndFill(1,0)
  1305. #--------now the shape drawing methods-----------------------
  1306. def rect(self, x, y, width, height, stroke=1, fill=0):
  1307. "draws a rectangle with lower left corner at (x,y) and width and height as given."
  1308. self._code.append('n %s re ' % fp_str(x, y, width, height)
  1309. + PATH_OPS[stroke, fill, self._fillMode])
  1310. def ellipse(self, x1, y1, x2, y2, stroke=1, fill=0):
  1311. """Draw an ellipse defined by an enclosing rectangle.
  1312. Note that (x1,y1) and (x2,y2) are the corner points of
  1313. the enclosing rectangle.
  1314. """
  1315. pathobject.PDFPathObject(code=self._code).ellipse(x1, y1, x2-x1, y2-y1)
  1316. self._strokeAndFill(stroke, fill)
  1317. def wedge(self, x1,y1, x2,y2, startAng, extent, stroke=1, fill=0):
  1318. """Like arc, but connects to the centre of the ellipse.
  1319. Most useful for pie charts and PacMan!"""
  1320. p = pathobject.PDFPathObject(code=self._code)
  1321. p.moveTo(0.5*(x1+x2),0.5*(y1+y2))
  1322. p.arcTo(x1,y1,x2,y2,startAng,extent)
  1323. p.close()
  1324. self._strokeAndFill(stroke,fill)
  1325. def circle(self, x_cen, y_cen, r, stroke=1, fill=0):
  1326. """draw a cirle centered at (x_cen,y_cen) with radius r (special case of ellipse)"""
  1327. x1 = x_cen - r
  1328. x2 = x_cen + r
  1329. y1 = y_cen - r
  1330. y2 = y_cen + r
  1331. self.ellipse(x1, y1, x2, y2, stroke, fill)
  1332. def roundRect(self, x, y, width, height, radius, stroke=1, fill=0):
  1333. """Draws a rectangle with rounded corners. The corners are
  1334. approximately quadrants of a circle, with the given radius."""
  1335. #make the path operators draw into our code
  1336. pathobject.PDFPathObject(code=self._code).roundRect(x, y, width, height, radius)
  1337. self._strokeAndFill(stroke,fill)
  1338. def _addShading(self, shading):
  1339. name = self._doc.addShading(shading)
  1340. self._shadingUsed[name] = name
  1341. return name
  1342. def shade(self, shading):
  1343. name = self._addShading(shading)
  1344. self._code.append('/%s sh' % name)
  1345. def linearGradient(self, x0, y0, x1, y1, colors, positions=None, extend=True):
  1346. #this code contributed by Peter Johnson <johnson.peter@gmail.com>
  1347. from reportlab.pdfbase.pdfdoc import PDFAxialShading
  1348. colorSpace, ncolors = _normalizeColors(colors)
  1349. fcn = _buildColorFunction(ncolors, positions)
  1350. if extend:
  1351. extendStr = "[true true]"
  1352. else:
  1353. extendStr = "[false false]"
  1354. shading = PDFAxialShading(x0, y0, x1, y1, Function=fcn,
  1355. ColorSpace=colorSpace, Extend=extendStr)
  1356. self.shade(shading)
  1357. def radialGradient(self, x, y, radius, colors, positions=None, extend=True):
  1358. #this code contributed by Peter Johnson <johnson.peter@gmail.com>
  1359. from reportlab.pdfbase.pdfdoc import PDFRadialShading
  1360. colorSpace, ncolors = _normalizeColors(colors)
  1361. fcn = _buildColorFunction(ncolors, positions)
  1362. if extend:
  1363. extendStr = "[true true]"
  1364. else:
  1365. extendStr = "[false false]"
  1366. shading = PDFRadialShading(x, y, 0.0, x, y, radius, Function=fcn,
  1367. ColorSpace=colorSpace, Extend=extendStr)
  1368. self.shade(shading)
  1369. ##################################################
  1370. #
  1371. # Text methods
  1372. #
  1373. # As with graphics, a separate object ensures that
  1374. # everything is bracketed between text operators.
  1375. # The methods below are a high-level convenience.
  1376. # use PDFTextObject for multi-line text.
  1377. ##################################################
  1378. def drawString(self, x, y, text, mode=None, charSpace=0, direction=None, wordSpace=None):
  1379. """Draws a string in the current text styles."""
  1380. text = asUnicode(text)
  1381. #we could inline this for speed if needed
  1382. t = self.beginText(x, y, direction=direction)
  1383. if mode is not None: t.setTextRenderMode(mode)
  1384. if charSpace: t.setCharSpace(charSpace)
  1385. if wordSpace: t.setWordSpace(wordSpace)
  1386. t.textLine(text)
  1387. if charSpace: t.setCharSpace(0)
  1388. if wordSpace: t.setWordSpace(0)
  1389. if mode is not None: t.setTextRenderMode(0)
  1390. self.drawText(t)
  1391. def drawRightString(self, x, y, text, mode=None, charSpace=0, direction=None, wordSpace=None):
  1392. """Draws a string right-aligned with the x coordinate"""
  1393. if sys.version_info[0] == 3 and not isinstance(text, str):
  1394. text = text.decode('utf-8')
  1395. width = self.stringWidth(text, self._fontname, self._fontsize)
  1396. if charSpace: width += (len(text)-1)*charSpace
  1397. if wordSpace: width += (text.count(u' ')+text.count(u'\xa0')-1)*wordSpace
  1398. t = self.beginText(x - width, y, direction=direction)
  1399. if mode is not None: t.setTextRenderMode(mode)
  1400. if charSpace: t.setCharSpace(charSpace)
  1401. if wordSpace: t.setWordSpace(wordSpace)
  1402. t.textLine(text)
  1403. if charSpace: t.setCharSpace(0)
  1404. if wordSpace: t.setWordSpace(0)
  1405. if mode is not None: t.setTextRenderMode(0)
  1406. self.drawText(t)
  1407. def drawCentredString(self, x, y, text, mode=None, charSpace=0, direction=None, wordSpace=None):
  1408. """Draws a string centred on the x coordinate.
  1409. We're British, dammit, and proud of our spelling!"""
  1410. if sys.version_info[0] == 3 and not isinstance(text, str):
  1411. text = text.decode('utf-8')
  1412. width = self.stringWidth(text, self._fontname, self._fontsize)
  1413. if charSpace: width += (len(text)-1)*charSpace
  1414. if wordSpace: width += (text.count(u' ')+text.count(u'\xa0')-1)*wordSpace
  1415. t = self.beginText(x - 0.5*width, y, direction=direction)
  1416. if mode is not None: t.setTextRenderMode(mode)
  1417. if charSpace: t.setCharSpace(charSpace)
  1418. if wordSpace: t.setWordSpace(wordSpace)
  1419. t.textLine(text)
  1420. if charSpace: t.setCharSpace(0)
  1421. if wordSpace: t.setWordSpace(0)
  1422. if mode is not None: t.setTextRenderMode(0)
  1423. self.drawText(t)
  1424. def drawAlignedString(self, x, y, text, pivotChar=rl_config.decimalSymbol, mode=None, charSpace=0, direction=None, wordSpace=None):
  1425. """Draws a string aligned on the first '.' (or other pivot character).
  1426. The centre position of the pivot character will be used as x.
  1427. So, you could draw a straight line down through all the decimals in a
  1428. column of numbers, and anything without a decimal should be
  1429. optically aligned with those that have.
  1430. There is one special rule to help with accounting formatting. Here's
  1431. how normal numbers should be aligned on the 'dot'. Look at the
  1432. LAST two::
  1433. 12,345,67
  1434. 987.15
  1435. 42
  1436. -1,234.56
  1437. (456.78)
  1438. (456)
  1439. 27 inches
  1440. 13cm
  1441. Since the last three do not contain a dot, a crude dot-finding
  1442. rule would place them wrong. So we test for the special case
  1443. where no pivot is found, digits are present, but the last character
  1444. is not a digit. We then work back from the end of the string
  1445. This case is a tad slower but hopefully rare.
  1446. """
  1447. parts = text.split(pivotChar,1)
  1448. pivW = self.stringWidth(pivotChar, self._fontname, self._fontsize)
  1449. if len(parts) == 1 and digitPat.search(text) is not None and text[-1] not in digits:
  1450. #we have no decimal but it ends in a bracket, or 'in' or something.
  1451. #the cut should be after the last digit.
  1452. leftText = parts[0][0:-1]
  1453. rightText = parts[0][-1]
  1454. #any more?
  1455. while leftText[-1] not in digits:
  1456. rightText = leftText[-1] + rightText
  1457. leftText = leftText[0:-1]
  1458. self.drawRightString(x-0.5*pivW, y, leftText, mode=mode, charSpace=charSpace,
  1459. direction=direction, wordSpace=wordSpace)
  1460. self.drawString(x-0.5*pivW, y, rightText, mode=mode, charSpace=charSpace,
  1461. direction=direction, wordSpace=wordSpace)
  1462. else:
  1463. #normal case
  1464. leftText = parts[0]
  1465. self.drawRightString(x-0.5*pivW, y, leftText, mode=mode, charSpace=charSpace,
  1466. direction=direction, wordSpace=wordSpace)
  1467. if len(parts) > 1:
  1468. rightText = pivotChar + parts[1]
  1469. self.drawString(x-0.5*pivW, y, rightText, mode=mode, charSpace=charSpace,
  1470. direction=direction, wordSpace=wordSpace)
  1471. def getAvailableFonts(self):
  1472. """Returns the list of PostScript font names available.
  1473. Standard set now, but may grow in future with font embedding."""
  1474. fontnames = self._doc.getAvailableFonts()
  1475. return fontnames
  1476. def listLoadedFonts0(self):
  1477. "Convenience function to list all loaded fonts"
  1478. names = list(pdfmetrics.widths.keys())
  1479. names.sort()
  1480. return names
  1481. def setFont(self, psfontname, size, leading = None):
  1482. """Sets the font. If leading not specified, defaults to 1.2 x
  1483. font size. Raises a readable exception if an illegal font
  1484. is supplied. Font names are case-sensitive! Keeps track
  1485. of font name and size for metrics."""
  1486. self._fontname = psfontname
  1487. self._fontsize = size
  1488. if leading is None:
  1489. leading = size * 1.2
  1490. self._leading = leading
  1491. font = pdfmetrics.getFont(self._fontname)
  1492. if not font._dynamicFont:
  1493. if font.face.builtIn or not getattr(self,'_drawTextAsPath',False):
  1494. pdffontname = self._doc.getInternalFontName(psfontname)
  1495. self._code.append('BT %s %s Tf %s TL ET' % (pdffontname, fp_str(size), fp_str(leading)))
  1496. def setFontSize(self, size=None, leading=None):
  1497. '''Sets font size or leading without knowing the font face'''
  1498. if size is None: size = self._fontsize
  1499. if leading is None: leading = self._leading
  1500. self.setFont(self._fontname, size, leading)
  1501. def stringWidth(self, text, fontName=None, fontSize=None):
  1502. "gets width of a string in the given font and size"
  1503. return pdfmetrics.stringWidth(text, fontName or self._fontname,
  1504. (fontSize,self._fontsize)[fontSize is None])
  1505. # basic graphics modes
  1506. def setLineWidth(self, width):
  1507. self._lineWidth = width
  1508. self._code.append('%s w' % fp_str(width))
  1509. def setLineCap(self, mode):
  1510. """0=butt,1=round,2=square"""
  1511. assert mode in (0,1,2), "Line caps allowed: 0=butt,1=round,2=square"
  1512. self._lineCap = mode
  1513. self._code.append('%d J' % mode)
  1514. def setLineJoin(self, mode):
  1515. """0=mitre, 1=round, 2=bevel"""
  1516. assert mode in (0,1,2), "Line Joins allowed: 0=mitre, 1=round, 2=bevel"
  1517. self._lineJoin = mode
  1518. self._code.append('%d j' % mode)
  1519. def setMiterLimit(self, limit):
  1520. self._miterLimit = limit
  1521. self._code.append('%s M' % fp_str(limit))
  1522. def setDash(self, array=[], phase=0):
  1523. """Two notations. pass two numbers, or an array and phase"""
  1524. reason = ''
  1525. if isinstance(array,(int,float)):
  1526. array = (array, phase)
  1527. phase = 0
  1528. elif not isSeq(array):
  1529. reason = 'array should be a sequence of numbers or a number'
  1530. bad = [_ for _ in array if not isinstance(_,(int,float)) or _ < 0]
  1531. if bad or not isinstance(phase,(int,float)) or phase<0:
  1532. reason = 'array & phase should be non-negative numbers'
  1533. elif array and sum(array)<=0:
  1534. reason = 'dash cycle should be larger than zero'
  1535. if reason:
  1536. raise ValueError('setDash: array=%r phase=%r\n%s' % (array, phase, reason))
  1537. self._code.append('[%s] %s d' % (fp_str(array), phase))
  1538. # path stuff - the separate path object builds it
  1539. def beginPath(self):
  1540. """Returns a fresh path object. Paths are used to draw
  1541. complex figures. The object returned follows the protocol
  1542. for a pathobject.PDFPathObject instance"""
  1543. return pathobject.PDFPathObject()
  1544. def drawPath(self, aPath, stroke=1, fill=0, fillMode=None):
  1545. "Draw the path object in the mode indicated"
  1546. if fillMode is None:
  1547. fillMode = getattr(aPath,'_fillMode',self._fillMode)
  1548. self._code.append(str(aPath.getCode()))
  1549. self._strokeAndFill(stroke,fill,fillMode)
  1550. def _strokeAndFill(self,stroke,fill,fillMode=None):
  1551. self._code.append(PATH_OPS[stroke, fill, fillMode if fillMode is not None else self._fillMode])
  1552. def clipPath(self, aPath, stroke=1, fill=0, fillMode=None):
  1553. "clip as well as drawing"
  1554. if fillMode is None:
  1555. fillMode = getattr(aPath,'_fillMode',self._fillMode)
  1556. gc = aPath.getCode(); pathops = PATH_OPS[stroke, fill, fillMode]
  1557. clip = (fillMode == FILL_EVEN_ODD and ' W* ' or ' W ')
  1558. item = "%s%s%s" % (gc, clip, pathops) # ensure string conversion
  1559. self._code.append(item)
  1560. #self._code.append( aPath.getCode()
  1561. # + (self._fillMode == FILL_EVEN_ODD and ' W* ' or ' W ')
  1562. # + PATH_OPS[stroke,fill,self._fillMode])
  1563. def beginText(self, x=0, y=0, direction=None):
  1564. """Returns a fresh text object. Text objects are used
  1565. to add large amounts of text. See PDFTextObject"""
  1566. return PDFTextObject(self, x, y, direction=direction)
  1567. def drawText(self, aTextObject):
  1568. """Draws a text object"""
  1569. self._code.append(str(aTextObject.getCode()))
  1570. def setPageCompression(self, pageCompression=1):
  1571. """Possible values None, 1 or 0
  1572. If None the value from rl_config will be used.
  1573. If on, the page data will be compressed, leading to much
  1574. smaller files, but takes a little longer to create the files.
  1575. This applies to all subsequent pages, or until setPageCompression()
  1576. is next called."""
  1577. if pageCompression is None: pageCompression = rl_config.pageCompression
  1578. if pageCompression and not zlib:
  1579. self._pageCompression = 0
  1580. else:
  1581. self._pageCompression = pageCompression
  1582. self._doc.setCompression(self._pageCompression)
  1583. def setPageDuration(self, duration=None):
  1584. """Allows hands-off animation of presentations :-)
  1585. If this is set to a number, in full screen mode, Acrobat Reader
  1586. will advance to the next page after this many seconds. The
  1587. duration of the transition itself (fade/flicker etc.) is controlled
  1588. by the 'duration' argument to setPageTransition; this controls
  1589. the time spent looking at the page. This is effective for all
  1590. subsequent pages."""
  1591. self._pageDuration = duration
  1592. def setPageTransition(self, effectname=None, duration=1,
  1593. direction=0,dimension='H',motion='I'):
  1594. """PDF allows page transition effects for use when giving
  1595. presentations. There are six possible effects. You can
  1596. just guive the effect name, or supply more advanced options
  1597. to refine the way it works. There are three types of extra
  1598. argument permitted, and here are the allowed values::
  1599. direction_arg = [0,90,180,270]
  1600. dimension_arg = ['H', 'V']
  1601. motion_arg = ['I','O'] (start at inside or outside)
  1602. This table says which ones take which arguments::
  1603. PageTransitionEffects = {
  1604. 'Split': [direction_arg, motion_arg],
  1605. 'Blinds': [dimension_arg],
  1606. 'Box': [motion_arg],
  1607. 'Wipe' : [direction_arg],
  1608. 'Dissolve' : [],
  1609. 'Glitter':[direction_arg]
  1610. }
  1611. Have fun!
  1612. """
  1613. # This builds a Python dictionary with the right arguments
  1614. # for the Trans dictionary in the PDFPage object,
  1615. # and stores it in the variable _pageTransition.
  1616. # showPage later passes this to the setPageTransition method
  1617. # of the PDFPage object, which turns it to a PDFDictionary.
  1618. self._pageTransition = {}
  1619. if not effectname:
  1620. return
  1621. #first check each optional argument has an allowed value
  1622. if direction in [0,90,180,270]:
  1623. direction_arg = ('Di', '/%d' % direction)
  1624. else:
  1625. raise pdfdoc.PDFError(' directions allowed are 0,90,180,270')
  1626. if dimension in ['H', 'V']:
  1627. dimension_arg = ('Dm', '/' + dimension)
  1628. else:
  1629. raise pdfdoc.PDFError('dimension values allowed are H and V')
  1630. if motion in ['I','O']:
  1631. motion_arg = ('M', '/' + motion)
  1632. else:
  1633. raise pdfdoc.PDFError('motion values allowed are I and O')
  1634. # this says which effects require which argument types from above
  1635. PageTransitionEffects = {
  1636. 'Split': [direction_arg, motion_arg],
  1637. 'Blinds': [dimension_arg],
  1638. 'Box': [motion_arg],
  1639. 'Wipe' : [direction_arg],
  1640. 'Dissolve' : [],
  1641. 'Glitter':[direction_arg]
  1642. }
  1643. try:
  1644. args = PageTransitionEffects[effectname]
  1645. except KeyError:
  1646. raise pdfdoc.PDFError('Unknown Effect Name "%s"' % effectname)
  1647. # now build the dictionary
  1648. transDict = {}
  1649. transDict['Type'] = '/Trans'
  1650. transDict['D'] = '%d' % duration
  1651. transDict['S'] = '/' + effectname
  1652. for (key, value) in args:
  1653. transDict[key] = value
  1654. self._pageTransition = transDict
  1655. def getCurrentPageContent(self):
  1656. """Return uncompressed contents of current page buffer.
  1657. This is useful in creating test cases and assertions of what
  1658. got drawn, without necessarily saving pages to disk"""
  1659. return '\n'.join(self._code)
  1660. def setViewerPreference(self,pref,value):
  1661. '''set one of the allowed enbtries in the documents viewer preferences'''
  1662. catalog = self._doc.Catalog
  1663. VP = getattr(catalog,'ViewerPreferences',None)
  1664. if VP is None:
  1665. from reportlab.pdfbase.pdfdoc import ViewerPreferencesPDFDictionary
  1666. VP = catalog.ViewerPreferences = ViewerPreferencesPDFDictionary()
  1667. VP[pref] = value
  1668. def getViewerPreference(self,pref):
  1669. '''you'll get an error here if none have been set'''
  1670. return self._doc.Catalog.ViewerPreferences[pref]
  1671. def delViewerPreference(self,pref):
  1672. '''you'll get an error here if none have been set'''
  1673. del self._doc.Catalog.ViewerPreferences[pref]
  1674. def setCatalogEntry(self,key,value):
  1675. from reportlab.pdfbase.pdfdoc import PDFDictionary, PDFArray, PDFString
  1676. if isStr(value):
  1677. value = PDFString(value)
  1678. elif isinstance(value,(list,tuple)):
  1679. value = PDFArray(value)
  1680. elif isinstance(value,dict):
  1681. value = PDFDictionary(value)
  1682. setattr(self._doc.Catalog,key,value)
  1683. def getCatalogEntry(self,key):
  1684. return getattr(self._doc.Catalog,key)
  1685. def delCatalogEntry(self,key):
  1686. '''you'll get an error here if it's not been set'''
  1687. delattr(self._doc.Catalog,key)
  1688. def addPageLabel(self, pageNum, style=None, start=None, prefix=None):
  1689. '''add a PDFPageLabel for pageNum'''
  1690. catalog = self._doc.Catalog
  1691. PL = getattr(catalog,'PageLabels',None)
  1692. if PL is None:
  1693. from reportlab.pdfbase.pdfdoc import PDFPageLabels
  1694. PL = catalog.PageLabels = PDFPageLabels()
  1695. from reportlab.pdfbase.pdfdoc import PDFPageLabel
  1696. PL.addPageLabel(pageNum,PDFPageLabel(style,start,prefix))
  1697. @property
  1698. def acroForm(self):
  1699. "get form from canvas, create the form if needed"
  1700. try:
  1701. return self.AcroForm
  1702. except AttributeError:
  1703. from reportlab.pdfbase.acroform import AcroForm
  1704. self._doc._catalog.AcroForm = self.AcroForm = AcroForm(self)
  1705. return self.AcroForm
  1706. @property
  1707. def drawBoundary(self):
  1708. if not hasattr(self,'_drawBoundary'):
  1709. from reportlab.platypus import Frame
  1710. self._drawBoundary = lambda sb,x,y,w,h: Frame._drawBoundary(self,sb,x,y,w,h)
  1711. return self._drawBoundary
  1712. if __name__ == '__main__':
  1713. print('For test scripts, look in tests')