bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def getAllNamedColors(): #returns a dictionary of all the named ones in the module # uses a singleton for efficiency import colors namedColors = {} for (name, value) in colors.__dict__.items(): if isinstance(value, Color): namedColors[name] = value return namedColors
def getAllNamedColors(): #returns a dictionary of all the named ones in the module # uses a singleton for efficiency import colors namedColors = {} for (name, value) in colors.__dict__.items(): if isinstance(value, Color): __namedColors[name] = value return __namedColors
5,500
def save(self, formats=None, verbose=None, fnRoot=None, outDir=None): from reportlab import rl_config "Saves copies of self in desired location and formats" ext = '' if not fnRoot: fnRoot = getattr(self,'fileNamePattern',(self.__class__.__name__+'%03d')) try: fnRoot = fnRoot % getattr(self,'chartId',0) except TypeError, err: if err != 'not all arguments converted': raise
def save(self, formats=None, verbose=None, fnRoot=None, outDir=None): from reportlab import rl_config "Saves copies of self in desired location and formats" ext = '' if not fnRoot: fnRoot = getattr(self,'fileNamePattern',(self.__class__.__name__+'%03d')) try: fnRoot = fnRoot % getattr(self,'chartId',0) except TypeError, err: if err != 'not all arguments converted': raise
5,501
def findFontAndRegister(fontName): '''search for and register a font given it's name''' #it might have a font-specific encoding e.g. Symbol # or Dingbats. If not, take the default. face = getTypeFace(fontName) if face.requiredEncoding: font = Font(fontName, fontName, face.requiredEncoding) else: font = Font(fontName, fontName, defaultEncoding) registerFont(font) return font
def findFontAndRegister(fontName): '''search for and register a font given its name''' #it might have a font-specific encoding e.g. Symbol # or Dingbats. If not, take the default. face = getTypeFace(fontName) if face.requiredEncoding: font = Font(fontName, fontName, face.requiredEncoding) else: font = Font(fontName, fontName, defaultEncoding) registerFont(font) return font
5,502
def raiseConfigError(msg): import exceptions class ConfigError(exceptions.Exception): pass raise ConfigError(msg)
def raiseConfigError(msg): import exceptions class ConfigError(exceptions.Exception): pass raise ConfigError(msg)
5,503
def raiseConfigError(msg): import exceptions class ConfigError(exceptions.Exception): pass raise ConfigError(msg)
def raiseConfigError(msg): import exceptions class ConfigError(exceptions.Exception): pass raise ConfigError(msg)
5,504
def MovePYDs(*F): for x in sys.argv: if x[:18]=='--install-platlib=': return src = sys.exec_prefix dst = os.path.join(src,'DLLs') if sys.hexversion>=0x20200a0: src = os.path.join(src,'Lib','site-packages') for f in F: dstf = os.path.join(dst,f) if os.path.isfile(dstf): os.remove(dstf) srcf = os.path.join(src,f) os.rename(srcf,dstf) print 'Renaming %s to %s' % (srcf, dstf)
def MovePYDs(*F): for x in sys.argv: if x[:18]=='--install-platlib=': return src = sys.exec_prefix dst = os.path.join(src,'DLLs') if sys.hexversion>=0x20200a0: src = os.path.join(src,'Lib','site-packages') for f in F: dstf = os.path.join(dst,f) if os.path.isfile(dstf): os.remove(dstf) srcf = os.path.join(src,f) os.rename(srcf,dstf) print 'Renaming %s to %s' % (srcf, dstf)
5,505
def save(self): """This writes out the PDF document""" canv = canvas.Canvas(self.filename, pagesize = (self.pageWidth, self.pageHeight) ) if self.title: canv.setTitle(self.title) if self.author: canv.setAuthor(self.author) if self.subject: canv.setSubject(self.subject) canv.setPageCompression(self.compression) for slide in self.slides: if self.speakerNotes: #frame and shift the slide canv.scale(0.67, 0.67) canv.translate(self.pageWidth / 6.0, self.pageHeight / 3.0) canv.rect(0,0,self.pageWidth, self.pageHeight)
def save(self): """This writes out the PDF document""" canv = canvas.Canvas(self.filename, pagesize = (self.pageWidth, self.pageHeight) ) if self.title: canv.setTitle(self.title) if self.author: canv.setAuthor(self.author) if self.subject: canv.setSubject(self.subject) canv.setPageCompression(self.compression) for slide in self.slides: if self.speakerNotes: #frame and shift the slide canv.scale(0.67, 0.67) canv.translate(self.pageWidth / 6.0, self.pageHeight / 3.0) canv.rect(0,0,self.pageWidth, self.pageHeight)
5,506
def drawOn(self, canv): for graphic in self.graphics: graphic.drawOn(canv)
def drawOn(self, canv): for graphic in self.graphics: name = str(hash(graphic)) internalname = canv._doc.hasForm(name) if not internalname: canv.beginForm(name) canv.saveState() graphic.drawOn(canv) canv.restoreState() canv.endForm() canv.doForm(name) else: canv.doForm(name)
5,507
def drawOn(self, canv): for graphic in self.graphics: graphic.drawOn(canv)
def drawOn(self, canv): for graphic in self.graphics: graphic.drawOn(canv)
5,508
def drawOn(self, canv): filename = self.filename if filename: internalname = canv._doc.hasForm(filename) if not internalname: canv.beginForm(filename) canv.saveState() x, y = self.x, self.y w, h = self.width, self.height canv.drawInlineImage(filename, x, y, w, h) canv.restoreState() canv.endForm() canv.doForm(filename) else: canv.doForm(filename)
def drawOn(self, canv): filename = self.filename if filename: internalname = canv._doc.hasForm(filename) if not internalname: canv.beginForm(filename) canv.saveState() x, y = self.x, self.y w, h = self.width, self.height canv.drawInlineImage(filename, x, y, w, h) canv.restoreState() canv.endForm() canv.doForm(filename) else: canv.doForm(filename)
5,509
def __init__(self, cmds=None, parent=None, **kw): #handle inheritance from parent first. commands = [] if parent: # copy the parents list at construction time commands = commands + parent.getCommands() self._opts = parent._opts if cmds: commands = commands + cmds self._cmds = commands self._opts={} self._opts.update(kw)
def __init__(self, cmds=None, parent=None, **kw): #handle inheritance from parent first. commands = [] if parent: # copy the parents list at construction time commands = commands + parent.getCommands() self._opts = parent._opts if cmds: commands = commands + list(cmds) self._cmds = commands self._opts={} self._opts.update(kw)
5,510
def cvs_checkout(d): os.chdir(d) recursive_rmdir(cvsdir) cvs = find_exe('cvs') if cvs is None: os.exit(1) os.environ['CVSROOT']=':pserver:%s@cvs.reportlab.sourceforge.net:/cvsroot/reportlab' % USER if release: do_exec(cvs+(' export -r %s reportlab' % tagname), 'the export phase') else: if py2pdf: do_exec(cvs+' co reportlab', 'the checkout phase') # now we need to move the files & delete those we don't need dst = py2pdf_dir recursive_rmdir(dst) os.mkdir(dst) do_exec("mv reportlab/demos/py2pdf/py2pdf.py %s"%dst, "mv py2pdf.py") do_exec("mv reportlab/demos/py2pdf/PyFontify.py %s" % dst, "mv pyfontify.py") do_exec("rm -r reportlab/demos reportlab/platypus reportlab/lib/styles.py reportlab/README.pdfgen.txt", "rm") do_exec("mv reportlab %s" dst) CVS_remove(dst) else: do_exec(cvs+' co reportlab', 'the checkout phase')
def cvs_checkout(d): os.chdir(d) recursive_rmdir(cvsdir) cvs = find_exe('cvs') if cvs is None: os.exit(1) os.environ['CVSROOT']=':pserver:%s@cvs.reportlab.sourceforge.net:/cvsroot/reportlab' % USER if release: do_exec(cvs+(' export -r %s reportlab' % tagname), 'the export phase') else: if py2pdf: do_exec(cvs+' co reportlab', 'the checkout phase') # now we need to move the files & delete those we don't need dst = py2pdf_dir recursive_rmdir(dst) os.mkdir(dst) do_exec("mv reportlab/demos/py2pdf/py2pdf.py %s"%dst, "mv py2pdf.py") do_exec("mv reportlab/demos/py2pdf/PyFontify.py %s" % dst, "mv pyfontify.py") do_exec("rm -r reportlab/demos reportlab/platypus reportlab/lib/styles.py reportlab/README.pdfgen.txt", "rm") do_exec("mv reportlab %s" % dst) CVS_remove(dst) else: do_exec(cvs+' co reportlab', 'the checkout phase')
5,511
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""" return []
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""" return []
5,512
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""" return []
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""" return []
5,513
def split(self,flowable): '''calls split on the flowable''' y = self.y p = self.y1p s = self.atTop and 0 or flowable.getSpaceBefore() return flowable.wrap(self.width, y-p-s)
def split(self,flowable): '''calls split on the flowable''' y = self.y p = self.y1p s = self.atTop and 0 or flowable.getSpaceBefore() return flowable.wrap(self.width, y-p-s)
5,514
def doIt(file) : """Generates a PDF document, save it into file, and returns Python source code. file : either a filename or a file-like object. returns : the equivalent Python source code as a string of text. """'''
def doIt(file, regenerate=0) : """Generates a PDF document, save it into file. file : either a filename or a file-like object. returns : the equivalent Python source code as a string of text. """'''
5,515
def doIt(file) : """Generates a PDF document, save it into file, and returns Python source code. file : either a filename or a file-like object. returns : the equivalent Python source code as a string of text. """'''
def doIt(file) : """Generates a PDF document, save it into file, and returns Python source code. file : either a filename or a file-like object. regenerate : if set then this function returns the Python source code which when run will produce the same result. if unset then this function returns None, and is much faster. """ if regenerate : from reportlab.pdfgen.pycanvas import Canvas else : from reportlab.pdfgen.canvas import Canvas '''
5,516
def doIt(file) : """Generates a PDF document, save it into file, and returns Python source code. file : either a filename or a file-like object. returns : the equivalent Python source code as a string of text. """'''
def doIt(file) : """Generates a PDF document, save it into file, and returns Python source code. file : either a filename or a file-like object. returns : the equivalent Python source code as a string of text. """'''
5,517
def doIt(file) : """Generates a PDF document, save it into file, and returns Python source code. file : either a filename or a file-like object. returns : the equivalent Python source code as a string of text. """'''
def doIt(file) : """Generates a PDF document, save it into file, and returns Python source code. file : either a filename or a file-like object. returns : the equivalent Python source code as a string of text. """'''
5,518
def buildargs(*args, **kwargs) : arguments = "" for arg in args : arguments += "%s, " % repr(arg) for (kw, val) in kwargs.items() : arguments += "%s=%s, " % (kw, repr(val)) if arguments[-2:] == ", " : arguments = arguments[:-2] return arguments
def buildargs(*args, **kwargs) : arguments = "" for arg in args : arguments += "%s, " % repr(arg) for (kw, val) in kwargs.items() : arguments += "%s=%s, " % (kw, repr(val)) if arguments[-2:] == ", " : arguments = arguments[:-2] return arguments
5,519
def __call__(self, *args, **kwargs) : global _in if not _in : self._parent._parent._PyWrite(" %s.%s(%s)" % (self._parent._name, self._action, apply(buildargs, args, kwargs))) _in += 1 retcode = apply(getattr(self._parent._object, self._action), args, kwargs) _in -= 1 return retcode
def __call__(self, *args, **kwargs) : """The fake method is called, print it then call the real one.""" if not self._parent._parent._in : self._precomment() self._parent._parent._PyWrite(" %s.%s(%s)" % (self._parent._name, self._action, apply(buildargs, args, kwargs))) _in += 1 retcode = apply(getattr(self._parent._object, self._action), args, kwargs) _in -= 1 return retcode
5,520
def __call__(self, *args, **kwargs) : global _in if not _in : self._parent._parent._PyWrite(" %s.%s(%s)" % (self._parent._name, self._action, apply(buildargs, args, kwargs))) _in += 1 retcode = apply(getattr(self._parent._object, self._action), args, kwargs) _in -= 1 return retcode
def __call__(self, *args, **kwargs) : global _in if not _in : self._parent._parent._PyWrite(" %s.%s(%s)" % (self._parent._name, self._action, apply(buildargs, args, kwargs))) self._postcomment() self._parent._parent._in += 1 retcode = apply(getattr(self._parent._object, self._action), args, kwargs) _in -= 1 return retcode
5,521
def __call__(self, *args, **kwargs) : global _in if not _in : self._parent._parent._PyWrite(" %s.%s(%s)" % (self._parent._name, self._action, apply(buildargs, args, kwargs))) _in += 1 retcode = apply(getattr(self._parent._object, self._action), args, kwargs) _in -= 1 return retcode
def __call__(self, *args, **kwargs) : global _in if not _in : self._parent._parent._PyWrite(" %s.%s(%s)" % (self._parent._name, self._action, apply(buildargs, args, kwargs))) _in += 1 retcode = apply(getattr(self._parent._object, self._action), args, kwargs) self._parent._parent._in -= 1 return retcode
5,522
def __call__(self, *args, **kwargs) : global _in try : if (not _in) and (self._action != "__nonzero__") : if self._action == "showPage" : self._parent._PyWrite("\n # Ends page %i" % self._parent._pagenumber) elif self._action == "saveState" : state = {} d = self._parent._object.__dict__ for name in self._parent._object.STATE_ATTRIBUTES: state[name] = d[name] self._parent._PyWrite("\n # Saves context level %i %s" % (self._parent._contextlevel, state)) self._parent._contextlevel += 1 elif self._action == "restoreState" : self._parent._contextlevel -= 1 self._parent._PyWrite("\n # Restores context level %i %s" % (self._parent._contextlevel, self._parent._object.state_stack[-1])) elif self._action == "beginForm" : self._parent._formnumber += 1 self._parent._PyWrite("\n # Begins form %i" % self._parent._formnumber) elif self._action == "endForm" : self._parent._PyWrite("\n # Ends form %i" % self._parent._formnumber) elif self._action == "save" : self._parent._PyWrite("\n # Saves the PDF document to disk") self._parent._PyWrite(" %s.%s(%s)" % (self._parent._name, self._action, apply(buildargs, args, kwargs))) if self._action == "showPage" : self._parent._pagenumber += 1 self._parent._PyWrite("\n # Begins page %i" % self._parent._pagenumber) elif self._action == "endForm" : self._parent._PyWrite("") _in += 1 retcode = apply(getattr(self._parent._object, self._action), args, kwargs) _in -= 1 return retcode except AttributeError : # __nonzero__, but I don't know why _in -= 1 return 1
def __call__(self, *args, **kwargs) : global _in try : if (not _in) and (self._action != "__nonzero__") : if self._action == "showPage" : self._parent._PyWrite("\n # Ends page %i" % self._parent._pagenumber) elif self._action == "saveState" : state = {} d = self._parent._object.__dict__ for name in self._parent._object.STATE_ATTRIBUTES: state[name] = d[name] self._parent._PyWrite("\n # Saves context level %i %s" % (self._parent._contextlevel, state)) self._parent._contextlevel += 1 elif self._action == "restoreState" : self._parent._contextlevel -= 1 self._parent._PyWrite("\n # Restores context level %i %s" % (self._parent._contextlevel, self._parent._object.state_stack[-1])) elif self._action == "beginForm" : self._parent._formnumber += 1 self._parent._PyWrite("\n # Begins form %i" % self._parent._formnumber) elif self._action == "endForm" : self._parent._PyWrite("\n # Ends form %i" % self._parent._formnumber) elif self._action == "save" : self._parent._PyWrite("\n # Saves the PDF document to disk") self._parent._PyWrite(" %s.%s(%s)" % (self._parent._name, self._action, apply(buildargs, args, kwargs))) if self._action == "showPage" : self._parent._pagenumber += 1 self._parent._PyWrite("\n # Begins page %i" % self._parent._pagenumber) elif self._action == "endForm" : self._parent._PyWrite("") _in += 1 retcode = apply(getattr(self._parent._object, self._action), args, kwargs) _in -= 1 return retcode except AttributeError : # __nonzero__, but I don't know why _in -= 1 return 1
5,523
def __init__(self, *args, **kwargs) : self._contextlevel = 0 self._pagenumber = 1 self._formnumber = 0 self._footerpresent = 0 self._object = apply(canvas.Canvas, args, kwargs) self._pyfile = cStringIO.StringIO() self._PyWrite(PyHeader) try : del kwargs["filename"] except KeyError : pass self._PyWrite(" # create the PDF document\n %s = pycanvas.Canvas(file, %s)\n\n # Begins page 1" % (self._name, apply(buildargs, args[1:], kwargs)))
def __init__(self, *args, **kwargs) : self._contextlevel = 0 self._pagenumber = 1 self._formnumber = 0 self._footerpresent = 0 self._object = apply(canvas.Canvas, args, kwargs) self._pyfile = cStringIO.StringIO() self._PyWrite(PyHeader) try : del kwargs["filename"] except KeyError : pass self._PyWrite(" def __nonzero__(self) : """This is needed by platypus' tables.""" return 1 # create the PDF document\n %s = pycanvas.Canvas(file, %s)\n\n # Begins page 1" % (self._name, apply(buildargs, args[1:], kwargs)))
5,524
def _drawHLines(self, (sc, sr), (ec, er), weight, color): self._prepLine(weight, color) scp = self._colpositions[sc] ecp = self._colpositions[ec+1] for rowpos in self._rowpositions[sr:er+1]: self.canv.line(scp, rowpos, ecp, rowpos)
def _drawHLines(self, (sc, sr), (ec, er), weight, color): self._prepLine(weight, color) scp = ecp[0] ecp = ecp[-1] for rowpos in rp: self.canv.line(scp, rowpos, ecp, rowpos)
5,525
def _drawVLines(self, (sc, sr), (ec, er), weight, color): self._prepLine(weight, color) srp = self._rowpositions[sr] erp = self._rowpositions[er+1] for colpos in self._colpositions[sc:ec+1]: self.canv.line(colpos, srp, colpos, erp)
def _drawVLines(self, (sc, sr), (ec, er), weight, color): self._prepLine(weight, color) srp = erp[0] erp = erp[-1] for colpos in cp: self.canv.line(colpos, srp, colpos, erp)
5,526
def _drawBkgrnd(self): for cmd, (sc, sr), (ec, er), color in self._bkgrndcmds: if sc < 0: sc = sc + self._ncols if ec < 0: ec = ec + self._ncols if sr < 0: sr = sr + self._nrows if er < 0: er = er + self._nrows color = colors.toColor(color) x0 = self._colpositions[sc] y0 = self._rowpositions[sr] x1 = self._colpositions[ec+1] y1 = self._rowpositions[er+1] self.canv.setFillColor(color) self.canv.rect(x0, y0, x1-x0, y1-y0,stroke=0,fill=1)
def _drawBkgrnd(self): for cmd, (sc, sr), (ec, er), color in self._bkgrndcmds: if sc < 0: sc = sc + ncols if ec < 0: ec = ec + ncols if sr < 0: sr = sr + nrows if er < 0: er = er + nrows color = colors.toColor(color) x0 = self._colpositions[sc] y0 = self._rowpositions[sr] x1 = self._colpositions[ec+1] y1 = self._rowpositions[er+1] self.canv.setFillColor(color) self.canv.rect(x0, y0, x1-x0, y1-y0,stroke=0,fill=1)
5,527
def _drawBkgrnd(self): for cmd, (sc, sr), (ec, er), color in self._bkgrndcmds: if sc < 0: sc = sc + self._ncols if ec < 0: ec = ec + self._ncols if sr < 0: sr = sr + self._nrows if er < 0: er = er + self._nrows color = colors.toColor(color) x0 = self._colpositions[sc] y0 = self._rowpositions[sr] x1 = self._colpositions[ec+1] y1 = self._rowpositions[er+1] self.canv.setFillColor(color) self.canv.rect(x0, y0, x1-x0, y1-y0,stroke=0,fill=1)
def _drawBkgrnd(self): for cmd, (sc, sr), (ec, er), color in self._bkgrndcmds: if sc < 0: sc = sc + self._ncols if ec < 0: ec = ec + self._ncols if sr < 0: sr = sr + self._nrows if er < 0: er = er + self._nrows color = colors.toColor(color) x0 = self._colpositions[sc] y0 = self._rowpositions[sr] x1 = self._colpositions[min(ec+1,ncols)] y1 = self._rowpositions[min(er+1,nrows)] self.canv.setFillColor(color) self.canv.rect(x0, y0, x1-x0, y1-y0,stroke=0,fill=1)
5,528
def test(): from reportlab.lib.units import inch rowheights = (24, 16, 16, 16, 16) rowheights2 = (24, 16, 16, 16, 30) colwidths = (50, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32) data = ( ('', 'Jan', 'Feb', 'Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89), ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119), ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13), ('Hats', 893, 912, '1,212', 643, 789, 159, 888, '1,298', 832, 453, '1,344','2,843') ) data2 = ( ('', 'Jan', 'Feb', 'Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89), ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119), ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13), ('Hats\nLarge', 893, 912, '1,212', 643, 789, 159, 888, '1,298', 832, 453, '1,344','2,843') ) styleSheet = getSampleStyleSheet() lst = [] lst.append(Paragraph("Tables", styleSheet['Heading1'])) lst.append(Paragraph(__doc__, styleSheet['BodyText'])) lst.append(Paragraph("The Tables (shown in different styles below) were created using the following code:", styleSheet['BodyText'])) lst.append(Preformatted(""" colwidths = (50, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32) rowheights = (24, 16, 16, 16, 16) data = ( ('', 'Jan', 'Feb', 'Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89), ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119), ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13), ('Hats', 893, 912, '1,212', 643, 789, 159, 888, '1,298', 832, 453, '1,344','2,843') ) t = Table(data, colwidths, rowheights) """, styleSheet['Code'], dedent=4)) lst.append(Paragraph(""" You can then give the Table a TableStyle object to control its format. The first TableStyle used was created as follows: """, styleSheet['BodyText'])) lst.append(Preformatted("""
def test(): from reportlab.lib.units import inch rowheights = (24, 16, 16, 16, 16) rowheights2 = (24, 16, 16, 16, 30) colwidths = (50, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32) data = ( ('', 'Jan', 'Feb', 'Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89), ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119), ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13), ('Hats', 893, 912, '1,212', 643, 789, 159, 888, '1,298', 832, 453, '1,344','2,843') ) data2 = ( ('', 'Jan', 'Feb', 'Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89), ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119), ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13), ('Hats\nLarge', 893, 912, '1,212', 643, 789, 159, 888, '1,298', 832, 453, '1,344','2,843') ) styleSheet = getSampleStyleSheet() lst = [] lst.append(Paragraph("Tables", styleSheet['Heading1'])) lst.append(Paragraph(__doc__, styleSheet['BodyText'])) lst.append(Paragraph("The Tables (shown in different styles below) were created using the following code:", styleSheet['BodyText'])) lst.append(Preformatted(""" colwidths = (50, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32) rowheights = (24, 16, 16, 16, 16) data = ( ('', 'Jan', 'Feb', 'Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89), ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119), ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13), ('Hats', 893, 912, '1,212', 643, 789, 159, 888, '1,298', 832, 453, '1,344','2,843') ) t = Table(data, colwidths, rowheights) """, styleSheet['Code'], dedent=4)) lst.append(Paragraph(""" You can then give the Table a TableStyle object to control its format. The first TableStyle used was created as follows: """, styleSheet['BodyText'])) lst.append(Preformatted("""
5,529
def __init__(self,filename, pagesize=(595.27,841.89), bottomup = 1, pageCompression=1, encoding=rl_config.defaultEncoding, verbosity=0): """Create a canvas of a given size. etc. Most of the attributes are private - we will use set/get methods as the preferred interface. Default page size is A4.""" self._filename = filename self._encodingName = encoding self._doc = pdfdoc.PDFDocument(encoding)
def __init__(self,filename, pagesize=(595.27,841.89), bottomup = 1, pageCompression=1, encoding=rl_config.defaultEncoding, verbosity=0): """Create a canvas of a given size. etc. Most of the attributes are private - we will use set/get methods as the preferred interface.self.init_graphics_state() self.state_stack = [] def init_graphics_state(self): Default page size is A4.""" self._filename = filename self._encodingName = encoding self._doc = pdfdoc.PDFDocument(encoding)
5,530
def markfilename(filename): # with the Mac, we need to tag the file in a special #way so the system knows it is a PDF file. #This supplied by Joe Strout import os if os.name == 'mac': import macfs try: macfs.FSSpec(filename).SetCreatorType('CARO','PDF ') except: pass
def markfilename(filename): # with the Mac, we need to tag the file in a special #way so the system knows it is a PDF file. #This supplied by Joe Strout import os if os.name == 'mac': import macfs try: macfs.FSSpec(filename).SetCreatorType('CARO','PDF ') except: pass
5,531
def info(self): # the representation of self in file if any (should be None or PDFDict) return None
def info(self): # the representation of self in file if any (should be None or PDFDict) return None
5,532
def info(self): # the representation of self in file if any (should be None or PDFDict) return None
def info(self): # the representation of self in file if any (should be None or PDFDict) return None
5,533
def __init__(self, encoding=rl_config.defaultEncoding, dummyoutline=0): #self.defaultStreamFilters = [PDFBase85Encode, PDFZCompress] # for testing! #self.defaultStreamFilters = [PDFZCompress] # for testing! assert encoding in ['MacRomanEncoding', 'WinAnsiEncoding', 'MacRoman', 'WinAnsi'], 'Unsupported encoding %s' % encoding if encoding[-8:] <> 'Encoding': encoding = encoding + 'Encoding' self.encoding = encoding # signature for creating PDF ID import md5, time sig = self.signature = md5.new() sig.update("a reportlab document") sig.update(repr(time.time())) # initialize with timestamp digest # mapping of internal identifier ("Page001") to PDF objectnumber and generation number (34, 0) self.idToObjectNumberAndVersion = {} # mapping of internal identifier ("Page001") to PDF object (PDFPage instance) self.idToObject = {} # internal id to file location self.idToOffset = {} # number to id self.numberToId = {} cat = self.Catalog = self._catalog = PDFCatalog() pages = self.Pages = PDFPages() cat.Pages = pages if dummyoutline: outlines = PDFOutlines0() else: outlines = PDFOutlines() self.Outlines = self.outline = outlines cat.Outlines = outlines self.info = PDFInfo() #self.Reference(self.Catalog) #self.Reference(self.Info) self.fontMapping = {} #make an empty font dictionary DD = PDFDictionary({}) DD.__Comment__ = "The standard fonts dictionary" DDR = self.Reference(DD, BasicFonts)
def __init__(self, encoding=rl_config.defaultEncoding, dummyoutline=0): #self.defaultStreamFilters = [PDFBase85Encode, PDFZCompress] # for testing! #self.defaultStreamFilters = [PDFZCompress] # for testing! assert encoding in ['MacRomanEncoding', 'WinAnsiEncoding', 'MacRoman', 'WinAnsi'], 'Unsupported encoding %s' % encoding if encoding[-8:] <> 'Encoding': encoding = encoding + 'Encoding' self.encoding = encoding # signature for creating PDF ID import md5, time sig = self.signature = md5.new() sig.update("a reportlab document") sig.update(repr(time.time())) # initialize with timestamp digest # mapping of internal identifier ("Page001") to PDF objectnumber and generation number (34, 0) self.idToObjectNumberAndVersion = {} # mapping of internal identifier ("Page001") to PDF object (PDFPage instance) self.idToObject = {} # internal id to file location self.idToOffset = {} # number to id self.numberToId = {} cat = self.Catalog = self._catalog = PDFCatalog() pages = self.Pages = PDFPages() cat.Pages = pages if dummyoutline: outlines = PDFOutlines0() else: outlines = PDFOutlines() self.Outlines = self.outline = outlines cat.Outlines = outlines self.info = PDFInfo() #self.Reference(self.Catalog) #self.Reference(self.Info) self.fontMapping = {} #make an empty font dictionary DD = PDFDictionary({}) DD.__Comment__ = "The standard fonts dictionary" DDR = self.Reference(DD, BasicFonts)
5,534
def updateSignature(self, thing): "add information to the signature" if self._ID: return # but not if its used already! self.signature.update(str(thing))
def updateSignature(self, thing): "add information to the signature" if self._ID: return # but not if its used already! self.signature.update(str(thing))
5,535
def SaveToFile(self, filename, canvas): # add info stuff to signature self.info.digest(self.signature) ### later: maybe add more info to sig? # prepare outline self.Reference(self.Catalog) self.Reference(self.info) outline = self.outline outline.prepare(self, canvas) from types import StringType if type(filename) is StringType: myfile = 1 f = open(filename, "wb") else: myfile = 0 f = filename # IT BETTER BE A FILE-LIKE OBJECT! txt = self.format() f.write(txt) if myfile: f.close() markfilename(filename) # do platform specific file junk
def SaveToFile(self, filename, canvas): # add info stuff to signature self.info.digest(self.signature) ### later: maybe add more info to sig? # prepare outline self.Reference(self.Catalog) self.Reference(self.info) outline = self.outline outline.prepare(self, canvas) from types import StringType if type(filename) is StringType: myfile = 1 f = open(filename, "wb") else: myfile = 0 f = filename # IT BETTER BE A FILE-LIKE OBJECT! txt = self.format() f.write(txt) if myfile: f.close() markfilename(filename) # do platform specific file junk
5,536
def inForm(self): """specify that we are in a form xobject (disable page features, etc)""" # don't need this check anymore since going in a form pushes old context at canvas level. #if self.inObject not in ["form", None]: # raise ValueError, "can't go in form already in object %s" % self.inObject self.inObject = "form" # don't need to do anything else, I think...
def inForm(self): """specify that we are in a form xobject (disable page features, etc)""" # don't need this check anymore since going in a form pushes old context at canvas level. #if self.inObject not in ["form", None]: # raise ValueError, "can't go in form already in object %s" % self.inObject self.inObject = "form" # don't need to do anything else, I think...
5,537
def getInternalFontName(self, psfontname): fm = self.fontMapping if fm.has_key(psfontname): return fm[psfontname] else: try: # does pdfmetrics know about it? if so, add from reportlab.pdfbase import pdfmetrics fontObj = pdfmetrics.getFont(psfontname) fontObj.addObjects(self) #self.addFont(fontObj) return fm[psfontname] except KeyError: raise PDFError, "Font %s not known!" % repr(psfontname)
def getInternalFontName(self, psfontname): fm = self.fontMapping if fm.has_key(psfontname): return fm[psfontname] else: try: # does pdfmetrics know about it? if so, add from reportlab.pdfbase import pdfmetrics fontObj = pdfmetrics.getFont(psfontname) fontObj.addObjects(self) #self.addFont(fontObj) return fm[psfontname] except KeyError: raise PDFError, "Font %s not known!" % repr(psfontname)
5,538
def getInternalFontName(self, psfontname): fm = self.fontMapping if fm.has_key(psfontname): return fm[psfontname] else: try: # does pdfmetrics know about it? if so, add from reportlab.pdfbase import pdfmetrics fontObj = pdfmetrics.getFont(psfontname) fontObj.addObjects(self) #self.addFont(fontObj) return fm[psfontname] except KeyError: raise PDFError, "Font %s not known!" % repr(psfontname)
def getInternalFontName(self, psfontname): fm = self.fontMapping if fm.has_key(psfontname): return fm[psfontname] else: try: # does pdfmetrics know about it? if so, add from reportlab.pdfbase import pdfmetrics fontObj = pdfmetrics.getFont(psfontname) fontObj.addObjects(self) #self.addFont(fontObj) return fm[psfontname] except KeyError: raise PDFError, "Font %s not known!" % repr(psfontname)
5,539
def addPage(self, page): name = self.thisPageName() self.Reference(page, name) self.Pages.addPage(page) self.pageCounter = self.pageCounter+1 self.inObject = None
def addPage(self, page): name = self.thisPageName() self.Reference(page, name) self.Pages.addPage(page) self.pageCounter = self.pageCounter+1 self.inObject = None
5,540
def annotationName(self, externalname): return "Annot.%s"%externalname
def annotationName(self, externalname): return "Annot.%s"%externalname
5,541
def addAnnotation(self, name, annotation): self.Reference(annotation, self.annotationName(name))
def addAnnotation(self, name, annotation): self.Reference(annotation, self.annotationName(name))
5,542
def refAnnotation(self, name): internalname = self.annotationName(name) return PDFObjectReference(internalname)
def refAnnotation(self, name): internalname = self.annotationName(name) return PDFObjectReference(internalname)
5,543
def setTitle(self, title): "embeds in PDF file" self.info.title = title
def setTitle(self, title): "embeds in PDF file" self.info.title = title
5,544
def setAuthor(self, author): "embedded in PDF file" self.info.author = author
def setAuthor(self, author): "embedded in PDF file" self.info.author = author
5,545
def format(self): # register the Catalog/INfo and then format the objects one by one until exhausted # (possible infinite loop if there is a bug that continually makes new objects/refs...) # Prepare encryption self.encrypt.prepare(self) cat = self.Catalog info = self.info self.Reference(self.Catalog) self.Reference(self.info) # register the encryption dictionary if present encryptref = None encryptinfo = self.encrypt.info() if encryptinfo: encryptref = self.Reference(encryptinfo) # make std fonts (this could be made optional counter = 0 # start at first object (object 1 after preincrement) ids = [] # the collection of object ids in object number order numbertoid = self.numberToId idToNV = self.idToObjectNumberAndVersion idToOb = self.idToObject idToOf = self.idToOffset ### note that new entries may be "appended" DURING FORMATTING done = None File = PDFFile() # output collector while done is None: counter = counter+1 # do next object... if numbertoid.has_key(counter): id = numbertoid[counter] #printidToOb obj = idToOb[id] IO = PDFIndirectObject(id, obj) # register object number and version #encrypt.register(id, IOf = IO.format(self) # add a comment to the PDF output if DoComments: File.add("%% %s %s %s" % (repr(id), repr(repr(obj)[:50]), LINEEND)) offset = File.add(IOf) idToOf[id] = offset ids.append(id) else: done = 1 # sanity checks (must happen AFTER formatting) lno = len(numbertoid) if counter-1!=lno: raise ValueError, "counter %s doesn't match number to id dictionary %s" %(counter, lno) # now add the xref xref = PDFCrossReferenceTable() xref.addsection(0, ids) xreff = xref.format(self) xrefoffset = File.add(xreff) # now add the trailer trailer = PDFTrailer( startxref = xrefoffset, Size = lno+1, Root = self.Reference(cat), Info = self.Reference(info), Encrypt = encryptref, ID = self.ID(), ) trailerf = trailer.format(self) File.add(trailerf) # return string format for pdf file return File.format(self)
def format(self): # register the Catalog/INfo and then format the objects one by one until exhausted # (possible infinite loop if there is a bug that continually makes new objects/refs...) # Prepare encryption self.encrypt.prepare(self) cat = self.Catalog info = self.info self.Reference(self.Catalog) self.Reference(self.info) # register the encryption dictionary if present encryptref = None encryptinfo = self.encrypt.info() if encryptinfo: encryptref = self.Reference(encryptinfo) # make std fonts (this could be made optional counter = 0 # start at first object (object 1 after preincrement) ids = [] # the collection of object ids in object number order numbertoid = self.numberToId idToNV = self.idToObjectNumberAndVersion idToOb = self.idToObject idToOf = self.idToOffset ### note that new entries may be "appended" DURING FORMATTING done = None File = PDFFile() # output collector while done is None: counter = counter+1 # do next object... if numbertoid.has_key(counter): id = numbertoid[counter] #printidToOb obj = idToOb[id] IO = PDFIndirectObject(id, obj) # register object number and version #encrypt.register(id, IOf = IO.format(self) # add a comment to the PDF output if DoComments: File.add("%% %s %s %s" % (repr(id), repr(repr(obj)[:50]), LINEEND)) offset = File.add(IOf) idToOf[id] = offset ids.append(id) else: done = 1 # sanity checks (must happen AFTER formatting) lno = len(numbertoid) if counter-1!=lno: raise ValueError, "counter %s doesn't match number to id dictionary %s" %(counter, lno) # now add the xref xref = PDFCrossReferenceTable() xref.addsection(0, ids) xreff = xref.format(self) xrefoffset = File.add(xreff) # now add the trailer trailer = PDFTrailer( startxref = xrefoffset, Size = lno+1, Root = self.Reference(cat), Info = self.Reference(info), Encrypt = encryptref, ID = self.ID(), ) trailerf = trailer.format(self) File.add(trailerf) # return string format for pdf file return File.format(self)
5,546
def format(self): # register the Catalog/INfo and then format the objects one by one until exhausted # (possible infinite loop if there is a bug that continually makes new objects/refs...) # Prepare encryption self.encrypt.prepare(self) cat = self.Catalog info = self.info self.Reference(self.Catalog) self.Reference(self.info) # register the encryption dictionary if present encryptref = None encryptinfo = self.encrypt.info() if encryptinfo: encryptref = self.Reference(encryptinfo) # make std fonts (this could be made optional counter = 0 # start at first object (object 1 after preincrement) ids = [] # the collection of object ids in object number order numbertoid = self.numberToId idToNV = self.idToObjectNumberAndVersion idToOb = self.idToObject idToOf = self.idToOffset ### note that new entries may be "appended" DURING FORMATTING done = None File = PDFFile() # output collector while done is None: counter = counter+1 # do next object... if numbertoid.has_key(counter): id = numbertoid[counter] #printidToOb obj = idToOb[id] IO = PDFIndirectObject(id, obj) # register object number and version #encrypt.register(id, IOf = IO.format(self) # add a comment to the PDF output if DoComments: File.add("%% %s %s %s" % (repr(id), repr(repr(obj)[:50]), LINEEND)) offset = File.add(IOf) idToOf[id] = offset ids.append(id) else: done = 1 # sanity checks (must happen AFTER formatting) lno = len(numbertoid) if counter-1!=lno: raise ValueError, "counter %s doesn't match number to id dictionary %s" %(counter, lno) # now add the xref xref = PDFCrossReferenceTable() xref.addsection(0, ids) xreff = xref.format(self) xrefoffset = File.add(xreff) # now add the trailer trailer = PDFTrailer( startxref = xrefoffset, Size = lno+1, Root = self.Reference(cat), Info = self.Reference(info), Encrypt = encryptref, ID = self.ID(), ) trailerf = trailer.format(self) File.add(trailerf) # return string format for pdf file return File.format(self)
def format(self): # register the Catalog/INfo and then format the objects one by one until exhausted # (possible infinite loop if there is a bug that continually makes new objects/refs...) # Prepare encryption self.encrypt.prepare(self) cat = self.Catalog info = self.info self.Reference(self.Catalog) self.Reference(self.info) # register the encryption dictionary if present encryptref = None encryptinfo = self.encrypt.info() if encryptinfo: encryptref = self.Reference(encryptinfo) # make std fonts (this could be made optional counter = 0 # start at first object (object 1 after preincrement) ids = [] # the collection of object ids in object number order numbertoid = self.numberToId idToNV = self.idToObjectNumberAndVersion idToOb = self.idToObject idToOf = self.idToOffset ### note that new entries may be "appended" DURING FORMATTING done = None File = PDFFile() # output collector while done is None: counter = counter+1 # do next object... if numbertoid.has_key(counter): id = numbertoid[counter] #printidToOb obj = idToOb[id] IO = PDFIndirectObject(id, obj) # register object number and version #encrypt.register(id, IOf = IO.format(self) # add a comment to the PDF output if DoComments: File.add("%% %s %s %s" % (repr(id), repr(repr(obj)[:50]), LINEEND)) offset = File.add(IOf) idToOf[id] = offset ids.append(id) else: done = 1 # sanity checks (must happen AFTER formatting) lno = len(numbertoid) if counter-1!=lno: raise ValueError, "counter %s doesn't match number to id dictionary %s" %(counter, lno) # now add the xref xref = PDFCrossReferenceTable() xref.addsection(0, ids) xreff = xref.format(self) xrefoffset = File.add(xreff) # now add the trailer trailer = PDFTrailer( startxref = xrefoffset, Size = lno+1, Root = self.Reference(cat), Info = self.Reference(info), Encrypt = encryptref, ID = self.ID(), ) trailerf = trailer.format(self) File.add(trailerf) # return string format for pdf file return File.format(self)
5,547
def getXObjectName(self, name): """Lets canvas find out what form is called internally. Never mind whether it is defined yet or not.""" return xObjectName(name)
def getXObjectName(self, name): """Lets canvas find out what form is called internally. Never mind whether it is defined yet or not.""" return xObjectName(name)
5,548
def xobjDict(self, formnames): """construct an xobject dict (for inclusion in a resource dict, usually) from a list of form names (images not yet supported)""" D = {} for name in formnames: internalname = xObjectName(name) reference = PDFObjectReference(internalname) D[internalname] = reference #print "xobjDict D", D return PDFDictionary(D)
def xobjDict(self, formnames): """construct an xobject dict (for inclusion in a resource dict, usually) from a list of form names (images not yet supported)""" D = {} for name in formnames: internalname = xObjectName(name) reference = PDFObjectReference(internalname) D[internalname] = reference #print "xobjDict D", D return PDFDictionary(D)
5,549
def __str__(self): return "(%s)" % pdfutils._escape(self.s)
def __str__(self): return "(%s)" % pdfutils._escape(self.s)
5,550
def PDFName(data): # might need to change this to class for encryption # NOTE: RESULT MUST ALWAYS SUPPORT MEANINGFUL COMPARISONS (EQUALITY) AND HASH # first convert the name ldata = list(data) index = 0 for thischar in data: if 0x21<=ord(thischar)<=0x7e and thischar not in "%()<>{}[]#": pass # no problemo else: hexord = hex(ord(thischar))[2:] # forget the 0x thing... ldata[index] = "#"+hexord index = index+1 data = string.join(ldata, "") return "/%s" % data
def PDFName(data): # might need to change this to class for encryption # NOTE: RESULT MUST ALWAYS SUPPORT MEANINGFUL COMPARISONS (EQUALITY) AND HASH # first convert the name ldata = list(data) index = 0 for thischar in data: if 0x21<=ord(thischar)<=0x7e and thischar not in "%()<>{}[]#": pass # no problemo else: hexord = hex(ord(thischar))[2:] # forget the 0x thing... ldata[index] = "#"+hexord index = index+1 data = string.join(ldata, "") return "/%s" % data
5,551
def decode(self, encoded): from reportlab.lib.utils import import_zlib zlib = import_zlib() if not zlib: raise ImportError, "cannot z-decompress zlib unavailable" return zlib.decompress(encoded)
def decode(self, encoded): from reportlab.lib.utils import import_zlib zlib = import_zlib() if not zlib: raise ImportError, "cannot z-decompress zlib unavailable" return zlib.decompress(encoded)
5,552
def decode(self, text): from pdfutils import _AsciiBase85Decode return _AsciiBase85Decode(text)
def decode(self, text): from pdfutils import _AsciiBase85Decode return _AsciiBase85Decode(text)
5,553
def teststream(content=None): #content = "" # test if content is None: content = teststreamcontent content = string.strip(content) content = string.replace(content, "\n", LINEEND) + LINEEND S = PDFStream() S.content = content S.filters = [PDFBase85Encode, PDFZCompress] # nothing else needed... S.__Comment__ = "test stream" return S
def teststream(content=None): #content = "" # test if content is None: content = teststreamcontent content = string.strip(content) content = string.replace(content, "\n", LINEEND) + LINEEND S = PDFStream() S.content = content S.filters = [PDFBase85Encode, PDFZCompress] # nothing else needed... S.__Comment__ = "test stream" return S
5,554
def format(self, document): strings = map(str, self.strings) # final conversion, in case of lazy objects return string.join(self.strings, "")
def format(self, document): strings = map(str, self.strings) # final conversion, in case of lazy objects return string.join(self.strings, "")
5,555
def format(self, document): fdict = format(self.dict, document) D = LINEENDDICT.copy() D["dict"] = fdict D["startxref"] = self.startxref return TRAILERFMT % D
def format(self, document): fdict = format(self.dict, document) D = LINEENDDICT.copy() D["dict"] = fdict D["startxref"] = self.startxref return TRAILERFMT % D
5,556
def showFullScreen(self): self.PageMode = PDFName("FullScreen")
def showFullScreen(self): self.PageMode = PDFName("FullScreen")
5,557
def setPageTransition(self, tranDict): self.Trans = PDFDictionary(tranDict)
def setPageTransition(self, tranDict): self.Trans = PDFDictionary(tranDict)
5,558
def check_format(self, document): # set up parameters unless usual behaviour is suppressed if self.Override_default_compilation: return self.MediaBox = self.MediaBox or PDFArray([0, 0, self.pagewidth, self.pageheight]) if not self.Annots: self.Annots = None else: #print self.Annots #raise ValueError, "annotations not reimplemented yet" if type(self.Annots) is not types.InstanceType: self.Annots = PDFArray(self.Annots) if not self.Contents: stream = self.stream if not stream: self.Contents = teststream() else: S = PDFStream() if self.compression: S.filters = [PDFZCompress, PDFBase85Encode] S.content = stream S.__Comment__ = "page stream" self.Contents = S if not self.Resources: resources = PDFResourceDictionary() # fonts! resources.basicFonts() if self.hasImages: resources.allProcs() else: resources.basicProcs() if self.XObjects: #print "XObjects", self.XObjects.dict resources.XObject = self.XObjects self.Resources = resources if not self.Parent: pages = document.Pages self.Parent = document.Reference(pages)
def check_format(self, document): # set up parameters unless usual behaviour is suppressed if self.Override_default_compilation: return self.MediaBox = self.MediaBox or PDFArray([0, 0, self.pagewidth, self.pageheight]) if not self.Annots: self.Annots = None else: #print self.Annots #raise ValueError, "annotations not reimplemented yet" if type(self.Annots) is not types.InstanceType: self.Annots = PDFArray(self.Annots) if not self.Contents: stream = self.stream if not stream: self.Contents = teststream() else: S = PDFStream() if self.compression: S.filters = [PDFZCompress, PDFBase85Encode] S.content = stream S.__Comment__ = "page stream" self.Contents = S if not self.Resources: resources = PDFResourceDictionary() # fonts! resources.basicFonts() if self.hasImages: resources.allProcs() else: resources.basicProcs() if self.XObjects: #print "XObjects", self.XObjects.dict resources.XObject = self.XObjects self.Resources = resources if not self.Parent: pages = document.Pages self.Parent = document.Reference(pages)
5,559
def format(self, document): return self.text
def format(self, document): return self.text
5,560
def format(self, document): D = {} D["Title"] = PDFString(self.Title) D["Parent"] = self.Parent D["Dest"] = self.Dest for n in ("Prev", "Next", "First", "Last", "Count"): v = getattr(self, n) if v is not None: D[n] = v PD = PDFDictionary(D) return PD.format(document)
def format(self, document): D = {} D["Title"] = PDFString(self.Title) D["Parent"] = self.Parent D["Dest"] = self.Dest for n in ("Prev", "Next", "First", "Last", "Count"): v = getattr(self, n) if v is not None: D[n] = v PD = PDFDictionary(D) return PD.format(document)
5,561
def addOutlineEntry(self, destinationname, level=0, title=None, closed=None): """destinationname of None means "close the tree" """ from types import IntType, TupleType if destinationname is None and level!=0: raise ValueError, "close tree must have level of 0" if type(level) is not IntType: raise ValueError, "level must be integer, got %s" % type(level) if level<0: raise ValueError, "negative levels not allowed" if title is None: title = destinationname currentlevel = self.currentlevel stack = self.levelstack tree = self.buildtree # adjust currentlevel and stack to match level if level>currentlevel: if level>currentlevel+1: raise ValueError, "can't jump from outline level %s to level %s, need intermediates" %(currentlevel, level) level = currentlevel = currentlevel+1 stack.append([]) while level<currentlevel: # pop off levels to match current = stack[-1] del stack[-1] previous = stack[-1] lastinprevious = previous[-1] if type(lastinprevious) is TupleType: (name, sectionlist) = lastinprevious raise ValueError, "cannot reset existing sections: " + repr(lastinprevious) else: name = lastinprevious sectionlist = current previous[-1] = (name, sectionlist) #sectionlist.append(current) currentlevel = currentlevel-1 if destinationname is None: return stack[-1].append(destinationname) self.destinationnamestotitles[destinationname] = title if closed: self.closedict[destinationname] = 1 self.currentlevel = level
def addOutlineEntry(self, destinationname, level=0, title=None, closed=None): """destinationname of None means "close the tree" """ from types import IntType, TupleType if destinationname is None and level!=0: raise ValueError, "close tree must have level of 0" if type(level) is not IntType: raise ValueError, "level must be integer, got %s" % type(level) if level<0: raise ValueError, "negative levels not allowed" if title is None: title = destinationname currentlevel = self.currentlevel stack = self.levelstack tree = self.buildtree # adjust currentlevel and stack to match level if level>currentlevel: if level>currentlevel+1: raise ValueError, "can't jump from outline level %s to level %s, need intermediates" %(currentlevel, level) level = currentlevel = currentlevel+1 stack.append([]) while level<currentlevel: # pop off levels to match current = stack[-1] del stack[-1] previous = stack[-1] lastinprevious = previous[-1] if type(lastinprevious) is TupleType: (name, sectionlist) = lastinprevious raise ValueError, "cannot reset existing sections: " + repr(lastinprevious) else: name = lastinprevious sectionlist = current previous[-1] = (name, sectionlist) #sectionlist.append(current) currentlevel = currentlevel-1 if destinationname is None: return stack[-1].append(destinationname) self.destinationnamestotitles[destinationname] = title if closed: self.closedict[destinationname] = 1 self.currentlevel = level
5,562
def setDestinations(self, destinationtree): self.mydestinations = destinationtree
def setDestinations(self, destinationtree): self.mydestinations = destinationtree
5,563
def format(self, document): D = {} D["Type"] = PDFName("Outlines") c = self.count D["Count"] = c if c!=0: D["First"] = self.first D["Last"] = self.last PD = PDFDictionary(D) return PD.format(document)
def format(self, document): D = {} D["Type"] = PDFName("Outlines") c = self.count D["Count"] = c if c!=0: D["First"] = self.first D["Last"] = self.last PD = PDFDictionary(D) return PD.format(document)
5,564
def setNames(self, canvas, *nametree): desttree = self.translateNames(canvas, nametree) self.setDestinations(desttree)
def setNames(self, canvas, *nametree): desttree = self.translateNames(canvas, nametree) self.setDestinations(desttree)
5,565
def setNameList(self, canvas, nametree): "Explicit list so I don't need to do apply(...) in the caller" desttree = self.translateNames(canvas, nametree) self.setDestinations(desttree)
def setNameList(self, canvas, nametree): "Explicit list so I don't need to do apply(...) in the caller" desttree = self.translateNames(canvas, nametree) self.setDestinations(desttree)
5,566
def maketree(self, document, destinationtree, Parent=None, toplevel=0): from types import ListType, TupleType, DictType tdestinationtree = type(destinationtree) if toplevel: levelname = "Outline" Parent = document.Reference(document.Outlines) else: self.count = self.count+1 levelname = "Outline.%s" % self.count if Parent is None: raise ValueError, "non-top level outline elt parent must be specified" if tdestinationtree is not ListType and tdestinationtree is not TupleType: raise ValueError, "destinationtree must be list or tuple, got %s" nelts = len(destinationtree) lastindex = nelts-1 lastelt = firstref = lastref = None destinationnamestotitles = self.destinationnamestotitles closedict = self.closedict for index in range(nelts): eltobj = OutlineEntryObject() eltobj.Parent = Parent eltname = "%s.%s" % (levelname, index) eltref = document.Reference(eltobj, eltname) #document.add(eltname, eltobj) if lastelt is not None: lastelt.Next = eltref eltobj.Prev = lastref if firstref is None: firstref = eltref lastref = eltref lastelt = eltobj # advance eltobj lastref = eltref elt = destinationtree[index] te = type(elt) if te is DictType: # simple leaf {name: dest} leafdict = elt elif te is TupleType: # leaf with subsections: ({name: ref}, subsections) XXXX should clean up (see count(...)) try: (leafdict, subsections) = elt except: raise ValueError, "destination tree elt tuple should have two elts, got %s" % len(elt) eltobj.Count = count(subsections, closedict) (eltobj.First, eltobj.Last) = self.maketree(document, subsections, eltref) else: raise ValueError, "destination tree elt should be dict or tuple, got %s" % te try: [(Title, Dest)] = leafdict.items() except: raise ValueError, "bad outline leaf dictionary, should have one entry "+str(elt) eltobj.Title = destinationnamestotitles[Title] eltobj.Dest = Dest if te is TupleType and closedict.has_key(Dest): # closed subsection, count should be negative eltobj.Count = -eltobj.Count return (firstref, lastref)
def maketree(self, document, destinationtree, Parent=None, toplevel=0): from types import ListType, TupleType, DictType tdestinationtree = type(destinationtree) if toplevel: levelname = "Outline" Parent = document.Reference(document.Outlines) else: self.count = self.count+1 levelname = "Outline.%s" % self.count if Parent is None: raise ValueError, "non-top level outline elt parent must be specified" if tdestinationtree is not ListType and tdestinationtree is not TupleType: raise ValueError, "destinationtree must be list or tuple, got %s" nelts = len(destinationtree) lastindex = nelts-1 lastelt = firstref = lastref = None destinationnamestotitles = self.destinationnamestotitles closedict = self.closedict for index in range(nelts): eltobj = OutlineEntryObject() eltobj.Parent = Parent eltname = "%s.%s" % (levelname, index) eltref = document.Reference(eltobj, eltname) #document.add(eltname, eltobj) if lastelt is not None: lastelt.Next = eltref eltobj.Prev = lastref if firstref is None: firstref = eltref lastref = eltref lastelt = eltobj # advance eltobj lastref = eltref elt = destinationtree[index] te = type(elt) if te is DictType: # simple leaf {name: dest} leafdict = elt elif te is TupleType: # leaf with subsections: ({name: ref}, subsections) XXXX should clean up (see count(...)) try: (leafdict, subsections) = elt except: raise ValueError, "destination tree elt tuple should have two elts, got %s" % len(elt) eltobj.Count = count(subsections, closedict) (eltobj.First, eltobj.Last) = self.maketree(document, subsections, eltref) else: raise ValueError, "destination tree elt should be dict or tuple, got %s" % te try: [(Title, Dest)] = leafdict.items() except: raise ValueError, "bad outline leaf dictionary, should have one entry "+str(elt) eltobj.Title = destinationnamestotitles[Title] eltobj.Dest = Dest if te is TupleType and closedict.has_key(Dest): # closed subsection, count should be negative eltobj.Count = -eltobj.Count return (firstref, lastref)
5,567
def count(tree, closedict=None): """utility for outline: recursively count leaves in a tuple/list tree""" from operator import add from types import TupleType, ListType tt = type(tree) if tt is TupleType: # leaf with subsections XXXX should clean up this structural usage (leafdict, subsections) = tree [(Title, Dest)] = leafdict.items() if closedict and closedict.has_key(Dest): return 1 # closed tree element if tt is TupleType or tt is ListType: #return reduce(add, map(count, tree)) counts = [] for e in tree: counts.append(count(e, closedict)) return reduce(add, counts) return 1
def count(tree, closedict=None): """utility for outline: recursively count leaves in a tuple/list tree""" from operator import add from types import TupleType, ListType tt = type(tree) if tt is TupleType: # leaf with subsections XXXX should clean up this structural usage (leafdict, subsections) = tree [(Title, Dest)] = leafdict.items() if closedict and closedict.has_key(Dest): return 1 # closed tree element if tt is TupleType or tt is ListType: #return reduce(add, map(count, tree)) counts = [] for e in tree: counts.append(count(e, closedict)) return reduce(add, counts) return 1
5,568
def digest(self, md5object): # add self information to signature for x in (self.title, self.author, self.subject): md5object.update(str(x))
def digest(self, md5object): # add self information to signature for x in (self.title, self.author, self.subject): md5object.update(str(x))
5,569
def Dict(self): d = {} d.update(self.otherkw) d["Rect"] = self.Rect d["Contents"] = self.Contents d["Subtype"] = "/Text" return apply(self.AnnotationDict, (), d)
def Dict(self): d = {} d.update(self.otherkw) d["Rect"] = self.Rect d["Contents"] = self.Contents d["Subtype"] = "/Text" return apply(self.AnnotationDict, (), d)
5,570
def Dict(self): d = {} d.update(self.otherkw) d["Rect"] = self.Rect d["Contents"] = self.Contents d["Subtype"] = "/Text" return apply(self.AnnotationDict, (), d)
def Dict(self): d = {} d.update(self.otherkw) d["Rect"] = self.Rect d["Contents"] = self.Contents d["Subtype"] = "/Text" return apply(self.AnnotationDict, (), d)
5,571
def __init__(self, Rect, Contents, Destination, Border="[0 0 1]", **kw): self.Border = Border self.Rect = Rect self.Contents = Contents self.Destination = Destination self.otherkw = kw
def __init__(self, Rect, Contents, Destination, Border="[0 0 1]", **kw): self.Border = Border self.Rect = Rect self.Contents = Contents self.Destination = Destination self.otherkw = kw
5,572
def dummyDictString(self): # old, testing return """ << /Type /Annot /Subtype /Link /Rect [71 717 190 734] /Border [16 16 1] /Dest [23 0 R /Fit] >> """
def dummyDictString(self): # old, testing return """ << /Type /Annot /Subtype /Link /Rect [71 717 190 734] /Border [16 16 1] /Dest [23 0 R /Fit] >> """
5,573
def Dict(self): d = {} d.update(self.otherkw) d["Border"] = self.Border d["Rect"] = self.Rect d["Contents"] = self.Contents d["Subtype"] = "/Link" d["Dest"] = self.Destination return apply(self.AnnotationDict, (), d)
def Dict(self): d = {} d.update(self.otherkw) d["Border"] = self.Border d["Rect"] = self.Rect d["Contents"] = self.Contents d["Subtype"] = "/Link" d["Dest"] = self.Destination return apply(self.AnnotationDict, (), d)
5,574
def format(self, doc): S = PDFString(DATEFMT % (self.yyyy, self.mm, self.dd, self.hh, self.m, self.s)) return format(S, doc)
def format(self, doc): S = PDFString(DATEFMT % (self.yyyy, self.mm, self.dd, self.hh, self.m, self.s)) return format(S, doc)
5,575
def setPage(self, page): self.page = page #self.fmt.page = page # may not yet be defined!
def setPage(self, page): self.page = page #self.fmt.page = page # may not yet be defined!
5,576
def format(self, document): pageref = document.Reference(self.page) A = PDFArray( [ pageref, PDFName(self.typename), self.left, self.top, self.zoom ] ) return format(A, document)
def format(self, document): pageref = document.Reference(self.page) A = PDFArray( [ pageref, PDFName(self.typename), self.left, self.top, self.zoom ] ) return format(A, document)
5,577
def format(self, document): pageref = document.Reference(self.page) A = PDFArray( [ pageref, PDFName(self.typename) ] ) return format(A, document)
def format(self, document): pageref = document.Reference(self.page) A = PDFArray( [ pageref, PDFName(self.typename) ] ) return format(A, document)
5,578
def format(self, document): pageref = document.Reference(self.page) A = PDFArray( [ pageref, PDFName(self.typename), self.top ] ) return format(A, document)
def format(self, document): pageref = document.Reference(self.page) A = PDFArray( [ pageref, PDFName(self.typename), self.top ] ) return format(A, document)
5,579
def __init__(self, lowerx, lowery, upperx, uppery): #not done self.lowerx = lowerx; self.lowery=lowery; self.upperx=upperx; self.uppery=uppery
def __init__(self, lowerx, lowery, upperx, uppery): #not done self.lowerx = lowerx; self.lowery=lowery; self.upperx=upperx; self.uppery=uppery
5,580
def BBoxList(self): "get the declared bounding box for the form as a list" if self.BBox: return list(self.BBox.sequence) else: return [self.lowerx, self.lowery, self.upperx, self.uppery]
def BBoxList(self): "get the declared bounding box for the form as a list" if self.BBox: return list(self.BBox.sequence) else: return [self.lowerx, self.lowery, self.upperx, self.uppery]
5,581
def __init__(self, name, source=None, mask=None): self.name = name self.width = 24 self.height = 23 self.bitsPerComponent = 1 self.colorSpace = 'DeviceGray' self.filter = PDFName('ASCII85Decode') self.streamContent = """ 003B00 002700 002480 0E4940 114920 14B220 3CB650 75FE88 17FF8C 175F14 1C07E2 3803C4 703182 F8EDFC B2BBC2 BB6F84 31BFC2 18EA3C 0E3E00 07FC00 03F800 1E1800 1FF800> """ self.mask = mask if source is None: pass # use the canned one. elif type(source) == type(''): # it is a filename img = PIL_Image.open(open_for_read(source)) self.loadImageFromPIL(img) else: # it is already a PIL Image self.loadImageFromPIL(source)
def __init__(self, name, source=None, mask=None): self.name = name self.width = 24 self.height = 23 self.bitsPerComponent = 1 self.colorSpace = 'DeviceGray' self.filter = PDFName('ASCII85Decode') self.streamContent = """ 003B00 002700 002480 0E4940 114920 14B220 3CB650 75FE88 17FF8C 175F14 1C07E2 3803C4 703182 F8EDFC B2BBC2 BB6F84 31BFC2 18EA3C 0E3E00 07FC00 03F800 1E1800 1FF800> """ self.mask = mask if source is None: pass # use the canned one. elif type(source) == type(''): # it is a filename img = PIL_Image.open(open_for_read(source)) self.loadImageFromPIL(img) else: # it is already a PIL Image self.loadImageFromPIL(source)
5,582
def __init__(self, name, source=None, mask=None): self.name = name self.width = 24 self.height = 23 self.bitsPerComponent = 1 self.colorSpace = 'DeviceGray' self.filter = PDFName('ASCII85Decode') self.streamContent = """ 003B00 002700 002480 0E4940 114920 14B220 3CB650 75FE88 17FF8C 175F14 1C07E2 3803C4 703182 F8EDFC B2BBC2 BB6F84 31BFC2 18EA3C 0E3E00 07FC00 03F800 1E1800 1FF800> """ self.mask = mask if source is None: pass # use the canned one. elif type(source) == type(''): # it is a filename img = PIL_Image.open(open_for_read(source)) self.loadImageFromPIL(img) else: # it is already a PIL Image self.loadImageFromPIL(source)
def __init__(self, name, source=None, mask=None): self.name = name self.width = 24 self.height = 23 self.bitsPerComponent = 1 self.colorSpace = 'DeviceGray' self.filter = PDFName('ASCII85Decode') self.streamContent = """ 003B00 002700 002480 0E4940 114920 14B220 3CB650 75FE88 17FF8C 175F14 1C07E2 3803C4 703182 F8EDFC B2BBC2 BB6F84 31BFC2 18EA3C 0E3E00 07FC00 03F800 1E1800 1FF800> """ self.mask = mask if source is None: pass # use the canned one. elif type(source) == type(''): # it is a filename img = PIL_Image.open(open_for_read(source)) self.loadImageFromPIL(img) else: # it is already a PIL Image self.loadImageFromPIL(source)
5,583
def loadImageFromPIL(self, PILImage): "Extracts the stream, width and height" zlib = import_zlib() if not zlib: return #standardize it to RGB. We could be more optimal later. if PILImage.mode <> 'RGB': PILImage = PILImage.convert('RGB') imgwidth, imgheight = PILImage.size raw = PILImage.tostring() assert(len(raw) == imgwidth * imgheight, "Wrong amount of data for image") compressed = zlib.compress(raw) encoded = pdfutils._AsciiBase85Encode(compressed) self.colorSpace = 'DeviceRGB' self.bitsPerComponent = 8 self.streamContent = encoded self.width = imgwidth self.height = imgheight
def loadImageFromPIL(self, PILImage): "Extracts the stream, width and height" zlib = import_zlib() if not zlib: return #standardize it to RGB. We could be more optimal later. if PILImage.mode <> 'RGB': PILImage = PILImage.convert('RGB') imgwidth, imgheight = PILImage.size raw = PILImage.tostring() assert(len(raw) == imgwidth * imgheight, "Wrong amount of data for image") compressed = zlib.compress(raw) encoded = pdfutils._AsciiBase85Encode(compressed) self.colorSpace = 'DeviceRGB' self.bitsPerComponent = 8 self.streamContent = encoded self.width = imgwidth self.height = imgheight
5,584
def format(self, document): S = PDFStream() S.content = self.streamContent dict = S.dictionary dict["Type"] = PDFName("XObject") dict["Subtype"] = PDFName("Image") dict["Width"] = self.width dict["Height"] = self.height dict["BitsPerComponent"] = self.bitsPerComponent dict["ColorSpace"] = PDFName(self.colorSpace) dict["Filter"] = PDFArray( [PDFName('ASCII85Decode'), PDFName('FlateDecode')]) dict["Length"] = len(self.streamContent) if self.mask: dict["Mask"] = PDFArray(self.mask) return S.format(document)
def format(self, document): S = PDFStream() S.content = self.streamContent dict = S.dictionary dict["Type"] = PDFName("XObject") dict["Subtype"] = PDFName("Image") dict["Width"] = self.width dict["Height"] = self.height dict["BitsPerComponent"] = self.bitsPerComponent dict["ColorSpace"] = PDFName(self.colorSpace) dict["Filter"] = PDFArray( [PDFName('ASCII85Decode'), PDFName('FlateDecode')]) dict["Length"] = len(self.streamContent) if self.mask: dict["Mask"] = PDFArray(self.mask) return S.format(document)
5,585
def format(self, document): S = PDFStream() S.content = self.streamContent dict = S.dictionary dict["Type"] = PDFName("XObject") dict["Subtype"] = PDFName("Image") dict["Width"] = self.width dict["Height"] = self.height dict["BitsPerComponent"] = self.bitsPerComponent dict["ColorSpace"] = PDFName(self.colorSpace) dict["Filter"] = PDFArray( [PDFName('ASCII85Decode'), PDFName('FlateDecode')]) dict["Length"] = len(self.streamContent) if self.mask: dict["Mask"] = PDFArray(self.mask) return S.format(document)
def format(self, document): S = PDFStream() S.content = self.streamContent dict = S.dictionary dict["Type"] = PDFName("XObject") dict["Subtype"] = PDFName("Image") dict["Width"] = self.width dict["Height"] = self.height dict["BitsPerComponent"] = self.bitsPerComponent dict["ColorSpace"] = PDFName(self.colorSpace) dict["Filter"] = PDFArray( [PDFName('ASCII85Decode'), PDFName('FlateDecode')]) dict["Length"] = len(self.streamContent) if self.mask: if self.mask=='auto': if PILImage.info.has_key("transparency") : transparency = PILImage.info["transparency"] * 3 (tred, tgreen, tblue) = map(ord, PILImage.palette.data[transparency:transparency+3]) self.mask = (tred, tred, tgreen, tgreen, tblue, tblue) dict["Mask"] = PDFArray(self.mask) else: dict["Mask"] = PDFArray(self.mask) return S.format(document)
5,586
def format(self, document): S = PDFStream() S.content = self.streamContent dict = S.dictionary dict["Type"] = PDFName("XObject") dict["Subtype"] = PDFName("Image") dict["Width"] = self.width dict["Height"] = self.height dict["BitsPerComponent"] = self.bitsPerComponent dict["ColorSpace"] = PDFName(self.colorSpace) dict["Filter"] = PDFArray( [PDFName('ASCII85Decode'), PDFName('FlateDecode')]) dict["Length"] = len(self.streamContent) if self.mask: dict["Mask"] = PDFArray(self.mask) return S.format(document)
def format(self, document): S = PDFStream() S.content = self.streamContent dict = S.dictionary dict["Type"] = PDFName("XObject") dict["Subtype"] = PDFName("Image") dict["Width"] = self.width dict["Height"] = self.height dict["BitsPerComponent"] = self.bitsPerComponent dict["ColorSpace"] = PDFName(self.colorSpace) dict["Filter"] = PDFArray( [PDFName('ASCII85Decode'), PDFName('FlateDecode')]) dict["Length"] = len(self.streamContent) if self.mask: dict["Mask"] = PDFArray(self.mask) return S.format(document)
5,587
def format(self, document): S = PDFStream() S.content = self.streamContent dict = S.dictionary dict["Type"] = PDFName("XObject") dict["Subtype"] = PDFName("Image") dict["Width"] = self.width dict["Height"] = self.height dict["BitsPerComponent"] = self.bitsPerComponent dict["ColorSpace"] = PDFName(self.colorSpace) dict["Filter"] = PDFArray( [PDFName('ASCII85Decode'), PDFName('FlateDecode')]) dict["Length"] = len(self.streamContent) if self.mask: dict["Mask"] = PDFArray(self.mask) return S.format(document)
def format(self, document): S = PDFStream() S.content = self.streamContentdict = S.dictionary dict["Type"] = PDFName("XObject") dict["Subtype"] = PDFName("Image") dict["Width"] = self.width dict["Height"] = self.height dict["BitsPerComponent"] = self.bitsPerComponent dict["ColorSpace"] = PDFName(self.colorSpace) dict["Filter"] = PDFArray( [PDFName('ASCII85Decode'), PDFName('FlateDecode')]) dict["Length"] = len(self.streamContent) if self.mask: dict["Mask"] = PDFArray(self.mask)return S.format(document)
5,588
def beforeBuild(self): """Called by multiBuild before it starts; use this to clear old contents""" pass
def beforeBuild(self): """Called by multiBuild before it starts; use this to clear old contents""" pass
5,589
def checkPageSize(self,canv,doc): '''This gets called by the template framework If canv size != doc size then the canv size is set to the template size or if that's not available to the doc size. ''' #### NEVER EVER EVER COMPARE FLOATS FOR EQUALITY #RGB converting pagesizes to ints means we are accurate to one point #RGB I suggest we should be aiming a little better cp = None dp = None sp = None if canv._pagesize: cp = map(int, canv._pagesize) if self.pagesize: sp = map(int, self.pagesize) if doc.pagesize: dp = map(int, doc.pagesize) if cp!=sp: if sp: canv.setPageSize(self.pagesize) elif cp!=dp: canv.setPageSize(doc.pagesize)
def checkPageSize(self,canv,doc): '''This gets called by the template framework If canv size != doc size then the canv size is set to the template size or if that's not available to the doc size. ''' #### NEVER EVER EVER COMPARE FLOATS FOR EQUALITY #RGB converting pagesizes to ints means we are accurate to one point #RGB I suggest we should be aiming a little better cp = None dp = None sp = None if canv._pagesize: cp = map(int, canv._pagesize) if self.pagesize: sp = map(int, self.pagesize) if doc.pagesize: dp = map(int, doc.pagesize) if cp!=sp: if sp: canv.setPageSize(self.pagesize) elif cp!=dp: canv.setPageSize(doc.pagesize)
5,590
def afterDrawPage(self, canv, doc): """This is called after the last flowable for the page has been processed. You might use this if the page header or footer needed knowledge of what flowables were drawn on this page.""" pass
def afterDrawPage(self, canv, doc): """This is called after the last flowable for the page has been processed. You might use this if the page header or footer needed knowledge of what flowables were drawn on this page.""" pass
5,591
def afterDrawPage(self, canv, doc): """This is called after the last flowable for the page has been processed. You might use this if the page header or footer needed knowledge of what flowables were drawn on this page.""" pass
def afterDrawPage(self, canv, doc): """This is called after the last flowable for the page has been processed. You might use this if the page header or footer needed knowledge of what flowables were drawn on this page.""" pass
5,592
def afterDrawPage(self, canv, doc): """This is called after the last flowable for the page has been processed. You might use this if the page header or footer needed knowledge of what flowables were drawn on this page.""" pass
def afterDrawPage(self, canv, doc): """This is called after the last flowable for the page has been processed. You might use this if the page header or footer needed knowledge of what flowables were drawn on this page.""" pass
5,593
def afterDrawPage(self, canv, doc): """This is called after the last flowable for the page has been processed. You might use this if the page header or footer needed knowledge of what flowables were drawn on this page.""" pass
def afterDrawPage(self, canv, doc): """This is called after the last flowable for the page has been processed. You might use this if the page header or footer needed knowledge of what flowables were drawn on this page.""" pass
5,594
def afterDrawPage(self, canv, doc): """This is called after the last flowable for the page has been processed. You might use this if the page header or footer needed knowledge of what flowables were drawn on this page.""" pass
def afterDrawPage(self, canv, doc): """This is called after the last flowable for the page has been processed. You might use this if the page header or footer needed knowledge of what flowables were drawn on this page.""" pass
5,595
def __init__(self, filename, **kw): """create a document template bound to a filename (see class documentation for keyword arguments)""" self.filename = filename
def __init__(self, filename, **kw): """create a document template bound to a filename (see class documentation for keyword arguments)""" self.filename = filename
5,596
def addPageTemplates(self,pageTemplates): 'add one or a sequence of pageTemplates' if type(pageTemplates) not in (ListType,TupleType): pageTemplates = [pageTemplates] #this test below fails due to inconsistent imports! #assert filter(lambda x: not isinstance(x,PageTemplate), pageTemplates)==[], "pageTemplates argument error" for t in pageTemplates: self.pageTemplates.append(t)
def addPageTemplates(self,pageTemplates): 'add one or a sequence of pageTemplates' if type(pageTemplates) not in (ListType,TupleType): pageTemplates = [pageTemplates] #this test below fails due to inconsistent imports! #assert filter(lambda x: not isinstance(x,PageTemplate), pageTemplates)==[], "pageTemplates argument error" for t in pageTemplates: self.pageTemplates.append(t)
5,597
def handle_breakBefore(self, flowables): '''preprocessing step to allow pageBreakBefore and frameBreakBefore attributes''' first = flowables[0] # if we insert a page break before, we'll process that, see it again, # and go in an infinite loop. So we need to set a flag on the object # saying 'skip me'. This should be unset on the next pass if hasattr(first, '_skipMeNextTime'): delattr(first, '_skipMeNextTime') return # this could all be made much quicker by putting the attributes # in to the flowables with a defult value of 0 if hasattr(first,'pageBreakBefore') and first.pageBreakBefore == 1: first._skipMeNextTime = 1 first.insert(0, PageBreak()) return if hasattr(first,'style') and hasattr(first.style, 'pageBreakBefore') and first.style.pageBreakBefore == 1: first._skipMeNextTime = 1 flowables.insert(0, PageBreak()) return if hasattr(first,'frameBreakBefore') and first.frameBreakBefore == 1: first._skipMeNextTime = 1 flowables.insert(0, FrameBreak()) return if hasattr(first,'style') and hasattr(first.style, 'frameBreakBefore') and first.style.frameBreakBefore == 1: first._skipMeNextTime = 1 flowables.insert(0, FrameBreak()) return
def handle_breakBefore(self, flowables): '''preprocessing step to allow pageBreakBefore and frameBreakBefore attributes''' first = flowables[0] # if we insert a page break before, we'll process that, see it again, # and go in an infinite loop. So we need to set a flag on the object # saying 'skip me'. This should be unset on the next pass if hasattr(first, '_skipMeNextTime'): delattr(first, '_skipMeNextTime') return # this could all be made much quicker by putting the attributes # in to the flowables with a defult value of 0 if hasattr(first,'pageBreakBefore') and first.pageBreakBefore == 1: first._skipMeNextTime = 1 first.insert(0, PageBreak()) return if hasattr(first,'style') and hasattr(first.style, 'pageBreakBefore') and first.style.pageBreakBefore == 1: first._skipMeNextTime = 1 flowables.insert(0, PageBreak()) return if hasattr(first,'frameBreakBefore') and first.frameBreakBefore == 1: first._skipMeNextTime = 1 flowables.insert(0, FrameBreak()) return if hasattr(first,'style') and hasattr(first.style, 'frameBreakBefore') and first.style.frameBreakBefore == 1: first._skipMeNextTime = 1 flowables.insert(0, FrameBreak()) return
5,598
def handle_keepWithNext(self, flowables): "implements keepWithNext" #disabled for now - will not work return this = flowables[0] if isinstance(this, KeepTogether): if hasattr(this, '_skipMeNextTime'): delattr(this, '_skipMeNextTime') return keepWithNext = ((hasattr(this, 'keepWithNext') and this.keepWithNext == 1) or (hasattr(this, 'style') and hasattr(this.style, 'keepWithNext') and this.style.keepWithNext == 1) ) if keepWithNext: print 'found a keepWithNext, %d items remaining' % len(flowables) collected = []
def handle_keepWithNext(self, flowables): "implements keepWithNext" #disabled for now - will not work return this = flowables[0] if isinstance(this, KeepTogether): if hasattr(this, '_skipMeNextTime'): delattr(this, '_skipMeNextTime') return keepWithNext = ((hasattr(this, 'keepWithNext') and this.keepWithNext == 1) or (hasattr(this, 'style') and hasattr(this.style, 'keepWithNext') and this.style.keepWithNext == 1) ) if keepWithNext: print 'found a keepWithNext, %d items remaining' % len(flowables) collected = []
5,599