-
Notifications
You must be signed in to change notification settings - Fork 40
/
flowables.py
1996 lines (1782 loc) · 71.2 KB
/
flowables.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/platypus/flowables.py
__version__=''' $Id$ '''
__doc__="""
A flowable is a "floating element" in a document whose exact position is determined by the
other elements that precede it, such as a paragraph, a diagram interspersed between paragraphs,
a section header, etcetera. Examples of non-flowables include page numbering annotations,
headers, footers, fixed diagrams or logos, among others.
Flowables are defined here as objects which know how to determine their size and which
can draw themselves onto a page with respect to a relative "origin" position determined
at a higher level. The object's draw() method should assume that (0,0) corresponds to the
bottom left corner of the enclosing rectangle that will contain the object. The attributes
vAlign and hAlign may be used by 'packers' as hints as to how the object should be placed.
Some Flowables also know how to "split themselves". For example a
long paragraph might split itself between one page and the next.
Packers should set the canv attribute during wrap, split & draw operations to allow
the flowable to work out sizes etc in the proper context.
The "text" of a document usually consists mainly of a sequence of flowables which
flow into a document from top to bottom (with column and page breaks controlled by
higher level components).
"""
import os
from copy import deepcopy, copy
from reportlab.lib.colors import red, gray, lightgrey
from reportlab.lib.rl_accel import fp_str
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY
from reportlab.lib.styles import _baseFontName
from reportlab.lib.utils import strTypes
from reportlab.pdfbase import pdfutils
from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.rl_config import _FUZZ, overlapAttachedSpace, ignoreContainerActions, listWrapOnFakeWidth
import collections
__all__=('TraceInfo','Flowable','XBox','Preformatted','Image','Spacer','PageBreak','SlowPageBreak',
'CondPageBreak','KeepTogether','Macro','CallerMacro','ParagraphAndImage',
'FailOnWrap','HRFlowable','PTOContainer','KeepInFrame','UseUpSpace',
'ListFlowable','ListItem','DDIndenter','LIIndenter',
'DocAssign', 'DocExec', 'DocAssert', 'DocPara', 'DocIf', 'DocWhile',
'PageBreakIfNotEmpty',
)
class TraceInfo:
"Holder for info about where an object originated"
def __init__(self):
self.srcFile = '(unknown)'
self.startLineNo = -1
self.startLinePos = -1
self.endLineNo = -1
self.endLinePos = -1
#############################################################
# Flowable Objects - a base class and a few examples.
# One is just a box to get some metrics. We also have
# a paragraph, an image and a special 'page break'
# object which fills the space.
#############################################################
class Flowable:
"""Abstract base class for things to be drawn. Key concepts:
1. It knows its size
2. It draws in its own coordinate system (this requires the
base API to provide a translate() function.
"""
_fixedWidth = 0 #assume wrap results depend on arguments?
_fixedHeight = 0
def __init__(self):
self.width = 0
self.height = 0
self.wrapped = 0
#these are hints to packers/frames as to how the floable should be positioned
self.hAlign = 'LEFT' #CENTER/CENTRE or RIGHT
self.vAlign = 'BOTTOM' #MIDDLE or TOP
#optional holder for trace info
self._traceInfo = None
self._showBoundary = None
#many flowables handle text and must be processed in the
#absence of a canvas. tagging them with their encoding
#helps us to get conversions right. Use Python codec names.
self.encoding = None
def _drawOn(self,canv):
'''ensure canv is set on and then draw'''
self.canv = canv
self.draw()#this is the bit you overload
del self.canv
def _hAlignAdjust(self,x,sW=0):
if sW and hasattr(self,'hAlign'):
a = self.hAlign
if a in ('CENTER','CENTRE', TA_CENTER):
x += 0.5*sW
elif a in ('RIGHT',TA_RIGHT):
x += sW
elif a not in ('LEFT',TA_LEFT):
raise ValueError("Bad hAlign value "+str(a))
return x
def drawOn(self, canvas, x, y, _sW=0):
"Tell it to draw itself on the canvas. Do not override"
x = self._hAlignAdjust(x,_sW)
canvas.saveState()
canvas.translate(x, y)
self._drawOn(canvas)
if hasattr(self, '_showBoundary') and self._showBoundary:
#diagnostic tool support
canvas.setStrokeColor(gray)
canvas.rect(0,0,self.width, self.height)
canvas.restoreState()
def wrapOn(self, canv, aW, aH):
'''intended for use by packers allows setting the canvas on
during the actual wrap'''
self.canv = canv
w, h = self.wrap(aW,aH)
del self.canv
return w, h
def wrap(self, availWidth, availHeight):
"""This will be called by the enclosing frame before objects
are asked their size, drawn or whatever. It returns the
size actually used."""
return (self.width, self.height)
def minWidth(self):
"""This should return the minimum required width"""
return getattr(self,'_minWidth',self.width)
def splitOn(self, canv, aW, aH):
'''intended for use by packers allows setting the canvas on
during the actual split'''
self.canv = canv
S = self.split(aW,aH)
del self.canv
return S
def split(self, availWidth, availheight):
"""This will be called by more sophisticated frames when
wrap fails. Stupid flowables should return []. Clever flowables
should split themselves and return a list of flowables.
If they decide that nothing useful can be fitted in the
available space (e.g. if you have a table and not enough
space for the first row), also return []"""
return []
def getKeepWithNext(self):
"""returns boolean determining whether the next flowable should stay with this one"""
if hasattr(self,'keepWithNext'): return self.keepWithNext
elif hasattr(self,'style') and hasattr(self.style,'keepWithNext'): return self.style.keepWithNext
else: return 0
def getSpaceAfter(self):
"""returns how much space should follow this item if another item follows on the same page."""
if hasattr(self,'spaceAfter'): return self.spaceAfter
elif hasattr(self,'style') and hasattr(self.style,'spaceAfter'): return self.style.spaceAfter
else: return 0
def getSpaceBefore(self):
"""returns how much space should precede this item if another item precedess on the same page."""
if hasattr(self,'spaceBefore'): return self.spaceBefore
elif hasattr(self,'style') and hasattr(self.style,'spaceBefore'): return self.style.spaceBefore
else: return 0
def isIndexing(self):
"""Hook for IndexingFlowables - things which have cross references"""
return 0
def identity(self, maxLen=None):
'''
This method should attempt to return a string that can be used to identify
a particular flowable uniquely. The result can then be used for debugging
and or error printouts
'''
if hasattr(self, 'getPlainText'):
r = self.getPlainText(identify=1)
elif hasattr(self, 'text'):
r = str(self.text)
else:
r = '...'
if r and maxLen:
r = r[:maxLen]
return "<%s at %s%s>%s" % (self.__class__.__name__, hex(id(self)), self._frameName(), r)
def _doctemplateAttr(self,a):
return getattr(getattr(getattr(self,'canv',None),'_doctemplate',None),a,None)
def _frameName(self):
f = getattr(self,'_frame',None)
if not f: f = self._doctemplateAttr('frame')
if f and f.id: return ' frame=%s' % f.id
return ''
class XBox(Flowable):
"""Example flowable - a box with an x through it and a caption.
This has a known size, so does not need to respond to wrap()."""
def __init__(self, width, height, text = 'A Box'):
Flowable.__init__(self)
self.width = width
self.height = height
self.text = text
def __repr__(self):
return "XBox(w=%s, h=%s, t=%s)" % (self.width, self.height, self.text)
def draw(self):
self.canv.rect(0, 0, self.width, self.height)
self.canv.line(0, 0, self.width, self.height)
self.canv.line(0, self.height, self.width, 0)
#centre the text
self.canv.setFont(_baseFontName,12)
self.canv.drawCentredString(0.5*self.width, 0.5*self.height, self.text)
def _trimEmptyLines(lines):
#don't want the first or last to be empty
while len(lines) and lines[0].strip() == '':
lines = lines[1:]
while len(lines) and lines[-1].strip() == '':
lines = lines[:-1]
return lines
def _dedenter(text,dedent=0):
'''
tidy up text - carefully, it is probably code. If people want to
indent code within a source script, you can supply an arg to dedent
and it will chop off that many character, otherwise it leaves
left edge intact.
'''
lines = text.split('\n')
if dedent>0:
templines = _trimEmptyLines(lines)
lines = []
for line in templines:
line = line[dedent:].rstrip()
lines.append(line)
else:
lines = _trimEmptyLines(lines)
return lines
SPLIT_CHARS = "[{( ,.;:/\\-"
def splitLines(lines, maximum_length, split_characters, new_line_characters):
if split_characters is None:
split_characters = SPLIT_CHARS
if new_line_characters is None:
new_line_characters = ""
# Return a table of lines
lines_splitted = []
for line in lines:
if len(line) > maximum_length:
splitLine(line, lines_splitted, maximum_length, \
split_characters, new_line_characters)
else:
lines_splitted.append(line)
return lines_splitted
def splitLine(line_to_split, lines_splitted, maximum_length, \
split_characters, new_line_characters):
# Used to implement the characters added
#at the beginning of each new line created
first_line = True
# Check if the text can be splitted
while line_to_split and len(line_to_split)>0:
# Index of the character where we can split
split_index = 0
# Check if the line length still exceeds the maximum length
if len(line_to_split) <= maximum_length:
# Return the remaining of the line
split_index = len(line_to_split)
else:
# Iterate for each character of the line
for line_index in range(maximum_length):
# Check if the character is in the list
# of allowed characters to split on
if line_to_split[line_index] in split_characters:
split_index = line_index + 1
# If the end of the line was reached
# with no character to split on
if split_index==0:
split_index = line_index + 1
if first_line:
lines_splitted.append(line_to_split[0:split_index])
first_line = False
maximum_length -= len(new_line_characters)
else:
lines_splitted.append(new_line_characters + \
line_to_split[0:split_index])
# Remaining text to split
line_to_split = line_to_split[split_index:]
class Preformatted(Flowable):
"""This is like the HTML <PRE> tag.
It attempts to display text exactly as you typed it in a fixed width "typewriter" font.
By default the line breaks are exactly where you put them, and it will not be wrapped.
You can optionally define a maximum line length and the code will be wrapped; and
extra characters to be inserted at the beginning of each wrapped line (e.g. '> ').
"""
def __init__(self, text, style, bulletText = None, dedent=0, maxLineLength=None, splitChars=None, newLineChars=""):
"""text is the text to display. If dedent is set then common leading space
will be chopped off the front (for example if the entire text is indented
6 spaces or more then each line will have 6 spaces removed from the front).
"""
self.style = style
self.bulletText = bulletText
self.lines = _dedenter(text,dedent)
if text and maxLineLength:
self.lines = splitLines(
self.lines,
maxLineLength,
splitChars,
newLineChars
)
def __repr__(self):
bT = self.bulletText
H = "Preformatted("
if bT is not None:
H = "Preformatted(bulletText=%s," % repr(bT)
return "%s'''\\ \n%s''')" % (H, '\n'.join(self.lines))
def wrap(self, availWidth, availHeight):
self.width = availWidth
self.height = self.style.leading*len(self.lines)
return (self.width, self.height)
def minWidth(self):
style = self.style
fontSize = style.fontSize
fontName = style.fontName
return max([stringWidth(line,fontName,fontSize) for line in self.lines])
def split(self, availWidth, availHeight):
#returns two Preformatted objects
#not sure why they can be called with a negative height
if availHeight < self.style.leading:
return []
linesThatFit = int(availHeight * 1.0 / self.style.leading)
text1 = '\n'.join(self.lines[0:linesThatFit])
text2 = '\n'.join(self.lines[linesThatFit:])
style = self.style
if style.firstLineIndent != 0:
style = deepcopy(style)
style.firstLineIndent = 0
return [Preformatted(text1, self.style), Preformatted(text2, style)]
def draw(self):
#call another method for historical reasons. Besides, I
#suspect I will be playing with alternate drawing routines
#so not doing it here makes it easier to switch.
cur_x = self.style.leftIndent
cur_y = self.height - self.style.fontSize
self.canv.addLiteral('%PreformattedPara')
if self.style.textColor:
self.canv.setFillColor(self.style.textColor)
tx = self.canv.beginText(cur_x, cur_y)
#set up the font etc.
tx.setFont( self.style.fontName,
self.style.fontSize,
self.style.leading)
for text in self.lines:
tx.textLine(text)
self.canv.drawText(tx)
class Image(Flowable):
"""an image (digital picture). Formats supported by PIL/Java 1.4 (the Python/Java Imaging Library
are supported. Images as flowables may be aligned horizontally in the
frame with the hAlign parameter - accepted values are 'CENTER',
'LEFT' or 'RIGHT' with 'CENTER' being the default.
We allow for two kinds of lazyness to allow for many images in a document
which could lead to file handle starvation.
lazy=1 don't open image until required.
lazy=2 open image when required then shut it.
"""
_fixedWidth = 1
_fixedHeight = 1
def __init__(self, filename, width=None, height=None, kind='direct',
mask="auto", lazy=1, hAlign='CENTER'):
"""If size to draw at not specified, get it from the image."""
self.hAlign = hAlign
self._mask = mask
fp = hasattr(filename,'read')
if fp:
self._file = filename
self.filename = repr(filename)
else:
self._file = self.filename = filename
if not fp and os.path.splitext(filename)[1] in ['.jpg', '.JPG', '.jpeg', '.JPEG']:
# if it is a JPEG, will be inlined within the file -
# but we still need to know its size now
from reportlab.lib.utils import open_for_read
f = open_for_read(filename, 'b')
try:
try:
info = pdfutils.readJPEGInfo(f)
except:
#couldn't read as a JPEG, try like normal
self._setup(width,height,kind,lazy)
return
finally:
f.close()
self.imageWidth = info[0]
self.imageHeight = info[1]
self._img = None
self._setup(width,height,kind,0)
elif fp:
self._setup(width,height,kind,0)
else:
self._setup(width,height,kind,lazy)
def _setup(self,width,height,kind,lazy):
self._lazy = lazy
self._width = width
self._height = height
self._kind = kind
if lazy<=0: self._setup_inner()
def _setup_inner(self):
width = self._width
height = self._height
kind = self._kind
img = self._img
if img: self.imageWidth, self.imageHeight = img.getSize()
if self._lazy>=2: del self._img
if kind in ['direct','absolute']:
self.drawWidth = width or self.imageWidth
self.drawHeight = height or self.imageHeight
elif kind in ['percentage','%']:
self.drawWidth = self.imageWidth*width*0.01
self.drawHeight = self.imageHeight*height*0.01
elif kind in ['bound','proportional']:
factor = min(float(width)/self.imageWidth,float(height)/self.imageHeight)
self.drawWidth = self.imageWidth*factor
self.drawHeight = self.imageHeight*factor
def _restrictSize(self,aW,aH):
if self.drawWidth>aW+_FUZZ or self.drawHeight>aH+_FUZZ:
self._oldDrawSize = self.drawWidth, self.drawHeight
factor = min(float(aW)/self.drawWidth,float(aH)/self.drawHeight)
self.drawWidth *= factor
self.drawHeight *= factor
return self.drawWidth, self.drawHeight
def _unRestrictSize(self):
dwh = getattr(self,'_oldDrawSize',None)
if dwh:
self.drawWidth, self.drawHeight = dwh
def __getattr__(self,a):
if a=='_img':
from reportlab.lib.utils import ImageReader #this may raise an error
self._img = ImageReader(self._file)
if not isinstance(self._file,strTypes):
self._file = None
if self._lazy>=2: self._lazy = 1 #here we're assuming we cannot read again
return self._img
elif a in ('drawWidth','drawHeight','imageWidth','imageHeight'):
self._setup_inner()
return self.__dict__[a]
raise AttributeError("<Image @ 0x%x>.%s" % (id(self),a))
def wrap(self, availWidth, availHeight):
#the caller may decide it does not fit.
return self.drawWidth, self.drawHeight
def draw(self):
lazy = self._lazy
if lazy>=2: self._lazy = 1
self.canv.drawImage( self._img or self.filename,
getattr(self,'_offs_x',0),
getattr(self,'_offs_y',0),
self.drawWidth,
self.drawHeight,
mask=self._mask,
)
if lazy>=2:
self._img = self._file = None
self._lazy = lazy
def identity(self,maxLen=None):
r = Flowable.identity(self,maxLen)
if r[-4:]=='>...' and isinstance(self.filename,str):
r = "%s filename=%s>" % (r[:-4],self.filename)
return r
class NullDraw(Flowable):
def draw(self):
pass
class Spacer(NullDraw):
"""A spacer just takes up space and doesn't draw anything - it guarantees
a gap between objects."""
_fixedWidth = 1
_fixedHeight = 1
def __init__(self, width, height, isGlue=False):
self.width = width
if isGlue:
self.height = 1e-4
self.spacebefore = height
self.height = height
def __repr__(self):
return "%s(%s, %s)" % (self.__class__.__name__,self.width, self.height)
class UseUpSpace(NullDraw):
def __init__(self):
pass
def __repr__(self):
return "%s()" % self.__class__.__name__
def wrap(self, availWidth, availHeight):
self.width = availWidth
self.height = availHeight
return (availWidth,availHeight-1e-8) #step back a point
class PageBreak(UseUpSpace):
"""Move on to the next page in the document.
This works by consuming all remaining space in the frame!"""
def __init__(self,nextTemplate=None):
self.nextTemplate = nextTemplate
class SlowPageBreak(PageBreak):
pass
class PageBreakIfNotEmpty(PageBreak):
pass
class CondPageBreak(Spacer):
"""use up a frame if not enough vertical space effectively CondFrameBreak"""
def __init__(self, height):
self.height = height
def __repr__(self):
return "CondPageBreak(%s)" %(self.height,)
def wrap(self, availWidth, availHeight):
if availHeight<self.height:
f = self._doctemplateAttr('frame')
if not f: return availWidth, availHeight
from reportlab.platypus.doctemplate import FrameBreak
f.add_generated_content(FrameBreak)
return 0, 0
def identity(self,maxLen=None):
return repr(self).replace(')',',frame=%s)'%self._frameName())
def _listWrapOn(F,availWidth,canv,mergeSpace=1,obj=None,dims=None,fakeWidth=None):
'''return max width, required height for a list of flowables F'''
doct = getattr(canv,'_doctemplate',None)
cframe = getattr(doct,'frame',None)
if fakeWidth is None:
fakeWidth = listWrapOnFakeWidth
if cframe:
from reportlab.platypus.doctemplate import _addGeneratedContent, Indenter
doct_frame = cframe
cframe = doct.frame = deepcopy(doct_frame)
cframe._generated_content = None
del cframe._generated_content
try:
W = 0
H = 0
pS = 0
atTop = 1
F = F[:]
while F:
f = F.pop(0)
if hasattr(f,'frameAction'):
from reportlab.platypus.doctemplate import Indenter
if isinstance(f,Indenter):
availWidth -= f.left+f.right
continue
w,h = f.wrapOn(canv,availWidth,0xfffffff)
if dims is not None: dims.append((w,h))
if cframe:
_addGeneratedContent(F,cframe)
if w<=_FUZZ or h<=_FUZZ: continue
W = max(W,min(w,availWidth) if fakeWidth else w)
H += h
if not atTop:
h = f.getSpaceBefore()
if mergeSpace:
if getattr(f,'_SPACETRANSFER',False):
h = pS
h = max(h-pS,0)
H += h
else:
if obj is not None: obj._spaceBefore = f.getSpaceBefore()
atTop = 0
s = f.getSpaceAfter()
if getattr(f,'_SPACETRANSFER',False):
s = pS
pS = s
H += pS
if obj is not None: obj._spaceAfter = pS
return W, H-pS
finally:
if cframe:
doct.frame = doct_frame
def _flowableSublist(V):
"if it isn't a list or tuple, wrap it in a list"
if not isinstance(V,(list,tuple)): V = V is not None and [V] or []
from reportlab.platypus.doctemplate import LCActionFlowable
assert not [x for x in V if isinstance(x,LCActionFlowable)],'LCActionFlowables not allowed in sublists'
return V
class _ContainerSpace: #Abstract some common container like behaviour
def getSpaceBefore(self):
for c in self._content:
if not hasattr(c,'frameAction'):
return c.getSpaceBefore()
return 0
def getSpaceAfter(self,content=None):
#this needs 2.4
#for c in reversed(content or self._content):
reverseContent = (content or self._content)[:]
reverseContent.reverse()
for c in reverseContent:
if not hasattr(c,'frameAction'):
return c.getSpaceAfter()
return 0
class KeepTogether(_ContainerSpace,Flowable):
def __init__(self,flowables,maxHeight=None):
self._content = _flowableSublist(flowables)
self._maxHeight = maxHeight
def __repr__(self):
f = self._content
L = list(map(repr,f))
L = "\n"+"\n".join(L)
L = L.replace("\n", "\n ")
return "%s(%s,maxHeight=%s)" % (self.__class__.__name__,L,self._maxHeight)
def wrap(self, aW, aH):
dims = []
W,H = _listWrapOn(self._content,aW,self.canv,dims=dims)
self._H = H
self._H0 = dims and dims[0][1] or 0
self._wrapInfo = aW,aH
return W, 0xffffff # force a split
def split(self, aW, aH):
if getattr(self,'_wrapInfo',None)!=(aW,aH): self.wrap(aW,aH)
S = self._content[:]
atTop = getattr(self,'_frame',None)
if atTop: atTop = getattr(atTop,'_atTop',None)
C0 = self._H>aH and (not self._maxHeight or aH>self._maxHeight)
C1 = (self._H0>aH) or C0 and atTop
if C0 or C1:
if C0:
from reportlab.platypus.doctemplate import FrameBreak
A = FrameBreak
else:
from reportlab.platypus.doctemplate import NullActionFlowable
A = NullActionFlowable
S.insert(0,A())
return S
def identity(self, maxLen=None):
msg = "<%s at %s%s> containing :%s" % (self.__class__.__name__,hex(id(self)),self._frameName(),"\n".join([f.identity() for f in self._content]))
if maxLen:
return msg[0:maxLen]
else:
return msg
class Macro(Flowable):
"""This is not actually drawn (i.e. it has zero height)
but is executed when it would fit in the frame. Allows direct
access to the canvas through the object 'canvas'"""
def __init__(self, command):
self.command = command
def __repr__(self):
return "Macro(%s)" % repr(self.command)
def wrap(self, availWidth, availHeight):
return (0,0)
def draw(self):
exec(self.command, globals(), {'canvas':self.canv})
def _nullCallable(*args,**kwds):
pass
class CallerMacro(Flowable):
'''
like Macro, but with callable command(s)
drawCallable(self)
wrapCallable(self,aW,aH)
'''
def __init__(self, drawCallable=None, wrapCallable=None):
self._drawCallable = drawCallable or _nullCallable
self._wrapCallable = wrapCallable or _nullCallable
def __repr__(self):
return "CallerMacro(%r,%r)" % (self._drawCallable,self._wrapCallable)
def wrap(self, aW, aH):
self._wrapCallable(self,aW,aH)
return (0,0)
def draw(self):
self._drawCallable(self)
class ParagraphAndImage(Flowable):
'''combine a Paragraph and an Image'''
def __init__(self,P,I,xpad=3,ypad=3,side='right'):
self.P = P
self.I = I
self.xpad = xpad
self.ypad = ypad
self._side = side
def getSpaceBefore(self):
return max(self.P.getSpaceBefore(),self.I.getSpaceBefore())
def getSpaceAfter(self):
return max(self.P.getSpaceAfter(),self.I.getSpaceAfter())
def wrap(self,availWidth,availHeight):
wI, hI = self.I.wrap(availWidth,availHeight)
self.wI = wI
self.hI = hI
# work out widths array for breaking
self.width = availWidth
P = self.P
style = P.style
xpad = self.xpad
ypad = self.ypad
leading = style.leading
leftIndent = style.leftIndent
later_widths = availWidth - leftIndent - style.rightIndent
intermediate_widths = later_widths - xpad - wI
first_line_width = intermediate_widths - style.firstLineIndent
P.width = 0
nIW = int((hI+ypad)/(leading*1.0))
P.blPara = P.breakLines([first_line_width] + nIW*[intermediate_widths]+[later_widths])
if self._side=='left':
self._offsets = [wI+xpad]*(1+nIW)+[0]
P.height = len(P.blPara.lines)*leading
self.height = max(hI,P.height)
return (self.width, self.height)
def split(self,availWidth, availHeight):
P, wI, hI, ypad = self.P, self.wI, self.hI, self.ypad
if hI+ypad>availHeight or len(P.frags)<=0: return []
S = P.split(availWidth,availHeight)
if not S: return S
P = self.P = S[0]
del S[0]
style = P.style
P.height = len(self.P.blPara.lines)*style.leading
self.height = max(hI,P.height)
return [self]+S
def draw(self):
canv = self.canv
if self._side=='left':
self.I.drawOn(canv,0,self.height-self.hI)
self.P._offsets = self._offsets
try:
self.P.drawOn(canv,0,0)
finally:
del self.P._offsets
else:
self.I.drawOn(canv,self.width-self.wI-self.xpad,self.height-self.hI)
self.P.drawOn(canv,0,0)
class FailOnWrap(NullDraw):
def wrap(self, availWidth, availHeight):
raise ValueError("FailOnWrap flowable wrapped and failing as ordered!")
class FailOnDraw(Flowable):
def wrap(self, availWidth, availHeight):
return 0,0
def draw(self):
raise ValueError("FailOnDraw flowable drawn, and failing as ordered!")
class HRFlowable(Flowable):
'''Like the hr tag'''
def __init__(self,
width="80%",
thickness=1,
lineCap='round',
color=lightgrey,
spaceBefore=1, spaceAfter=1,
hAlign='CENTER', vAlign='BOTTOM',
dash=None):
Flowable.__init__(self)
self.width = width
self.lineWidth = thickness
self.lineCap=lineCap
self.spaceBefore = spaceBefore
self.spaceAfter = spaceAfter
self.color = color
self.hAlign = hAlign
self.vAlign = vAlign
self.dash = dash
def __repr__(self):
return "HRFlowable(width=%s, height=%s)" % (self.width, self.height)
def wrap(self, availWidth, availHeight):
w = self.width
if type(w) is type(''):
w = w.strip()
if w.endswith('%'): w = availWidth*float(w[:-1])*0.01
else: w = float(w)
w = min(w,availWidth)
self._width = w
return w, self.lineWidth
def draw(self):
canv = self.canv
canv.saveState()
canv.setLineWidth(self.lineWidth)
canv.setLineCap({'butt':0,'round':1, 'square': 2}[self.lineCap.lower()])
canv.setStrokeColor(self.color)
if self.dash: canv.setDash(self.dash)
canv.line(0, 0, self._width, self.height)
canv.restoreState()
class _PTOInfo:
def __init__(self,trailer,header):
self.trailer = _flowableSublist(trailer)
self.header = _flowableSublist(header)
def cdeepcopy(obj):
if hasattr(obj,'deepcopy'):
return obj.deepcopy()
else:
return deepcopy(obj)
class _Container(_ContainerSpace): #Abstract some common container like behaviour
def drawOn(self, canv, x, y, _sW=0, scale=1.0, content=None, aW=None):
'''we simulate being added to a frame'''
from reportlab.platypus.doctemplate import ActionFlowable, Indenter
x0 = x
y0 = y
pS = 0
if aW is None: aW = self.width
aW *= scale
if content is None:
content = self._content
x = self._hAlignAdjust(x,_sW*scale)
y += self.height*scale
yt = y
frame = getattr(self,'_frame',None)
for c in content:
if not ignoreContainerActions and isinstance(c,ActionFlowable):
c.apply(self.canv._doctemplate)
continue
if isinstance(c,Indenter):
x += c.left*scale
aW -= (c.left+c.right)*scale
continue
w, h = c.wrapOn(canv,aW,0xfffffff)
if (w<_FUZZ or h<_FUZZ) and not getattr(c,'_ZEROSIZE',None): continue
if yt!=y:
s = c.getSpaceBefore()
if not getattr(c,'_SPACETRANSFER',False):
h += max(s-pS,0)
y -= h
fbg = getattr(frame,'_frameBGs',None)
s = c.getSpaceAfter()
if getattr(c,'_SPACETRANSFER',False):
s = pS
pS = s
if fbg:
fbgl, fbgr, fbgc = fbg[-1]
fbw = scale*(frame._width-fbgl-fbgr)
fbh = y + h + pS
fby = max(y0,y-pS)
fbh = max(0,fbh-fby)
if abs(fbw)>_FUZZ and abs(fbh)>_FUZZ:
canv.saveState()
canv.setFillColor(fbgc)
canv.rect(x0+scale*(fbgl-frame._leftPadding)-0.1,fby-0.1,fbw+0.2,fbh+0.2,stroke=0,fill=1)
canv.restoreState()
c._frame = frame
c.drawOn(canv,x,y,_sW=aW-w)
if c is not content[-1] and not getattr(c,'_SPACETRANSFER',None):
y -= pS
del c._frame
def copyContent(self,content=None):
C = [].append
for c in (content or self._content):
C(cdeepcopy(c))
self._content = C.__self__
class PTOContainer(_Container,Flowable):
'''PTOContainer(contentList,trailerList,headerList)
A container for flowables decorated with trailer & header lists.
If the split operation would be called then the trailer and header
lists are injected before and after the split. This allows specialist
"please turn over" and "continued from previous" like behaviours.'''
def __init__(self,content,trailer=None,header=None):
I = _PTOInfo(trailer,header)
self._content = C = []
for _ in _flowableSublist(content):
if isinstance(_,PTOContainer):
C.extend(_._content)
else:
C.append(_)
if not hasattr(_,'_ptoinfo'): _._ptoinfo = I
def wrap(self,availWidth,availHeight):
self.width, self.height = _listWrapOn(self._content,availWidth,self.canv)
return self.width,self.height
def split(self, availWidth, availHeight):
from reportlab.platypus.doctemplate import Indenter
if availHeight<0: return []
canv = self.canv
C = self._content
x = i = H = pS = hx = 0
n = len(C)
I2W = {}
dLeft = dRight = 0
for x in xrange(n):
c = C[x]
I = c._ptoinfo
if I not in I2W.keys():
T = I.trailer
Hdr = I.header
tW, tH = _listWrapOn(T, availWidth, self.canv)
if len(T): #trailer may have no content
tSB = T[0].getSpaceBefore()
else:
tSB = 0
I2W[I] = T,tW,tH,tSB
else:
T,tW,tH,tSB = I2W[I]
_, h = c.wrapOn(canv,availWidth,0xfffffff)
if isinstance(c,Indenter):
dw = c.left+c.right
dLeft += c.left
dRight += c.right
availWidth -= dw
pS = 0
hx = 0
else:
if x:
hx = max(c.getSpaceBefore()-pS,0)
h += hx
pS = c.getSpaceAfter()
H += h+pS
tHS = tH+max(tSB,pS)
if H+tHS>=availHeight-_FUZZ: break
i += 1
#first retract last thing we tried
H -= (h+pS)
#attempt a sub split on the last one we have
aH = (availHeight-H-tHS-hx)*0.99999
if aH>=0.05*availHeight:
SS = c.splitOn(canv,availWidth,aH)
else:
SS = []
if abs(dLeft)+abs(dRight)>1e-8:
R1I = [Indenter(-dLeft,-dRight)]
R2I = [Indenter(dLeft,dRight)]
else:
R1I = R2I = []
if not SS:
j = i
while i>1 and C[i-1].getKeepWithNext():
i -= 1
C[i].keepWithNext = 0
if i==1 and C[0].getKeepWithNext():
#robin's black sheep
i = j
C[0].keepWithNext = 0
F = [UseUpSpace()]