author | rgbecker |
Mon, 19 Nov 2001 11:33:19 +0000 | |
changeset 1428 | 13a13044e9a8 |
parent 1425 | fa9f74f1a701 |
child 1440 | 243d35446390 |
permissions | -rw-r--r-- |
494 | 1 |
#copyright ReportLab Inc. 2000 |
2 |
#see license.txt for license details |
|
3 |
#history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/platypus/doctemplate.py?cvsroot=reportlab |
|
1428 | 4 |
#$Header: /tmp/reportlab/reportlab/platypus/doctemplate.py,v 1.48 2001/11/19 11:33:19 rgbecker Exp $ |
565 | 5 |
|
1428 | 6 |
__version__=''' $Id: doctemplate.py,v 1.48 2001/11/19 11:33:19 rgbecker Exp $ ''' |
565 | 7 |
|
197 | 8 |
__doc__=""" |
268 | 9 |
This module contains the core structure of platypus. |
10 |
||
550 | 11 |
Platypus constructs documents. Document styles are determined by DocumentTemplates. |
268 | 12 |
|
13 |
Each DocumentTemplate contains one or more PageTemplates which defines the look of the |
|
14 |
pages of the document. |
|
15 |
||
16 |
Each PageTemplate has a procedure for drawing the "non-flowing" part of the page |
|
17 |
(for example the header, footer, page number, fixed logo graphic, watermark, etcetera) and |
|
18 |
a set of Frames which enclose the flowing part of the page (for example the paragraphs, |
|
19 |
tables, or non-fixed diagrams of the text). |
|
20 |
||
21 |
A document is built when a DocumentTemplate is fed a sequence of Flowables. |
|
22 |
The action of the build consumes the flowables in order and places them onto |
|
23 |
frames on pages as space allows. When a frame runs out of space the next frame |
|
24 |
of the page is used. If no frame remains a new page is created. A new page |
|
25 |
can also be created if a page break is forced. |
|
26 |
||
27 |
The special invisible flowable NextPageTemplate can be used to specify |
|
28 |
the page template for the next page (which by default is the one being used |
|
29 |
for the current frame). |
|
197 | 30 |
""" |
565 | 31 |
|
279 | 32 |
from reportlab.platypus.flowables import * |
33 |
from reportlab.platypus.paragraph import Paragraph |
|
34 |
from reportlab.platypus.frames import Frame |
|
1131 | 35 |
from reportlab.rl_config import defaultPageSize, _verbose |
279 | 36 |
import reportlab.lib.sequencer |
565 | 37 |
|
197 | 38 |
from types import * |
39 |
import sys |
|
40 |
||
565 | 41 |
|
253 | 42 |
def _doNothing(canvas, doc): |
550 | 43 |
"Dummy callback for onPage" |
44 |
pass |
|
512 | 45 |
|
565 | 46 |
|
512 | 47 |
class IndexingFlowable0(Flowable): |
550 | 48 |
"""Abstract interface definition for flowables which might |
49 |
hold references to other pages or themselves be targets |
|
50 |
of cross-references. XRefStart, XRefDest, Table of Contents, |
|
51 |
Indexes etc.""" |
|
52 |
def isIndexing(self): |
|
53 |
return 1 |
|
512 | 54 |
|
550 | 55 |
def isSatisfied(self): |
56 |
return 1 |
|
512 | 57 |
|
550 | 58 |
def notify(self, kind, stuff): |
59 |
"""This will be called by the framework wherever 'stuff' happens. |
|
60 |
'kind' will be a value that can be used to decide whether to |
|
61 |
pay attention or not.""" |
|
62 |
pass |
|
512 | 63 |
|
550 | 64 |
def beforeBuild(self): |
65 |
"""Called by multiBuild before it starts; use this to clear |
|
66 |
old contents""" |
|
67 |
pass |
|
1428 | 68 |
|
550 | 69 |
def afterBuild(self): |
70 |
"""Called after build ends but before isSatisfied""" |
|
71 |
pass |
|
253 | 72 |
|
565 | 73 |
|
197 | 74 |
class ActionFlowable(Flowable): |
550 | 75 |
'''This Flowable is never drawn, it can be used for data driven controls |
76 |
For example to change a page template (from one column to two, for example) |
|
77 |
use NextPageTemplate which creates an ActionFlowable. |
|
78 |
''' |
|
1324 | 79 |
def __init__(self,action=()): |
550 | 80 |
if type(action) not in (ListType, TupleType): |
81 |
action = (action,) |
|
1324 | 82 |
self.action = tuple(action) |
197 | 83 |
|
550 | 84 |
def wrap(self, availWidth, availHeight): |
85 |
'''Should never be called.''' |
|
86 |
raise NotImplementedError |
|
197 | 87 |
|
550 | 88 |
def draw(self): |
89 |
'''Should never be called.''' |
|
90 |
raise NotImplementedError |
|
197 | 91 |
|
550 | 92 |
def apply(self,doc): |
93 |
''' |
|
94 |
This is called by the doc.build processing to allow the instance to |
|
95 |
implement its behaviour |
|
96 |
''' |
|
97 |
action = self.action[0] |
|
98 |
args = tuple(self.action[1:]) |
|
99 |
arn = 'handle_'+action |
|
100 |
try: |
|
101 |
apply(getattr(doc,arn), args) |
|
102 |
except AttributeError, aerr: |
|
103 |
if aerr.args[0]==arn: |
|
104 |
raise NotImplementedError, "Can't handle ActionFlowable(%s)" % action |
|
105 |
else: |
|
106 |
raise |
|
107 |
except "bogus": |
|
108 |
t, v, None = sys.exc_info() |
|
109 |
raise t, "%s\n handle_%s args=%s"%(v,action,args) |
|
197 | 110 |
|
550 | 111 |
def __call__(self): |
112 |
return self |
|
218
274db2129c04
Fixes/Changes to get testplatypus to work with new framework
rgbecker
parents:
214
diff
changeset
|
113 |
|
1324 | 114 |
class NextFrameFlowable(ActionFlowable): |
115 |
def __init__(self,ix,resume=0): |
|
116 |
ActionFlowable.__init__(self,('nextFrame',ix,resume)) |
|
565 | 117 |
|
1324 | 118 |
class CurrentFrameFlowable(ActionFlowable): |
119 |
def __init__(self,ix,resume=0): |
|
120 |
ActionFlowable.__init__(self,('currentFrame',ix,resume)) |
|
121 |
||
122 |
class _FrameBreak(ActionFlowable): |
|
123 |
''' |
|
124 |
A special ActionFlowable that allows setting doc._nextFrameIndex |
|
125 |
||
126 |
eg story.append(FrameBreak('mySpecialFrame')) |
|
127 |
''' |
|
128 |
def __call__(self,ix=None,resume=0): |
|
129 |
r = self.__class__(self.action+(resume,)) |
|
130 |
r._ix = ix |
|
131 |
return r |
|
132 |
||
133 |
def apply(self,doc): |
|
134 |
if getattr(self,'_ix',None): doc._nextFrameIndex = self._ix |
|
135 |
ActionFlowable.apply(self,doc) |
|
136 |
||
137 |
FrameBreak = _FrameBreak('frameEnd') |
|
197 | 138 |
PageBegin = ActionFlowable('pageBegin') |
139 |
||
512 | 140 |
|
197 | 141 |
class NextPageTemplate(ActionFlowable): |
550 | 142 |
"""When you get to the next page, use the template specified (change to two column, for example) """ |
143 |
def __init__(self,pt): |
|
144 |
ActionFlowable.__init__(self,('nextPageTemplate',pt)) |
|
197 | 145 |
|
565 | 146 |
|
197 | 147 |
class PageTemplate: |
550 | 148 |
""" |
149 |
essentially a list of Frames and an onPage routine to call at the start |
|
150 |
of a page when this is selected. onPageEnd gets called at the end. |
|
151 |
derived classes can also implement beforeDrawPage and afterDrawPage if they want |
|
152 |
""" |
|
153 |
def __init__(self,id=None,frames=[],onPage=_doNothing, onPageEnd=_doNothing, |
|
684 | 154 |
pagesize=defaultPageSize): |
550 | 155 |
if type(frames) not in (ListType,TupleType): frames = [frames] |
156 |
assert filter(lambda x: not isinstance(x,Frame), frames)==[], "frames argument error" |
|
157 |
self.id = id |
|
158 |
self.frames = frames |
|
159 |
self.onPage = onPage |
|
160 |
self.onPageEnd = onPageEnd |
|
161 |
self.pagesize = pagesize |
|
512 | 162 |
|
550 | 163 |
def beforeDrawPage(self,canv,doc): |
164 |
"""Override this if you want additional functionality or prefer |
|
165 |
a class based page routine. Called before any flowables for |
|
166 |
this page are processed.""" |
|
167 |
pass |
|
197 | 168 |
|
936 | 169 |
def checkPageSize(self,canv,doc): |
1267
118eabbf5ba4
Added template pagesize args in SimpleDoc.__init__ as suggested by D Horkoff
rgbecker
parents:
1222
diff
changeset
|
170 |
'''This gets called by the template framework |
118eabbf5ba4
Added template pagesize args in SimpleDoc.__init__ as suggested by D Horkoff
rgbecker
parents:
1222
diff
changeset
|
171 |
If canv size != doc size then the canv size is set to |
1428 | 172 |
the template size or if that's not available to the |
1267
118eabbf5ba4
Added template pagesize args in SimpleDoc.__init__ as suggested by D Horkoff
rgbecker
parents:
1222
diff
changeset
|
173 |
doc size. |
118eabbf5ba4
Added template pagesize args in SimpleDoc.__init__ as suggested by D Horkoff
rgbecker
parents:
1222
diff
changeset
|
174 |
''' |
118eabbf5ba4
Added template pagesize args in SimpleDoc.__init__ as suggested by D Horkoff
rgbecker
parents:
1222
diff
changeset
|
175 |
#### NEVER EVER EVER COMPARE FLOATS FOR EQUALITY |
118eabbf5ba4
Added template pagesize args in SimpleDoc.__init__ as suggested by D Horkoff
rgbecker
parents:
1222
diff
changeset
|
176 |
#RGB converting pagesizes to ints means we are accurate to one point |
118eabbf5ba4
Added template pagesize args in SimpleDoc.__init__ as suggested by D Horkoff
rgbecker
parents:
1222
diff
changeset
|
177 |
#RGB I suggest we should be aiming a little better |
1222
e52d533376bc
platypus bug where platypus would mess up the pagesize of the canvas fixed.
aaron_watters
parents:
1131
diff
changeset
|
178 |
cp = None |
e52d533376bc
platypus bug where platypus would mess up the pagesize of the canvas fixed.
aaron_watters
parents:
1131
diff
changeset
|
179 |
dp = None |
e52d533376bc
platypus bug where platypus would mess up the pagesize of the canvas fixed.
aaron_watters
parents:
1131
diff
changeset
|
180 |
sp = None |
e52d533376bc
platypus bug where platypus would mess up the pagesize of the canvas fixed.
aaron_watters
parents:
1131
diff
changeset
|
181 |
if canv._pagesize: cp = map(int, canv._pagesize) |
e52d533376bc
platypus bug where platypus would mess up the pagesize of the canvas fixed.
aaron_watters
parents:
1131
diff
changeset
|
182 |
if self.pagesize: sp = map(int, self.pagesize) |
e52d533376bc
platypus bug where platypus would mess up the pagesize of the canvas fixed.
aaron_watters
parents:
1131
diff
changeset
|
183 |
if doc.pagesize: dp = map(int, doc.pagesize) |
1268 | 184 |
if cp!=sp: |
1222
e52d533376bc
platypus bug where platypus would mess up the pagesize of the canvas fixed.
aaron_watters
parents:
1131
diff
changeset
|
185 |
if sp: |
936 | 186 |
canv.setPageSize(self.pagesize) |
1268 | 187 |
elif cp!=dp: |
936 | 188 |
canv.setPageSize(doc.pagesize) |
189 |
||
550 | 190 |
def afterDrawPage(self, canv, doc): |
191 |
"""This is called after the last flowable for the page has |
|
192 |
been processed. You might use this if the page header or |
|
193 |
footer needed knowledge of what flowables were drawn on |
|
194 |
this page.""" |
|
195 |
pass |
|
1428 | 196 |
|
565 | 197 |
|
512 | 198 |
class BaseDocTemplate: |
550 | 199 |
""" |
200 |
First attempt at defining a document template class. |
|
512 | 201 |
|
550 | 202 |
The basic idea is simple. |
203 |
0) The document has a list of data associated with it |
|
204 |
this data should derive from flowables. We'll have |
|
205 |
special classes like PageBreak, FrameBreak to do things |
|
206 |
like forcing a page end etc. |
|
512 | 207 |
|
550 | 208 |
1) The document has one or more page templates. |
512 | 209 |
|
550 | 210 |
2) Each page template has one or more frames. |
512 | 211 |
|
550 | 212 |
3) The document class provides base methods for handling the |
213 |
story events and some reasonable methods for getting the |
|
214 |
story flowables into the frames. |
|
214 | 215 |
|
550 | 216 |
4) The document instances can override the base handler routines. |
1428 | 217 |
|
550 | 218 |
Most of the methods for this class are not called directly by the user, |
219 |
but in some advanced usages they may need to be overridden via subclassing. |
|
1428 | 220 |
|
550 | 221 |
EXCEPTION: doctemplate.build(...) must be called for most reasonable uses |
222 |
since it builds a document using the page template. |
|
1428 | 223 |
|
550 | 224 |
Each document template builds exactly one document into a file specified |
225 |
by the filename argument on initialization. |
|
197 | 226 |
|
550 | 227 |
Possible keyword arguments for the initialization: |
1428 | 228 |
|
550 | 229 |
pageTemplates: A list of templates. Must be nonempty. Names |
230 |
assigned to the templates are used for referring to them so no two used |
|
231 |
templates should have the same name. For example you might want one template |
|
232 |
for a title page, one for a section first page, one for a first page of |
|
233 |
a chapter and two more for the interior of a chapter on odd and even pages. |
|
234 |
If this argument is omitted then at least one pageTemplate should be provided |
|
235 |
using the addPageTemplates method before the document is built. |
|
236 |
showBoundary: if set draw a box around the frame boundaries. |
|
237 |
leftMargin: |
|
238 |
rightMargin: |
|
239 |
topMargin: |
|
240 |
bottomMargin: Margin sizes in points (default 1 inch) |
|
241 |
These margins may be overridden by the pageTemplates. They are primarily of interest |
|
242 |
for the SimpleDocumentTemplate subclass. |
|
243 |
allowSplitting: If set flowables (eg, paragraphs) may be split across frames or pages |
|
244 |
(default: 1) |
|
245 |
title: Internal title for document (does not automatically display on any page) |
|
246 |
author: Internal author for document (does not automatically display on any page) |
|
247 |
""" |
|
684 | 248 |
_initArgs = { 'pagesize':defaultPageSize, |
550 | 249 |
'pageTemplates':[], |
250 |
'showBoundary':0, |
|
251 |
'leftMargin':inch, |
|
252 |
'rightMargin':inch, |
|
253 |
'topMargin':inch, |
|
254 |
'bottomMargin':inch, |
|
255 |
'allowSplitting':1, |
|
256 |
'title':None, |
|
257 |
'author':None, |
|
258 |
'_pageBreakQuick':1} |
|
259 |
_invalidInitArgs = () |
|
197 | 260 |
|
550 | 261 |
def __init__(self, filename, **kw): |
262 |
"""create a document template bound to a filename (see class documentation for keyword arguments)""" |
|
263 |
self.filename = filename |
|
512 | 264 |
|
550 | 265 |
for k in self._initArgs.keys(): |
266 |
if not kw.has_key(k): |
|
267 |
v = self._initArgs[k] |
|
268 |
else: |
|
269 |
if k in self._invalidInitArgs: |
|
270 |
raise ValueError, "Invalid argument %s" % k |
|
271 |
v = kw[k] |
|
272 |
setattr(self,k,v) |
|
1222
e52d533376bc
platypus bug where platypus would mess up the pagesize of the canvas fixed.
aaron_watters
parents:
1131
diff
changeset
|
273 |
#print "pagesize is", self.pagesize |
512 | 274 |
|
550 | 275 |
p = self.pageTemplates |
276 |
self.pageTemplates = [] |
|
277 |
self.addPageTemplates(p) |
|
310 | 278 |
|
550 | 279 |
# facility to assist multi-build and cross-referencing. |
280 |
# various hooks can put things into here - key is what |
|
281 |
# you want, value is a page number. This can then be |
|
282 |
# passed to indexing flowables. |
|
283 |
self._pageRefs = {} |
|
284 |
self._indexingFlowables = [] |
|
1428 | 285 |
|
550 | 286 |
self._calc() |
287 |
self.afterInit() |
|
512 | 288 |
|
550 | 289 |
def _calc(self): |
290 |
self._rightMargin = self.pagesize[0] - self.rightMargin |
|
291 |
self._topMargin = self.pagesize[1] - self.topMargin |
|
292 |
self.width = self._rightMargin - self.leftMargin |
|
293 |
self.height = self._topMargin - self.bottomMargin |
|
512 | 294 |
|
295 |
||
550 | 296 |
def clean_hanging(self): |
297 |
'handle internal postponed actions' |
|
298 |
while len(self._hanging): |
|
299 |
self.handle_flowable(self._hanging) |
|
197 | 300 |
|
550 | 301 |
def addPageTemplates(self,pageTemplates): |
302 |
'add one or a sequence of pageTemplates' |
|
303 |
if type(pageTemplates) not in (ListType,TupleType): |
|
304 |
pageTemplates = [pageTemplates] |
|
305 |
#this test below fails due to inconsistent imports! |
|
306 |
#assert filter(lambda x: not isinstance(x,PageTemplate), pageTemplates)==[], "pageTemplates argument error" |
|
307 |
for t in pageTemplates: |
|
308 |
self.pageTemplates.append(t) |
|
1428 | 309 |
|
550 | 310 |
def handle_documentBegin(self): |
311 |
'''implement actions at beginning of document''' |
|
312 |
self._hanging = [PageBegin] |
|
313 |
self.pageTemplate = self.pageTemplates[0] |
|
314 |
self.page = 0 |
|
315 |
self.beforeDocument() |
|
253 | 316 |
|
550 | 317 |
def handle_pageBegin(self): |
318 |
'''Perform actions required at beginning of page. |
|
319 |
shouldn't normally be called directly''' |
|
320 |
self.page = self.page + 1 |
|
321 |
self.pageTemplate.beforeDrawPage(self.canv,self) |
|
936 | 322 |
self.pageTemplate.checkPageSize(self.canv,self) |
550 | 323 |
self.pageTemplate.onPage(self.canv,self) |
1324 | 324 |
for f in self.pageTemplate.frames: f._reset() |
550 | 325 |
self.beforePage() |
326 |
if hasattr(self,'_nextFrameIndex'): |
|
327 |
del self._nextFrameIndex |
|
328 |
self.frame = self.pageTemplate.frames[0] |
|
329 |
self.handle_frameBegin() |
|
197 | 330 |
|
550 | 331 |
def handle_pageEnd(self): |
332 |
''' show the current page |
|
333 |
check the next page template |
|
334 |
hang a page begin |
|
335 |
''' |
|
336 |
self.pageTemplate.afterDrawPage(self.canv, self) |
|
337 |
self.pageTemplate.onPageEnd(self.canv, self) |
|
338 |
self.afterPage() |
|
339 |
self.canv.showPage() |
|
340 |
if hasattr(self,'_nextPageTemplateIndex'): |
|
341 |
self.pageTemplate = self.pageTemplates[self._nextPageTemplateIndex] |
|
342 |
del self._nextPageTemplateIndex |
|
343 |
self._hanging.append(PageBegin) |
|
197 | 344 |
|
550 | 345 |
def handle_pageBreak(self): |
346 |
'''some might choose not to end all the frames''' |
|
347 |
if self._pageBreakQuick: |
|
348 |
self.handle_pageEnd() |
|
349 |
else: |
|
350 |
n = len(self._hanging) |
|
351 |
while len(self._hanging)==n: |
|
352 |
self.handle_frameEnd() |
|
512 | 353 |
|
1324 | 354 |
def handle_frameBegin(self,resume=0): |
355 |
'''What to do at the beginning of a frame''' |
|
356 |
f = self.frame |
|
357 |
if f._atTop: |
|
358 |
if self.showBoundary or self.frame.showBoundary: |
|
359 |
self.frame.drawBoundary(self.canv) |
|
197 | 360 |
|
1324 | 361 |
def handle_frameEnd(self,resume=0): |
550 | 362 |
''' Handles the semantics of the end of a frame. This includes the selection of |
363 |
the next frame or if this is the last frame then invoke pageEnd. |
|
364 |
''' |
|
365 |
if hasattr(self,'_nextFrameIndex'): |
|
366 |
frame = self.pageTemplate.frames[self._nextFrameIndex] |
|
367 |
del self._nextFrameIndex |
|
1324 | 368 |
self.handle_frameBegin(resume) |
550 | 369 |
elif hasattr(self.frame,'lastFrame') or self.frame is self.pageTemplate.frames[-1]: |
370 |
self.handle_pageEnd() |
|
371 |
self.frame = None |
|
372 |
else: |
|
373 |
f = self.frame |
|
374 |
self.frame = self.pageTemplate.frames[self.pageTemplate.frames.index(f) + 1] |
|
375 |
self.handle_frameBegin() |
|
197 | 376 |
|
550 | 377 |
def handle_nextPageTemplate(self,pt): |
378 |
'''On endPage chenge to the page template with name or index pt''' |
|
379 |
if type(pt) is StringType: |
|
380 |
for t in self.pageTemplates: |
|
381 |
if t.id == pt: |
|
382 |
self._nextPageTemplateIndex = self.pageTemplates.index(t) |
|
383 |
return |
|
384 |
raise ValueError, "can't find template('%s')"%pt |
|
385 |
elif type(pt) is IntType: |
|
386 |
self._nextPageTemplateIndex = pt |
|
387 |
else: |
|
388 |
raise TypeError, "argument pt should be string or integer" |
|
197 | 389 |
|
550 | 390 |
def handle_nextFrame(self,fx): |
391 |
'''On endFrame chenge to the frame with name or index fx''' |
|
392 |
if type(fx) is StringType: |
|
393 |
for f in self.pageTemplate.frames: |
|
394 |
if f.id == fx: |
|
395 |
self._nextFrameIndex = self.pageTemplate.frames.index(f) |
|
396 |
return |
|
397 |
raise ValueError, "can't find frame('%s')"%fx |
|
398 |
elif type(fx) is IntType: |
|
399 |
self._nextFrameIndex = fx |
|
400 |
else: |
|
401 |
raise TypeError, "argument fx should be string or integer" |
|
512 | 402 |
|
550 | 403 |
def handle_currentFrame(self,fx): |
404 |
'''chenge to the frame with name or index fx''' |
|
405 |
if type(fx) is StringType: |
|
406 |
for f in self.pageTemplate.frames: |
|
407 |
if f.id == fx: |
|
408 |
self._nextFrameIndex = self.pageTemplate.frames.index(f) |
|
409 |
return |
|
410 |
raise ValueError, "can't find frame('%s')"%fx |
|
411 |
elif type(fx) is IntType: |
|
412 |
self._nextFrameIndex = fx |
|
413 |
else: |
|
414 |
raise TypeError, "argument fx should be string or integer" |
|
197 | 415 |
|
1425 | 416 |
def handle_breakBefore(self, flowables): |
417 |
'''preprocessing step to allow pageBreakBefore and frameBreakBefore attributes''' |
|
418 |
first = flowables[0] |
|
419 |
# if we insert a page break before, we'll process that, see it again, |
|
420 |
# and go in an infinite loop. So we need to set a flag on the object |
|
421 |
# saying 'skip me'. This should be unset on the next pass |
|
422 |
if hasattr(first, '_skipMeNextTime'): |
|
423 |
delattr(first, '_skipMeNextTime') |
|
424 |
return |
|
425 |
# this could all be made much quicker by putting the attributes |
|
426 |
# in to the flowables with a defult value of 0 |
|
427 |
if hasattr(first,'pageBreakBefore') and first.pageBreakBefore == 1: |
|
428 |
first._skipMeNextTime = 1 |
|
429 |
first.insert(0, PageBreak()) |
|
430 |
return |
|
431 |
if hasattr(first,'style') and hasattr(first.style, 'pageBreakBefore') and first.style.pageBreakBefore == 1: |
|
432 |
first._skipMeNextTime = 1 |
|
433 |
flowables.insert(0, PageBreak()) |
|
434 |
return |
|
435 |
if hasattr(first,'frameBreakBefore') and first.frameBreakBefore == 1: |
|
436 |
first._skipMeNextTime = 1 |
|
437 |
flowables.insert(0, FrameBreak()) |
|
438 |
return |
|
439 |
if hasattr(first,'style') and hasattr(first.style, 'frameBreakBefore') and first.style.frameBreakBefore == 1: |
|
440 |
first._skipMeNextTime = 1 |
|
441 |
flowables.insert(0, FrameBreak()) |
|
442 |
return |
|
1428 | 443 |
|
444 |
||
1425 | 445 |
def handle_keepWithNext(self, flowables): |
446 |
"implements keepWithNext" |
|
1428 | 447 |
i = 0 |
448 |
n = len(flowables) |
|
449 |
while i<n and flowables[i].getKeepWithNext(): i = i + 1 |
|
450 |
if i: |
|
451 |
i = i + 1 |
|
452 |
K = KeepTogether(flowables[:i]) |
|
453 |
for f in K._flowables: |
|
454 |
f.keepWithNext = 0 |
|
455 |
del flowables[:i] |
|
456 |
flowables.insert(0,K) |
|
1425 | 457 |
|
550 | 458 |
def handle_flowable(self,flowables): |
459 |
'''try to handle one flowable from the front of list flowables.''' |
|
1428 | 460 |
|
550 | 461 |
#allow document a chance to look at, modify or ignore |
462 |
#the object(s) about to be processed |
|
463 |
self.filterFlowables(flowables) |
|
1428 | 464 |
|
1425 | 465 |
self.handle_breakBefore(flowables) |
466 |
self.handle_keepWithNext(flowables) |
|
550 | 467 |
f = flowables[0] |
468 |
del flowables[0] |
|
469 |
if f is None: |
|
470 |
return |
|
197 | 471 |
|
550 | 472 |
if isinstance(f,PageBreak): |
473 |
self.handle_pageBreak() |
|
474 |
self.afterFlowable(f) |
|
475 |
elif isinstance(f,ActionFlowable): |
|
476 |
f.apply(self) |
|
477 |
self.afterFlowable(f) |
|
478 |
else: |
|
1425 | 479 |
#try to fit it then draw it |
550 | 480 |
if self.frame.add(f, self.canv, trySplit=self.allowSplitting): |
481 |
self.afterFlowable(f) |
|
482 |
else: |
|
1425 | 483 |
#if isinstance(f, KeepTogether): print 'could not add it to frame' |
550 | 484 |
if self.allowSplitting: |
485 |
# see if this is a splittable thing |
|
486 |
S = self.frame.split(f,self.canv) |
|
487 |
n = len(S) |
|
488 |
else: |
|
489 |
n = 0 |
|
1425 | 490 |
#if isinstance(f, KeepTogether): print 'n=%d' % n |
550 | 491 |
if n: |
492 |
if self.frame.add(S[0], self.canv, trySplit=0): |
|
551 | 493 |
self.afterFlowable(S[0]) |
550 | 494 |
else: |
1425 | 495 |
print 'n = %d' % n |
1103 | 496 |
raise "LayoutError", "splitting error on page %d in\n%s" % (self.page,f.identity(30)) |
550 | 497 |
del S[0] |
498 |
for f in xrange(n-1): |
|
499 |
flowables.insert(f,S[f]) # put split flowables back on the list |
|
500 |
else: |
|
501 |
# this must be cleared when they are finally drawn! |
|
698
864265047890
Changed attribute postponed to _postponed in doctemplate.py.
dinu_gherman
parents:
684
diff
changeset
|
502 |
## if hasattr(f,'postponed'): |
864265047890
Changed attribute postponed to _postponed in doctemplate.py.
dinu_gherman
parents:
684
diff
changeset
|
503 |
if hasattr(f,'_postponed'): |
1103 | 504 |
message = "Flowable %s too large on page %d" % (f.identity(30), self.page) |
550 | 505 |
#show us, it might be handy |
506 |
#HACK = it seems within tables we sometimes |
|
507 |
#get an empty paragraph that won't fit and this |
|
508 |
#causes it to fall over. FIXME FIXME FIXME |
|
509 |
raise "LayoutError", message |
|
698
864265047890
Changed attribute postponed to _postponed in doctemplate.py.
dinu_gherman
parents:
684
diff
changeset
|
510 |
## f.postponed = 1 |
864265047890
Changed attribute postponed to _postponed in doctemplate.py.
dinu_gherman
parents:
684
diff
changeset
|
511 |
f._postponed = 1 |
550 | 512 |
flowables.insert(0,f) # put the flowable back |
513 |
self.handle_frameEnd() |
|
197 | 514 |
|
550 | 515 |
#these are provided so that deriving classes can refer to them |
516 |
_handle_documentBegin = handle_documentBegin |
|
517 |
_handle_pageBegin = handle_pageBegin |
|
518 |
_handle_pageEnd = handle_pageEnd |
|
519 |
_handle_frameBegin = handle_frameBegin |
|
520 |
_handle_frameEnd = handle_frameEnd |
|
521 |
_handle_flowable = handle_flowable |
|
522 |
_handle_nextPageTemplate = handle_nextPageTemplate |
|
523 |
_handle_currentFrame = handle_currentFrame |
|
524 |
_handle_nextFrame = handle_nextFrame |
|
197 | 525 |
|
550 | 526 |
def _startBuild(self, filename=None, canvasmaker=canvas.Canvas): |
527 |
self._calc() |
|
528 |
self.canv = canvasmaker(filename or self.filename,pagesize=self.pagesize) |
|
529 |
self.handle_documentBegin() |
|
512 | 530 |
|
550 | 531 |
def _endBuild(self): |
532 |
if self._hanging!=[] and self._hanging[-1] is PageBegin: |
|
533 |
del self._hanging[-1] |
|
534 |
self.clean_hanging() |
|
535 |
else: |
|
536 |
self.clean_hanging() |
|
537 |
self.handle_pageBreak() |
|
512 | 538 |
|
550 | 539 |
self.canv.save() |
540 |
#AR - hack - for some reason a document did not |
|
541 |
#have these: |
|
542 |
#if hasattr(self, 'frame'): del self.frame |
|
543 |
#if hasattr(self, 'pageTemplate'): del self.pageTemplate |
|
544 |
#del self.frame, self.pageTemplate |
|
218
274db2129c04
Fixes/Changes to get testplatypus to work with new framework
rgbecker
parents:
214
diff
changeset
|
545 |
|
550 | 546 |
def build(self, flowables, filename=None, canvasmaker=canvas.Canvas): |
547 |
"""Build the document from a list of flowables. |
|
548 |
If the filename argument is provided then that filename is used |
|
549 |
rather than the one provided upon initialization. |
|
550 |
If the canvasmaker argument is provided then it will be used |
|
551 |
instead of the default. For example a slideshow might use |
|
552 |
an alternate canvas which places 6 slides on a page (by |
|
553 |
doing translations, scalings and redefining the page break |
|
554 |
operations). |
|
555 |
""" |
|
556 |
#assert filter(lambda x: not isinstance(x,Flowable), flowables)==[], "flowables argument error" |
|
557 |
self._startBuild(filename,canvasmaker) |
|
512 | 558 |
|
550 | 559 |
while len(flowables): |
560 |
self.clean_hanging() |
|
561 |
self.handle_flowable(flowables) |
|
512 | 562 |
|
550 | 563 |
self._endBuild() |
512 | 564 |
|
550 | 565 |
def _allSatisfied0(self): |
566 |
"""Called by multi-build - are all cross-references resolved?""" |
|
567 |
allHappy = 1 |
|
568 |
for f in self._indexingFlowables: |
|
569 |
if not f.isSatisfied(): |
|
570 |
allHappy = 0 |
|
571 |
break |
|
1428 | 572 |
return allHappy |
197 | 573 |
|
550 | 574 |
def notify0(self, kind, stuff): |
575 |
""""Forward to any listeners""" |
|
576 |
for l in self._indexingFlowables: |
|
577 |
l.notify(kind, stuff) |
|
1428 | 578 |
|
550 | 579 |
def pageRef0(self, label): |
580 |
"""hook to register a page number""" |
|
1131 | 581 |
if _verbose: print "pageRef called with label '%s' on page %d" % ( |
550 | 582 |
label, self.page) |
583 |
self._pageRefs[label] = self.page |
|
1428 | 584 |
|
550 | 585 |
def multiBuild0(self, story, |
586 |
filename=None, |
|
587 |
canvasmaker=canvas.Canvas, |
|
588 |
maxPasses = 10): |
|
589 |
"""Makes multiple passes until all indexing flowables |
|
590 |
are happy.""" |
|
591 |
self._indexingFlowables = [] |
|
592 |
#scan the story and keep a copy |
|
593 |
for thing in story: |
|
594 |
if thing.isIndexing(): |
|
595 |
self._indexingFlowables.append(thing) |
|
596 |
#print 'scanned story, found these indexing flowables:\n' |
|
597 |
#print self._indexingFlowables |
|
197 | 598 |
|
550 | 599 |
passes = 0 |
600 |
while 1: |
|
601 |
passes = passes + 1 |
|
1131 | 602 |
if _verbose: print 'building pass '+str(passes) + '...', |
197 | 603 |
|
550 | 604 |
for fl in self._indexingFlowables: |
605 |
fl.beforeBuild() |
|
218
274db2129c04
Fixes/Changes to get testplatypus to work with new framework
rgbecker
parents:
214
diff
changeset
|
606 |
|
550 | 607 |
# work with a copy of the story, since it is consumed |
608 |
tempStory = story[:] |
|
609 |
self.build(tempStory, filename, canvasmaker) |
|
610 |
#self.notify0('debug',None) |
|
512 | 611 |
|
550 | 612 |
#clean up so multi-build does not go wrong - the frame |
613 |
#packer might have tacked an attribute onto some |
|
614 |
#paragraphs |
|
615 |
for elem in story: |
|
698
864265047890
Changed attribute postponed to _postponed in doctemplate.py.
dinu_gherman
parents:
684
diff
changeset
|
616 |
## if hasattr(elem, 'postponed'): |
864265047890
Changed attribute postponed to _postponed in doctemplate.py.
dinu_gherman
parents:
684
diff
changeset
|
617 |
## del elem.postponed |
864265047890
Changed attribute postponed to _postponed in doctemplate.py.
dinu_gherman
parents:
684
diff
changeset
|
618 |
if hasattr(elem, '_postponed'): |
864265047890
Changed attribute postponed to _postponed in doctemplate.py.
dinu_gherman
parents:
684
diff
changeset
|
619 |
del elem._postponed |
218
274db2129c04
Fixes/Changes to get testplatypus to work with new framework
rgbecker
parents:
214
diff
changeset
|
620 |
|
550 | 621 |
for fl in self._indexingFlowables: |
622 |
fl.afterBuild() |
|
218
274db2129c04
Fixes/Changes to get testplatypus to work with new framework
rgbecker
parents:
214
diff
changeset
|
623 |
|
550 | 624 |
happy = self._allSatisfied0() |
221 | 625 |
|
550 | 626 |
if happy: |
618 | 627 |
## print 'OK' |
550 | 628 |
break |
618 | 629 |
## else: |
630 |
## print 'failed' |
|
550 | 631 |
if passes > maxPasses: |
632 |
raise IndexError, "Index entries not resolved after %d passes" % maxPasses |
|
1428 | 633 |
|
1131 | 634 |
if _verbose: print 'saved' |
284
eabeb5f4e851
Added UserDocTemplate class, and paragraph.getPlainText()
andy_robinson
parents:
279
diff
changeset
|
635 |
|
550 | 636 |
#these are pure virtuals override in derived classes |
637 |
#NB these get called at suitable places by the base class |
|
638 |
#so if you derive and override the handle_xxx methods |
|
639 |
#it's up to you to ensure that they maintain the needed consistency |
|
640 |
def afterInit(self): |
|
641 |
"""This is called after initialisation of the base class.""" |
|
642 |
pass |
|
284
eabeb5f4e851
Added UserDocTemplate class, and paragraph.getPlainText()
andy_robinson
parents:
279
diff
changeset
|
643 |
|
550 | 644 |
def beforeDocument(self): |
645 |
"""This is called before any processing is |
|
646 |
done on the document.""" |
|
647 |
pass |
|
284
eabeb5f4e851
Added UserDocTemplate class, and paragraph.getPlainText()
andy_robinson
parents:
279
diff
changeset
|
648 |
|
550 | 649 |
def beforePage(self): |
650 |
"""This is called at the beginning of page |
|
651 |
processing, and immediately before the |
|
652 |
beforeDrawPage method of the current page |
|
653 |
template.""" |
|
654 |
pass |
|
284
eabeb5f4e851
Added UserDocTemplate class, and paragraph.getPlainText()
andy_robinson
parents:
279
diff
changeset
|
655 |
|
550 | 656 |
def afterPage(self): |
657 |
"""This is called after page processing, and |
|
658 |
immediately after the afterDrawPage method |
|
659 |
of the current page template.""" |
|
660 |
pass |
|
284
eabeb5f4e851
Added UserDocTemplate class, and paragraph.getPlainText()
andy_robinson
parents:
279
diff
changeset
|
661 |
|
550 | 662 |
def filterFlowables(self,flowables): |
663 |
'''called to filter flowables at the start of the main handle_flowable method. |
|
664 |
Upon return if flowables[0] has been set to None it is discarded and the main |
|
665 |
method returns. |
|
666 |
''' |
|
667 |
pass |
|
1428 | 668 |
|
550 | 669 |
def afterFlowable(self, flowable): |
670 |
'''called after a flowable has been rendered''' |
|
671 |
pass |
|
284
eabeb5f4e851
Added UserDocTemplate class, and paragraph.getPlainText()
andy_robinson
parents:
279
diff
changeset
|
672 |
|
565 | 673 |
|
221 | 674 |
class SimpleDocTemplate(BaseDocTemplate): |
550 | 675 |
"""A special case document template that will handle many simple documents. |
1428 | 676 |
See documentation for BaseDocTemplate. No pageTemplates are required |
550 | 677 |
for this special case. A page templates are inferred from the |
678 |
margin information and the onFirstPage, onLaterPages arguments to the build method. |
|
1428 | 679 |
|
550 | 680 |
A document which has all pages with the same look except for the first |
681 |
page may can be built using this special approach. |
|
682 |
""" |
|
683 |
_invalidInitArgs = ('pageTemplates',) |
|
565 | 684 |
|
550 | 685 |
def handle_pageBegin(self): |
686 |
'''override base method to add a change of page template after the firstpage. |
|
687 |
''' |
|
688 |
self._handle_pageBegin() |
|
689 |
self._handle_nextPageTemplate('Later') |
|
221 | 690 |
|
550 | 691 |
def build(self,flowables,onFirstPage=_doNothing, onLaterPages=_doNothing): |
692 |
"""build the document using the flowables. Annotate the first page using the onFirstPage |
|
693 |
function and later pages using the onLaterPages function. The onXXX pages should follow |
|
694 |
the signature |
|
1428 | 695 |
|
550 | 696 |
def myOnFirstPage(canvas, document): |
697 |
# do annotations and modify the document |
|
698 |
... |
|
1428 | 699 |
|
550 | 700 |
The functions can do things like draw logos, page numbers, |
701 |
footers, etcetera. They can use external variables to vary |
|
702 |
the look (for example providing page numbering or section names). |
|
703 |
""" |
|
704 |
self._calc() #in case we changed margins sizes etc |
|
705 |
frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal') |
|
1267
118eabbf5ba4
Added template pagesize args in SimpleDoc.__init__ as suggested by D Horkoff
rgbecker
parents:
1222
diff
changeset
|
706 |
self.addPageTemplates([PageTemplate(id='First',frames=frameT, onPage=onFirstPage,pagesize=self.pagesize), |
118eabbf5ba4
Added template pagesize args in SimpleDoc.__init__ as suggested by D Horkoff
rgbecker
parents:
1222
diff
changeset
|
707 |
PageTemplate(id='Later',frames=frameT, onPage=onLaterPages,pagesize=self.pagesize)]) |
550 | 708 |
if onFirstPage is _doNothing and hasattr(self,'onFirstPage'): |
709 |
self.pageTemplates[0].beforeDrawPage = self.onFirstPage |
|
710 |
if onLaterPages is _doNothing and hasattr(self,'onLaterPages'): |
|
711 |
self.pageTemplates[1].beforeDrawPage = self.onLaterPages |
|
712 |
BaseDocTemplate.build(self,flowables) |
|
512 | 713 |
|
565 | 714 |
|
550 | 715 |
########################################################## |
716 |
## |
|
717 |
## testing |
|
718 |
## |
|
719 |
########################################################## |
|
512 | 720 |
|
721 |
def randomText(): |
|
550 | 722 |
#this may or may not be appropriate in your company |
723 |
from random import randint, choice |
|
512 | 724 |
|
550 | 725 |
RANDOMWORDS = ['strategic','direction','proactive', |
726 |
'reengineering','forecast','resources', |
|
727 |
'forward-thinking','profit','growth','doubletalk', |
|
728 |
'venture capital','IPO'] |
|
512 | 729 |
|
550 | 730 |
sentences = 5 |
731 |
output = "" |
|
732 |
for sentenceno in range(randint(1,5)): |
|
733 |
output = output + 'Blah' |
|
734 |
for wordno in range(randint(10,25)): |
|
735 |
if randint(0,4)==0: |
|
736 |
word = choice(RANDOMWORDS) |
|
737 |
else: |
|
738 |
word = 'blah' |
|
739 |
output = output + ' ' +word |
|
740 |
output = output+'.' |
|
741 |
return output |
|
221 | 742 |
|
565 | 743 |
|
221 | 744 |
if __name__ == '__main__': |
745 |
||
550 | 746 |
def myFirstPage(canvas, doc): |
747 |
canvas.saveState() |
|
748 |
canvas.setStrokeColor(red) |
|
749 |
canvas.setLineWidth(5) |
|
750 |
canvas.line(66,72,66,PAGE_HEIGHT-72) |
|
751 |
canvas.setFont('Times-Bold',24) |
|
752 |
canvas.drawString(108, PAGE_HEIGHT-108, "TABLE OF CONTENTS DEMO") |
|
753 |
canvas.setFont('Times-Roman',12) |
|
754 |
canvas.drawString(4 * inch, 0.75 * inch, "First Page") |
|
755 |
canvas.restoreState() |
|
221 | 756 |
|
550 | 757 |
def myLaterPages(canvas, doc): |
758 |
canvas.saveState() |
|
759 |
canvas.setStrokeColor(red) |
|
760 |
canvas.setLineWidth(5) |
|
761 |
canvas.line(66,72,66,PAGE_HEIGHT-72) |
|
762 |
canvas.setFont('Times-Roman',12) |
|
763 |
canvas.drawString(4 * inch, 0.75 * inch, "Page %d" % doc.page) |
|
764 |
canvas.restoreState() |
|
221 | 765 |
|
550 | 766 |
def run(): |
767 |
objects_to_draw = [] |
|
768 |
from reportlab.lib.styles import ParagraphStyle |
|
769 |
#from paragraph import Paragraph |
|
770 |
from doctemplate import SimpleDocTemplate |
|
221 | 771 |
|
550 | 772 |
#need a style |
773 |
normal = ParagraphStyle('normal') |
|
774 |
normal.firstLineIndent = 18 |
|
775 |
normal.spaceBefore = 6 |
|
776 |
import random |
|
777 |
for i in range(15): |
|
778 |
height = 0.5 + (2*random.random()) |
|
779 |
box = XBox(6 * inch, height * inch, 'Box Number %d' % i) |
|
780 |
objects_to_draw.append(box) |
|
781 |
para = Paragraph(randomText(), normal) |
|
782 |
objects_to_draw.append(para) |
|
221 | 783 |
|
550 | 784 |
SimpleDocTemplate('doctemplate.pdf').build(objects_to_draw, |
785 |
onFirstPage=myFirstPage,onLaterPages=myLaterPages) |
|
221 | 786 |
|
550 | 787 |
run() |
221 | 788 |