author | rgbecker |
Wed, 07 Mar 2001 18:57:12 +0000 | |
changeset 684 | 2a43c747527a |
parent 681 | 934a4f24ea5d |
child 698 | 864265047890 |
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 |
|
684 | 4 |
#$Header: /tmp/reportlab/reportlab/platypus/doctemplate.py,v 1.37 2001/03/07 18:57:11 rgbecker Exp $ |
565 | 5 |
|
684 | 6 |
__version__=''' $Id: doctemplate.py,v 1.37 2001/03/07 18:57:11 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 |
|
684 | 35 |
from reportlab.config import defaultPageSize |
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 |
|
68 |
||
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 |
''' |
|
79 |
def __init__(self,action=[]): |
|
80 |
if type(action) not in (ListType, TupleType): |
|
81 |
action = (action,) |
|
82 |
self.action = 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 |
|
565 | 114 |
|
218
274db2129c04
Fixes/Changes to get testplatypus to work with new framework
rgbecker
parents:
214
diff
changeset
|
115 |
FrameBreak = ActionFlowable('frameEnd') |
197 | 116 |
PageBegin = ActionFlowable('pageBegin') |
117 |
||
512 | 118 |
|
197 | 119 |
class NextPageTemplate(ActionFlowable): |
550 | 120 |
"""When you get to the next page, use the template specified (change to two column, for example) """ |
121 |
def __init__(self,pt): |
|
122 |
ActionFlowable.__init__(self,('nextPageTemplate',pt)) |
|
197 | 123 |
|
565 | 124 |
|
197 | 125 |
class PageTemplate: |
550 | 126 |
""" |
127 |
essentially a list of Frames and an onPage routine to call at the start |
|
128 |
of a page when this is selected. onPageEnd gets called at the end. |
|
129 |
derived classes can also implement beforeDrawPage and afterDrawPage if they want |
|
130 |
""" |
|
131 |
def __init__(self,id=None,frames=[],onPage=_doNothing, onPageEnd=_doNothing, |
|
684 | 132 |
pagesize=defaultPageSize): |
550 | 133 |
if type(frames) not in (ListType,TupleType): frames = [frames] |
134 |
assert filter(lambda x: not isinstance(x,Frame), frames)==[], "frames argument error" |
|
135 |
self.id = id |
|
136 |
self.frames = frames |
|
137 |
self.onPage = onPage |
|
138 |
self.onPageEnd = onPageEnd |
|
139 |
self.pagesize = pagesize |
|
512 | 140 |
|
550 | 141 |
def beforeDrawPage(self,canv,doc): |
142 |
"""Override this if you want additional functionality or prefer |
|
143 |
a class based page routine. Called before any flowables for |
|
144 |
this page are processed.""" |
|
145 |
pass |
|
197 | 146 |
|
550 | 147 |
def afterDrawPage(self, canv, doc): |
148 |
"""This is called after the last flowable for the page has |
|
149 |
been processed. You might use this if the page header or |
|
150 |
footer needed knowledge of what flowables were drawn on |
|
151 |
this page.""" |
|
152 |
pass |
|
153 |
||
565 | 154 |
|
512 | 155 |
class BaseDocTemplate: |
550 | 156 |
""" |
157 |
First attempt at defining a document template class. |
|
512 | 158 |
|
550 | 159 |
The basic idea is simple. |
160 |
0) The document has a list of data associated with it |
|
161 |
this data should derive from flowables. We'll have |
|
162 |
special classes like PageBreak, FrameBreak to do things |
|
163 |
like forcing a page end etc. |
|
512 | 164 |
|
550 | 165 |
1) The document has one or more page templates. |
512 | 166 |
|
550 | 167 |
2) Each page template has one or more frames. |
512 | 168 |
|
550 | 169 |
3) The document class provides base methods for handling the |
170 |
story events and some reasonable methods for getting the |
|
171 |
story flowables into the frames. |
|
214 | 172 |
|
550 | 173 |
4) The document instances can override the base handler routines. |
174 |
||
175 |
Most of the methods for this class are not called directly by the user, |
|
176 |
but in some advanced usages they may need to be overridden via subclassing. |
|
177 |
||
178 |
EXCEPTION: doctemplate.build(...) must be called for most reasonable uses |
|
179 |
since it builds a document using the page template. |
|
180 |
||
181 |
Each document template builds exactly one document into a file specified |
|
182 |
by the filename argument on initialization. |
|
197 | 183 |
|
550 | 184 |
Possible keyword arguments for the initialization: |
185 |
||
186 |
pageTemplates: A list of templates. Must be nonempty. Names |
|
187 |
assigned to the templates are used for referring to them so no two used |
|
188 |
templates should have the same name. For example you might want one template |
|
189 |
for a title page, one for a section first page, one for a first page of |
|
190 |
a chapter and two more for the interior of a chapter on odd and even pages. |
|
191 |
If this argument is omitted then at least one pageTemplate should be provided |
|
192 |
using the addPageTemplates method before the document is built. |
|
193 |
showBoundary: if set draw a box around the frame boundaries. |
|
194 |
leftMargin: |
|
195 |
rightMargin: |
|
196 |
topMargin: |
|
197 |
bottomMargin: Margin sizes in points (default 1 inch) |
|
198 |
These margins may be overridden by the pageTemplates. They are primarily of interest |
|
199 |
for the SimpleDocumentTemplate subclass. |
|
200 |
allowSplitting: If set flowables (eg, paragraphs) may be split across frames or pages |
|
201 |
(default: 1) |
|
202 |
title: Internal title for document (does not automatically display on any page) |
|
203 |
author: Internal author for document (does not automatically display on any page) |
|
204 |
""" |
|
684 | 205 |
_initArgs = { 'pagesize':defaultPageSize, |
550 | 206 |
'pageTemplates':[], |
207 |
'showBoundary':0, |
|
208 |
'leftMargin':inch, |
|
209 |
'rightMargin':inch, |
|
210 |
'topMargin':inch, |
|
211 |
'bottomMargin':inch, |
|
212 |
'allowSplitting':1, |
|
213 |
'title':None, |
|
214 |
'author':None, |
|
215 |
'_pageBreakQuick':1} |
|
216 |
_invalidInitArgs = () |
|
197 | 217 |
|
550 | 218 |
def __init__(self, filename, **kw): |
219 |
"""create a document template bound to a filename (see class documentation for keyword arguments)""" |
|
220 |
self.filename = filename |
|
512 | 221 |
|
550 | 222 |
for k in self._initArgs.keys(): |
223 |
if not kw.has_key(k): |
|
224 |
v = self._initArgs[k] |
|
225 |
else: |
|
226 |
if k in self._invalidInitArgs: |
|
227 |
raise ValueError, "Invalid argument %s" % k |
|
228 |
v = kw[k] |
|
229 |
setattr(self,k,v) |
|
512 | 230 |
|
550 | 231 |
p = self.pageTemplates |
232 |
self.pageTemplates = [] |
|
233 |
self.addPageTemplates(p) |
|
310 | 234 |
|
550 | 235 |
# facility to assist multi-build and cross-referencing. |
236 |
# various hooks can put things into here - key is what |
|
237 |
# you want, value is a page number. This can then be |
|
238 |
# passed to indexing flowables. |
|
239 |
self._pageRefs = {} |
|
240 |
self._indexingFlowables = [] |
|
241 |
||
242 |
self._calc() |
|
243 |
self.afterInit() |
|
512 | 244 |
|
550 | 245 |
def _calc(self): |
246 |
self._rightMargin = self.pagesize[0] - self.rightMargin |
|
247 |
self._topMargin = self.pagesize[1] - self.topMargin |
|
248 |
self.width = self._rightMargin - self.leftMargin |
|
249 |
self.height = self._topMargin - self.bottomMargin |
|
512 | 250 |
|
251 |
||
550 | 252 |
def clean_hanging(self): |
253 |
'handle internal postponed actions' |
|
254 |
while len(self._hanging): |
|
255 |
self.handle_flowable(self._hanging) |
|
197 | 256 |
|
550 | 257 |
def addPageTemplates(self,pageTemplates): |
258 |
'add one or a sequence of pageTemplates' |
|
259 |
if type(pageTemplates) not in (ListType,TupleType): |
|
260 |
pageTemplates = [pageTemplates] |
|
261 |
#this test below fails due to inconsistent imports! |
|
262 |
#assert filter(lambda x: not isinstance(x,PageTemplate), pageTemplates)==[], "pageTemplates argument error" |
|
263 |
for t in pageTemplates: |
|
264 |
self.pageTemplates.append(t) |
|
265 |
||
266 |
def handle_documentBegin(self): |
|
267 |
'''implement actions at beginning of document''' |
|
268 |
self._hanging = [PageBegin] |
|
269 |
self.pageTemplate = self.pageTemplates[0] |
|
270 |
self.page = 0 |
|
271 |
self.beforeDocument() |
|
253 | 272 |
|
550 | 273 |
def handle_pageBegin(self): |
274 |
'''Perform actions required at beginning of page. |
|
275 |
shouldn't normally be called directly''' |
|
276 |
self.page = self.page + 1 |
|
277 |
self.pageTemplate.beforeDrawPage(self.canv,self) |
|
278 |
self.pageTemplate.onPage(self.canv,self) |
|
279 |
self.beforePage() |
|
280 |
if hasattr(self,'_nextFrameIndex'): |
|
281 |
del self._nextFrameIndex |
|
282 |
self.frame = self.pageTemplate.frames[0] |
|
283 |
self.handle_frameBegin() |
|
197 | 284 |
|
550 | 285 |
def handle_pageEnd(self): |
286 |
''' show the current page |
|
287 |
check the next page template |
|
288 |
hang a page begin |
|
289 |
''' |
|
290 |
self.pageTemplate.afterDrawPage(self.canv, self) |
|
291 |
self.pageTemplate.onPageEnd(self.canv, self) |
|
292 |
self.afterPage() |
|
293 |
self.canv.showPage() |
|
294 |
if hasattr(self,'_nextPageTemplateIndex'): |
|
295 |
self.pageTemplate = self.pageTemplates[self._nextPageTemplateIndex] |
|
296 |
del self._nextPageTemplateIndex |
|
297 |
self._hanging.append(PageBegin) |
|
197 | 298 |
|
550 | 299 |
def handle_pageBreak(self): |
300 |
'''some might choose not to end all the frames''' |
|
301 |
if self._pageBreakQuick: |
|
302 |
self.handle_pageEnd() |
|
303 |
else: |
|
304 |
n = len(self._hanging) |
|
305 |
while len(self._hanging)==n: |
|
306 |
self.handle_frameEnd() |
|
512 | 307 |
|
550 | 308 |
def handle_frameBegin(self,*args): |
309 |
'''What to do at the beginning of a page''' |
|
310 |
self.frame._reset() |
|
311 |
if self.showBoundary or self.frame.showBoundary: |
|
312 |
self.frame.drawBoundary(self.canv) |
|
197 | 313 |
|
550 | 314 |
def handle_frameEnd(self): |
315 |
''' Handles the semantics of the end of a frame. This includes the selection of |
|
316 |
the next frame or if this is the last frame then invoke pageEnd. |
|
317 |
''' |
|
318 |
if hasattr(self,'_nextFrameIndex'): |
|
319 |
frame = self.pageTemplate.frames[self._nextFrameIndex] |
|
320 |
del self._nextFrameIndex |
|
321 |
self.handle_frameBegin() |
|
322 |
elif hasattr(self.frame,'lastFrame') or self.frame is self.pageTemplate.frames[-1]: |
|
323 |
self.handle_pageEnd() |
|
324 |
self.frame = None |
|
325 |
else: |
|
326 |
f = self.frame |
|
327 |
self.frame = self.pageTemplate.frames[self.pageTemplate.frames.index(f) + 1] |
|
328 |
self.handle_frameBegin() |
|
197 | 329 |
|
550 | 330 |
def handle_nextPageTemplate(self,pt): |
331 |
'''On endPage chenge to the page template with name or index pt''' |
|
332 |
if type(pt) is StringType: |
|
333 |
for t in self.pageTemplates: |
|
334 |
if t.id == pt: |
|
335 |
self._nextPageTemplateIndex = self.pageTemplates.index(t) |
|
336 |
return |
|
337 |
raise ValueError, "can't find template('%s')"%pt |
|
338 |
elif type(pt) is IntType: |
|
339 |
self._nextPageTemplateIndex = pt |
|
340 |
else: |
|
341 |
raise TypeError, "argument pt should be string or integer" |
|
197 | 342 |
|
550 | 343 |
def handle_nextFrame(self,fx): |
344 |
'''On endFrame chenge to the frame with name or index fx''' |
|
345 |
if type(fx) is StringType: |
|
346 |
for f in self.pageTemplate.frames: |
|
347 |
if f.id == fx: |
|
348 |
self._nextFrameIndex = self.pageTemplate.frames.index(f) |
|
349 |
return |
|
350 |
raise ValueError, "can't find frame('%s')"%fx |
|
351 |
elif type(fx) is IntType: |
|
352 |
self._nextFrameIndex = fx |
|
353 |
else: |
|
354 |
raise TypeError, "argument fx should be string or integer" |
|
512 | 355 |
|
550 | 356 |
def handle_currentFrame(self,fx): |
357 |
'''chenge to the frame with name or index fx''' |
|
358 |
if type(fx) is StringType: |
|
359 |
for f in self.pageTemplate.frames: |
|
360 |
if f.id == fx: |
|
361 |
self._nextFrameIndex = self.pageTemplate.frames.index(f) |
|
362 |
return |
|
363 |
raise ValueError, "can't find frame('%s')"%fx |
|
364 |
elif type(fx) is IntType: |
|
365 |
self._nextFrameIndex = fx |
|
366 |
else: |
|
367 |
raise TypeError, "argument fx should be string or integer" |
|
197 | 368 |
|
550 | 369 |
def handle_flowable(self,flowables): |
370 |
'''try to handle one flowable from the front of list flowables.''' |
|
371 |
||
372 |
#allow document a chance to look at, modify or ignore |
|
373 |
#the object(s) about to be processed |
|
374 |
self.filterFlowables(flowables) |
|
375 |
f = flowables[0] |
|
376 |
del flowables[0] |
|
377 |
if f is None: |
|
378 |
return |
|
197 | 379 |
|
550 | 380 |
if isinstance(f,PageBreak): |
381 |
self.handle_pageBreak() |
|
382 |
self.afterFlowable(f) |
|
383 |
elif isinstance(f,ActionFlowable): |
|
384 |
f.apply(self) |
|
385 |
self.afterFlowable(f) |
|
386 |
else: |
|
387 |
#general case we have to do something |
|
388 |
if self.frame.add(f, self.canv, trySplit=self.allowSplitting): |
|
389 |
self.afterFlowable(f) |
|
390 |
else: |
|
391 |
if self.allowSplitting: |
|
392 |
# see if this is a splittable thing |
|
393 |
S = self.frame.split(f,self.canv) |
|
394 |
n = len(S) |
|
395 |
else: |
|
396 |
n = 0 |
|
197 | 397 |
|
550 | 398 |
if n: |
399 |
if self.frame.add(S[0], self.canv, trySplit=0): |
|
551 | 400 |
self.afterFlowable(S[0]) |
550 | 401 |
else: |
551 | 402 |
if hasattr(f,'text'): |
403 |
print 'Offending text:' |
|
404 |
print "'''"+f.text+"'''" |
|
405 |
print f.style.fontName, f.style.fontSize, f.style.leading, f.style.firstLineIndent, f.style.leftIndent, f.style.rightIndent |
|
406 |
print S[0].style.fontName, S[0].style.fontSize, S[0].style.leading, S[0].style.firstLineIndent, S[0].style.leftIndent, S[0].style.rightIndent |
|
407 |
elif hasattr(f, 'getPlainText'): |
|
550 | 408 |
print 'Offending Paragraph:' |
409 |
print f.getPlainText() |
|
410 |
raise "LayoutError", "splitting error type=%s" % type(f) |
|
411 |
del S[0] |
|
412 |
for f in xrange(n-1): |
|
413 |
flowables.insert(f,S[f]) # put split flowables back on the list |
|
414 |
else: |
|
415 |
# this must be cleared when they are finally drawn! |
|
416 |
if hasattr(f,'postponed'): |
|
417 |
message = "Flowable %s too large on page %d" % (f, self.page) |
|
418 |
#show us, it might be handy |
|
419 |
#HACK = it seems within tables we sometimes |
|
420 |
#get an empty paragraph that won't fit and this |
|
421 |
#causes it to fall over. FIXME FIXME FIXME |
|
422 |
if hasattr(f, 'getPlainText'): |
|
423 |
print 'Offending Paragraph:' |
|
424 |
print f.getPlainText() |
|
425 |
raise "LayoutError", message |
|
426 |
f.postponed = 1 |
|
427 |
flowables.insert(0,f) # put the flowable back |
|
428 |
self.handle_frameEnd() |
|
197 | 429 |
|
550 | 430 |
#these are provided so that deriving classes can refer to them |
431 |
_handle_documentBegin = handle_documentBegin |
|
432 |
_handle_pageBegin = handle_pageBegin |
|
433 |
_handle_pageEnd = handle_pageEnd |
|
434 |
_handle_frameBegin = handle_frameBegin |
|
435 |
_handle_frameEnd = handle_frameEnd |
|
436 |
_handle_flowable = handle_flowable |
|
437 |
_handle_nextPageTemplate = handle_nextPageTemplate |
|
438 |
_handle_currentFrame = handle_currentFrame |
|
439 |
_handle_nextFrame = handle_nextFrame |
|
197 | 440 |
|
550 | 441 |
def _startBuild(self, filename=None, canvasmaker=canvas.Canvas): |
442 |
self._calc() |
|
443 |
self.canv = canvasmaker(filename or self.filename,pagesize=self.pagesize) |
|
444 |
self.handle_documentBegin() |
|
512 | 445 |
|
550 | 446 |
def _endBuild(self): |
447 |
if self._hanging!=[] and self._hanging[-1] is PageBegin: |
|
448 |
del self._hanging[-1] |
|
449 |
self.clean_hanging() |
|
450 |
else: |
|
451 |
self.clean_hanging() |
|
452 |
self.handle_pageBreak() |
|
512 | 453 |
|
550 | 454 |
self.canv.save() |
455 |
#AR - hack - for some reason a document did not |
|
456 |
#have these: |
|
457 |
#if hasattr(self, 'frame'): del self.frame |
|
458 |
#if hasattr(self, 'pageTemplate'): del self.pageTemplate |
|
459 |
#del self.frame, self.pageTemplate |
|
218
274db2129c04
Fixes/Changes to get testplatypus to work with new framework
rgbecker
parents:
214
diff
changeset
|
460 |
|
550 | 461 |
def build(self, flowables, filename=None, canvasmaker=canvas.Canvas): |
462 |
"""Build the document from a list of flowables. |
|
463 |
If the filename argument is provided then that filename is used |
|
464 |
rather than the one provided upon initialization. |
|
465 |
If the canvasmaker argument is provided then it will be used |
|
466 |
instead of the default. For example a slideshow might use |
|
467 |
an alternate canvas which places 6 slides on a page (by |
|
468 |
doing translations, scalings and redefining the page break |
|
469 |
operations). |
|
470 |
""" |
|
471 |
#assert filter(lambda x: not isinstance(x,Flowable), flowables)==[], "flowables argument error" |
|
472 |
self._startBuild(filename,canvasmaker) |
|
512 | 473 |
|
550 | 474 |
while len(flowables): |
475 |
self.clean_hanging() |
|
476 |
self.handle_flowable(flowables) |
|
512 | 477 |
|
550 | 478 |
self._endBuild() |
512 | 479 |
|
550 | 480 |
def _allSatisfied0(self): |
481 |
"""Called by multi-build - are all cross-references resolved?""" |
|
482 |
allHappy = 1 |
|
483 |
for f in self._indexingFlowables: |
|
484 |
if not f.isSatisfied(): |
|
485 |
allHappy = 0 |
|
486 |
break |
|
487 |
return allHappy |
|
197 | 488 |
|
550 | 489 |
def notify0(self, kind, stuff): |
490 |
""""Forward to any listeners""" |
|
491 |
for l in self._indexingFlowables: |
|
492 |
l.notify(kind, stuff) |
|
493 |
||
494 |
def pageRef0(self, label): |
|
495 |
"""hook to register a page number""" |
|
496 |
print "pageRef called with label '%s' on page %d" % ( |
|
497 |
label, self.page) |
|
498 |
self._pageRefs[label] = self.page |
|
499 |
||
500 |
def multiBuild0(self, story, |
|
501 |
filename=None, |
|
502 |
canvasmaker=canvas.Canvas, |
|
503 |
maxPasses = 10): |
|
504 |
"""Makes multiple passes until all indexing flowables |
|
505 |
are happy.""" |
|
506 |
self._indexingFlowables = [] |
|
507 |
#scan the story and keep a copy |
|
508 |
for thing in story: |
|
509 |
if thing.isIndexing(): |
|
510 |
self._indexingFlowables.append(thing) |
|
511 |
#print 'scanned story, found these indexing flowables:\n' |
|
512 |
#print self._indexingFlowables |
|
197 | 513 |
|
550 | 514 |
passes = 0 |
515 |
while 1: |
|
516 |
passes = passes + 1 |
|
681 | 517 |
print 'building pass '+str(passes) + '...', |
197 | 518 |
|
550 | 519 |
for fl in self._indexingFlowables: |
520 |
fl.beforeBuild() |
|
218
274db2129c04
Fixes/Changes to get testplatypus to work with new framework
rgbecker
parents:
214
diff
changeset
|
521 |
|
550 | 522 |
# work with a copy of the story, since it is consumed |
523 |
tempStory = story[:] |
|
524 |
self.build(tempStory, filename, canvasmaker) |
|
525 |
#self.notify0('debug',None) |
|
512 | 526 |
|
550 | 527 |
#clean up so multi-build does not go wrong - the frame |
528 |
#packer might have tacked an attribute onto some |
|
529 |
#paragraphs |
|
530 |
for elem in story: |
|
531 |
if hasattr(elem, 'postponed'): |
|
532 |
del elem.postponed |
|
218
274db2129c04
Fixes/Changes to get testplatypus to work with new framework
rgbecker
parents:
214
diff
changeset
|
533 |
|
550 | 534 |
for fl in self._indexingFlowables: |
535 |
fl.afterBuild() |
|
218
274db2129c04
Fixes/Changes to get testplatypus to work with new framework
rgbecker
parents:
214
diff
changeset
|
536 |
|
550 | 537 |
happy = self._allSatisfied0() |
221 | 538 |
|
550 | 539 |
if happy: |
618 | 540 |
## print 'OK' |
550 | 541 |
break |
618 | 542 |
## else: |
543 |
## print 'failed' |
|
550 | 544 |
if passes > maxPasses: |
545 |
raise IndexError, "Index entries not resolved after %d passes" % maxPasses |
|
546 |
||
681 | 547 |
print 'saved' |
284
eabeb5f4e851
Added UserDocTemplate class, and paragraph.getPlainText()
andy_robinson
parents:
279
diff
changeset
|
548 |
|
550 | 549 |
#these are pure virtuals override in derived classes |
550 |
#NB these get called at suitable places by the base class |
|
551 |
#so if you derive and override the handle_xxx methods |
|
552 |
#it's up to you to ensure that they maintain the needed consistency |
|
553 |
def afterInit(self): |
|
554 |
"""This is called after initialisation of the base class.""" |
|
555 |
pass |
|
284
eabeb5f4e851
Added UserDocTemplate class, and paragraph.getPlainText()
andy_robinson
parents:
279
diff
changeset
|
556 |
|
550 | 557 |
def beforeDocument(self): |
558 |
"""This is called before any processing is |
|
559 |
done on the document.""" |
|
560 |
pass |
|
284
eabeb5f4e851
Added UserDocTemplate class, and paragraph.getPlainText()
andy_robinson
parents:
279
diff
changeset
|
561 |
|
550 | 562 |
def beforePage(self): |
563 |
"""This is called at the beginning of page |
|
564 |
processing, and immediately before the |
|
565 |
beforeDrawPage method of the current page |
|
566 |
template.""" |
|
567 |
pass |
|
284
eabeb5f4e851
Added UserDocTemplate class, and paragraph.getPlainText()
andy_robinson
parents:
279
diff
changeset
|
568 |
|
550 | 569 |
def afterPage(self): |
570 |
"""This is called after page processing, and |
|
571 |
immediately after the afterDrawPage method |
|
572 |
of the current page template.""" |
|
573 |
pass |
|
284
eabeb5f4e851
Added UserDocTemplate class, and paragraph.getPlainText()
andy_robinson
parents:
279
diff
changeset
|
574 |
|
550 | 575 |
def filterFlowables(self,flowables): |
576 |
'''called to filter flowables at the start of the main handle_flowable method. |
|
577 |
Upon return if flowables[0] has been set to None it is discarded and the main |
|
578 |
method returns. |
|
579 |
''' |
|
580 |
pass |
|
512 | 581 |
|
550 | 582 |
def afterFlowable(self, flowable): |
583 |
'''called after a flowable has been rendered''' |
|
584 |
pass |
|
284
eabeb5f4e851
Added UserDocTemplate class, and paragraph.getPlainText()
andy_robinson
parents:
279
diff
changeset
|
585 |
|
565 | 586 |
|
221 | 587 |
class SimpleDocTemplate(BaseDocTemplate): |
550 | 588 |
"""A special case document template that will handle many simple documents. |
589 |
See documentation for BaseDocTemplate. No pageTemplates are required |
|
590 |
for this special case. A page templates are inferred from the |
|
591 |
margin information and the onFirstPage, onLaterPages arguments to the build method. |
|
592 |
||
593 |
A document which has all pages with the same look except for the first |
|
594 |
page may can be built using this special approach. |
|
595 |
""" |
|
596 |
_invalidInitArgs = ('pageTemplates',) |
|
565 | 597 |
|
550 | 598 |
def handle_pageBegin(self): |
599 |
'''override base method to add a change of page template after the firstpage. |
|
600 |
''' |
|
601 |
self._handle_pageBegin() |
|
602 |
self._handle_nextPageTemplate('Later') |
|
221 | 603 |
|
550 | 604 |
def build(self,flowables,onFirstPage=_doNothing, onLaterPages=_doNothing): |
605 |
"""build the document using the flowables. Annotate the first page using the onFirstPage |
|
606 |
function and later pages using the onLaterPages function. The onXXX pages should follow |
|
607 |
the signature |
|
608 |
||
609 |
def myOnFirstPage(canvas, document): |
|
610 |
# do annotations and modify the document |
|
611 |
... |
|
612 |
||
613 |
The functions can do things like draw logos, page numbers, |
|
614 |
footers, etcetera. They can use external variables to vary |
|
615 |
the look (for example providing page numbering or section names). |
|
616 |
""" |
|
617 |
self._calc() #in case we changed margins sizes etc |
|
618 |
frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal') |
|
619 |
self.addPageTemplates([PageTemplate(id='First',frames=frameT, onPage=onFirstPage), |
|
620 |
PageTemplate(id='Later',frames=frameT, onPage=onLaterPages)]) |
|
621 |
if onFirstPage is _doNothing and hasattr(self,'onFirstPage'): |
|
622 |
self.pageTemplates[0].beforeDrawPage = self.onFirstPage |
|
623 |
if onLaterPages is _doNothing and hasattr(self,'onLaterPages'): |
|
624 |
self.pageTemplates[1].beforeDrawPage = self.onLaterPages |
|
625 |
BaseDocTemplate.build(self,flowables) |
|
512 | 626 |
|
565 | 627 |
|
550 | 628 |
########################################################## |
629 |
## |
|
630 |
## testing |
|
631 |
## |
|
632 |
########################################################## |
|
512 | 633 |
|
634 |
def randomText(): |
|
550 | 635 |
#this may or may not be appropriate in your company |
636 |
from random import randint, choice |
|
512 | 637 |
|
550 | 638 |
RANDOMWORDS = ['strategic','direction','proactive', |
639 |
'reengineering','forecast','resources', |
|
640 |
'forward-thinking','profit','growth','doubletalk', |
|
641 |
'venture capital','IPO'] |
|
512 | 642 |
|
550 | 643 |
sentences = 5 |
644 |
output = "" |
|
645 |
for sentenceno in range(randint(1,5)): |
|
646 |
output = output + 'Blah' |
|
647 |
for wordno in range(randint(10,25)): |
|
648 |
if randint(0,4)==0: |
|
649 |
word = choice(RANDOMWORDS) |
|
650 |
else: |
|
651 |
word = 'blah' |
|
652 |
output = output + ' ' +word |
|
653 |
output = output+'.' |
|
654 |
return output |
|
221 | 655 |
|
565 | 656 |
|
221 | 657 |
if __name__ == '__main__': |
658 |
||
550 | 659 |
def myFirstPage(canvas, doc): |
660 |
canvas.saveState() |
|
661 |
canvas.setStrokeColor(red) |
|
662 |
canvas.setLineWidth(5) |
|
663 |
canvas.line(66,72,66,PAGE_HEIGHT-72) |
|
664 |
canvas.setFont('Times-Bold',24) |
|
665 |
canvas.drawString(108, PAGE_HEIGHT-108, "TABLE OF CONTENTS DEMO") |
|
666 |
canvas.setFont('Times-Roman',12) |
|
667 |
canvas.drawString(4 * inch, 0.75 * inch, "First Page") |
|
668 |
canvas.restoreState() |
|
221 | 669 |
|
550 | 670 |
def myLaterPages(canvas, doc): |
671 |
canvas.saveState() |
|
672 |
canvas.setStrokeColor(red) |
|
673 |
canvas.setLineWidth(5) |
|
674 |
canvas.line(66,72,66,PAGE_HEIGHT-72) |
|
675 |
canvas.setFont('Times-Roman',12) |
|
676 |
canvas.drawString(4 * inch, 0.75 * inch, "Page %d" % doc.page) |
|
677 |
canvas.restoreState() |
|
221 | 678 |
|
550 | 679 |
def run(): |
680 |
objects_to_draw = [] |
|
681 |
from reportlab.lib.styles import ParagraphStyle |
|
682 |
#from paragraph import Paragraph |
|
683 |
from doctemplate import SimpleDocTemplate |
|
221 | 684 |
|
550 | 685 |
#need a style |
686 |
normal = ParagraphStyle('normal') |
|
687 |
normal.firstLineIndent = 18 |
|
688 |
normal.spaceBefore = 6 |
|
689 |
import random |
|
690 |
for i in range(15): |
|
691 |
height = 0.5 + (2*random.random()) |
|
692 |
box = XBox(6 * inch, height * inch, 'Box Number %d' % i) |
|
693 |
objects_to_draw.append(box) |
|
694 |
para = Paragraph(randomText(), normal) |
|
695 |
objects_to_draw.append(para) |
|
221 | 696 |
|
550 | 697 |
SimpleDocTemplate('doctemplate.pdf').build(objects_to_draw, |
698 |
onFirstPage=myFirstPage,onLaterPages=myLaterPages) |
|
221 | 699 |
|
550 | 700 |
run() |
221 | 701 |