rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
cv = self._cellvalues
cv = getattr(self,'_cellvalues',None)
def identity(self, maxLen=30): '''Identify our selves as well as possible''' vx = None nr = getattr(self,'_nrows','unknown') nc = getattr(self,'_ncols','unknown') cv = self._cellvalues if cv and 'unknown' not in (nr,nc): b = 0 for i in xrange(nr): for j in xrange(nc): v = cv[i][j] t = type(v) if t in _SeqTypes or isins...
del sys.path[0]
os.chdir(cwd) sys.path = opath
def getModuleObjects(folder, rootName, typ): "Get a list of all function objects defined *somewhere* in a package." folders = [folder] + subFoldersOfFolder(folder) objects = [] for f in folders: sys.path.insert(0, f) os.chdir(f) pattern = os.path.join('*.py') prefix = f[string.find(f, rootName):] prefix = string.repl...
if Klass in _ItemWrapper.keys():
if _ItemWrapper.has_key(Klass):
def __getitem__(self, index): try: return self._children[index] except KeyError: Klass = self._prototype if Klass in _ItemWrapper.keys(): WKlass = _ItemWrapper[Klass] else: class WKlass(Klass): def __getattr__(self,name): try: return Klass.__getattr__(self,name) except: return getattr(self._parent,name) _ItemWrapper[Kl...
return Klass.__getattr__(self,name)
return self.__class__.__bases__[0].__getattr__(self,name)
def __getattr__(self,name): try: return Klass.__getattr__(self,name) except: return getattr(self._parent,name)
tx.moveCursor(offset + 0.5 * extraspace, 0)
tx.moveCursor(0.5 * extraspace, 0)
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
tx.moveCursor(-offset + 0.5 * extraspace, 0)
tx.moveCursor(0.5 * extraspace, 0)
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
tx.moveCursor(offset + extraspace, 0)
tx.moveCursor(extraspace, 0)
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
tx.moveCursor(-offset + extraspace, 0)
tx.moveCursor(extraspace, 0)
def drawPara(self,debug=0): """Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite."""
data = open('odyssey.txt','r').readlines()
for fn in ('Odyssey.full.txt','Odyssey.txt'): if os.path.isfile(fn): break data = open(fn,'r').readlines()
def run(): started = time.time() canv = canvas.Canvas('odyssey.pdf') canv.setPageCompression(0) drawPageFrame(canv) #do some title page stuff canv.setFont("Times-Bold", 36) canv.drawCentredString(0.5 * A4[0], 7 * inch, "Homer's Odyssey") canv.setFont("Times-Bold", 18) canv.drawCentredString(0.5 * A4[0], 5 * inch, "Tr...
pages = canv.getPageNumber()
pages = canv.getPageNumber()-1
def run(): started = time.time() canv = canvas.Canvas('odyssey.pdf') canv.setPageCompression(0) drawPageFrame(canv) #do some title page stuff canv.setFont("Times-Bold", 36) canv.drawCentredString(0.5 * A4[0], 7 * inch, "Homer's Odyssey") canv.setFont("Times-Bold", 18) canv.drawCentredString(0.5 * A4[0], 5 * inch, "Tr...
self.canv.setPageRotation(getattr(self.pageTemplate,'rotation',0)
self.canv.setPageRotation(getattr(self.pageTemplate,'rotation',0))
def handle_pageEnd(self): ''' show the current page check the next page template hang a page begin ''' #detect infinite loops... if self._curPageFlowableCount == 0: self._emptyPages = self._emptyPages + 1 else: self._emptyPages = 0 if self._emptyPages >= self._emptyPagesAllowed: if 1: ident = "More than %d pages genera...
extra = basicWidth - length wordspace = extra*1.0/nwords
def draw(self): from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY style = self.style lines = self.lines rightIndent = style.rightIndent leftIndent = style.leftIndent leading = style.leading font = style.fontName size = style.fontSize alignment = style.alignment firstindent = style.firstLineIndent...
textobject.setWordSpace((extra*1.0/(nwords - 1)))
textobject.setWordSpace((basicWidth-length)/(nwords-1.0))
def draw(self): from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY style = self.style lines = self.lines rightIndent = style.rightIndent leftIndent = style.leftIndent leading = style.leading font = style.fontName size = style.fontSize alignment = style.alignment firstindent = style.firstLineIndent...
self.fontdict = MakeFontDictionary(fontstartpos, len(self.fonts))
fontdicttext = MakeFontDictionary(fontstartpos, len(self.fonts)) fontdictob = PDFLiteral(fontdicttext) self.add("FontDictionary", fontdictob) self.fontdict = self.objectReference("FontDictionary")
def __init__(self): self.objects = [] self.objectPositions = {} self.fonts = MakeType1Fonts()
self.objectPositions[key] = len(self.objects)
self.objectPositions[key] = len(self.objects)+1
def add(self, key, obj): self.objectPositions[key] = len(self.objects) # its position self.objects.append(obj) #obj.doc = self return len(self.objects) - 1 # give its position
return len(self.objects) - 1
return self.getPosition(key)
def add(self, key, obj): self.objectPositions[key] = len(self.objects) # its position self.objects.append(obj) #obj.doc = self return len(self.objects) - 1 # give its position
page.ParentPos = 3
page.ParentPos = self.getPosition("PagesTreeRoot")
def addPage(self, page): """adds page and stream at end. Maintains pages list""" #page.buildstream() pos = len(self.objects) # work out where added page.ParentPos = 3 #pages collection page.info = { 'parentpos':3, 'fontdict':self.fontdict, 'contentspos':pos + 2, } self.PageCol.PageList.append(pos+1) self.add('Page...
S = split(text,' ')
S = split(text)
def _getFragWords(frags): ''' given a Parafrag list return a list of fragwords [[size, (f00,w00), ..., (f0n,w0n)],....,[size, (fm0,wm0), ..., (f0n,wmn)]] each pair f,w represents a style and some string each sublist represents a word ''' R = [] W = [] n = 0 for f in frags: text = f.text #del f.text # we can't do this u...
if W!=[] and text[0] in [' ','\t']:
if W!=[] and text[0] in whitespace:
def _getFragWords(frags): ''' given a Parafrag list return a list of fragwords [[size, (f00,w00), ..., (f0n,w0n)],....,[size, (fm0,wm0), ..., (f0n,wmn)]] each pair f,w represents a style and some string each sublist represents a word ''' R = [] W = [] n = 0 for f in frags: text = f.text #del f.text # we can't do this u...
if text[-1] in [' ','\t']:
if text[-1] in whitespace:
def _getFragWords(frags): ''' given a Parafrag list return a list of fragwords [[size, (f00,w00), ..., (f0n,w0n)],....,[size, (fm0,wm0), ..., (f0n,wmn)]] each pair f,w represents a style and some string each sublist represents a word ''' R = [] W = [] n = 0 for f in frags: text = f.text #del f.text # we can't do this u...
if W!=[]: W.insert(0,n) R.append(W) W = [] n = 0 R.append([0,(f,'')])
W.append((f,''))
def _getFragWords(frags): ''' given a Parafrag list return a list of fragwords [[size, (f00,w00), ..., (f0n,w0n)],....,[size, (fm0,wm0), ..., (f0n,wmn)]] each pair f,w represents a style and some string each sublist represents a word ''' R = [] W = [] n = 0 for f in frags: text = f.text #del f.text # we can't do this u...
if nText!='' and nText[0]!=' ':
if (nText!='' and nText[0]!=' ') or hasattr(f,'cbDefn'):
def breakLines(self, width): """ Returns a broken line structure. There are two cases A) For the simple case of a single formatting input fragment the output is A fragment specifier with kind = 0 fontName, fontSize, leading, textColor lines= A list of lines Each line has two items. 1) unused width in points 2) word li...
raise LayoutError("More than %d pages generated without content - halting layout. Likely that a flowable is too large for any frame." % self._emptyPagesAllowed)
ident = "More than %d pages generated without content - halting layout. Likely that a flowable is too large for any frame." % self._emptyPagesAllowed raise LayoutError(ident)
def handle_pageEnd(self): ''' show the current page check the next page template hang a page begin ''' #detect infinite loops... if self._curPageFlowableCount == 0: self._emptyPages = self._emptyPages + 1 else: self._emptyPages = 0 if self._emptyPages >= self._emptyPagesAllowed: if 1: raise LayoutError("More than %d pa...
raise LayoutError("Splitting error(n==%d) on page %d in\n%s" % (n,self.page,f.identity(30)))
ident = "Splitting error(n==%d) on page %d in\n%s" % (n,self.page,f.identity(30)) raise LayoutError(ident)
def handle_flowable(self,flowables): '''try to handle one flowable from the front of list flowables.'''
raise LayoutError("Flowable %s too large on page %d" % (f.identity(30), self.page))
ident = "Flowable %s too large on page %d" % (f.identity(30), self.page) raise LayoutError(ident)
def handle_flowable(self,flowables): '''try to handle one flowable from the front of list flowables.'''
self.restartAccumulators() self.annotationCount = 0
self._restartAccumulators() self._annotationCount = 0
def __init__(self,filename,pagesize=(595.27,841.89), bottomup = 1, pageCompression=0 ): """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._doc = pdfdoc.PDFDocument() self._pagesize = pagesize #self._currentPageHasI...
self.setXObjects(page) self.setAnnotations(page)
self._setXObjects(page) self._setAnnotations(page)
def showPage(self): """This is where the fun happens""" page = pdfdoc.PDFPage() page.pagewidth = self._pagesize[0] page.pageheight = self._pagesize[1] page.hasImages = self._currentPageHasImages page.pageTransitionString = self._pageTransitionString page.setCompression(self._pageCompression) #print stream page.setStrea...
self.restartAccumulators() def setAnnotations(self,page):
self._restartAccumulators() def _setAnnotations(self,page):
def showPage(self): """This is where the fun happens""" page = pdfdoc.PDFPage() page.pagewidth = self._pagesize[0] page.pageheight = self._pagesize[1] page.hasImages = self._currentPageHasImages page.pageTransitionString = self._pageTransitionString page.setCompression(self._pageCompression) #print stream page.setStrea...
def setXObjects(self, thing):
def _setXObjects(self, thing):
def setXObjects(self, thing): """for pages and forms, define the XObject dictionary for resources, if needed""" forms = self._formsinuse if forms: xobjectsdict = self._doc.xobjDict(forms) thing.XObjects = xobjectsdict else: thing.XObjects = None
def bookmarkReference(self, name):
def _bookmarkReference(self, name):
def bookmarkReference(self, name): """get a reference to a (possibly undefined, possibly unbound) bookmark""" d = self._destinations try: return d[name] except: result = d[name] = pdfdoc.Destination(name) # newly defined, unbound return result
dest = self.bookmarkReference(name)
dest = self._bookmarkReference(name)
def bookmarkPage(self, name): """bind a bookmark (destination) to the current page""" # XXXX there are a lot of other ways a bookmark destination can be bound: should be implemented. # XXXX the other ways require tracking of the graphics state.... dest = self.bookmarkReference(name) pageref = self._doc.thisPageRef() de...
def bookmarkHorizontalInPageAbsolute(self, name, yhorizontal):
def bookmarkHorizontalAbsolute(self, name, yhorizontal):
def bookmarkHorizontalInPageAbsolute(self, name, yhorizontal): """bind a bookmark (destination to the current page at a horizontal position""" dest = self.bookmarkReference(name) pageref = self._doc.thisPageRef() dest.fith(yhorizontal) dest.setPageRef(pageref) return dest
dest = self.bookmarkReference(name)
dest = self._bookmarkReference(name)
def bookmarkHorizontalInPageAbsolute(self, name, yhorizontal): """bind a bookmark (destination to the current page at a horizontal position""" dest = self.bookmarkReference(name) pageref = self._doc.thisPageRef() dest.fith(yhorizontal) dest.setPageRef(pageref) return dest
def restartAccumulators(self):
def _restartAccumulators(self):
def restartAccumulators(self): self._code = [] # ready for more... self._currentPageHasImages = 1 # for safety... self._formsinuse = [] self._annotationrefs = []
self.setXObjects(form) self.setAnnotations(form)
self._setXObjects(form) self._setAnnotations(form)
def makeForm(self, name, lowerx=0, lowery=0, upperx=None, uppery=None): """Like showpage, but make a form using accumulated operations instead""" (w,h) = self._pagesize if upperx is None: upperx=w if uppery is None: uppery=h form = pdfdoc.PDFFormXObject(lowerx=lowerx, lowery=lowery, upperx=upperx, uppery=uppery) form.c...
self.restartAccumulators()
self._restartAccumulators()
def makeForm(self, name, lowerx=0, lowery=0, upperx=None, uppery=None): """Like showpage, but make a form using accumulated operations instead""" (w,h) = self._pagesize if upperx is None: upperx=w if uppery is None: uppery=h form = pdfdoc.PDFFormXObject(lowerx=lowerx, lowery=lowery, upperx=upperx, uppery=uppery) form.c...
self.addAnnotation(annotation, name, addtopage)
self._addAnnotation(annotation, name, addtopage)
def textAnnotation(self, contents, Rect=None, addtopage=1, name=None, **kw): if not Rect: (w,h) = self._pagesize# default to whole page (?) Rect = (0,0,w,h) annotation = apply(pdfdoc.TextAnnotation, (Rect, contents), kw) self.addAnnotation(annotation, name, addtopage)
def linkAnnotationAbsolute(self, contents, destinationname, Rect=None, addtopage=1, name=None, **kw):
def linkAbsolute(self, contents, destinationname, Rect=None, addtopage=1, name=None, **kw):
def linkAnnotationAbsolute(self, contents, destinationname, Rect=None, addtopage=1, name=None, **kw): """link annotation positioned wrt the default user space""" destination = self.bookmarkReference(destinationname) # permitted to be undefined... must bind later... (w,h) = self._pagesize if not Rect: Rect = (0,0,w,h) k...
destination = self.bookmarkReference(destinationname)
destination = self._bookmarkReference(destinationname)
def linkAnnotationAbsolute(self, contents, destinationname, Rect=None, addtopage=1, name=None, **kw): """link annotation positioned wrt the default user space""" destination = self.bookmarkReference(destinationname) # permitted to be undefined... must bind later... (w,h) = self._pagesize if not Rect: Rect = (0,0,w,h) k...
self.addAnnotation(annotation, name, addtopage)
self._addAnnotation(annotation, name, addtopage)
def linkAnnotationAbsolute(self, contents, destinationname, Rect=None, addtopage=1, name=None, **kw): """link annotation positioned wrt the default user space""" destination = self.bookmarkReference(destinationname) # permitted to be undefined... must bind later... (w,h) = self._pagesize if not Rect: Rect = (0,0,w,h) k...
def addAnnotation(self, annotation, name=None, addtopage=1): count = self.annotationCount = self.annotationCount+1
def _addAnnotation(self, annotation, name=None, addtopage=1): count = self._annotationCount = self._annotationCount+1
def addAnnotation(self, annotation, name=None, addtopage=1): count = self.annotationCount = self.annotationCount+1 if not name: name="NUMBER"+repr(count) self._doc.addAnnotation(name, annotation) if addtopage: self.annotatePage(name)
self.annotatePage(name)
self._annotatePage(name)
def addAnnotation(self, annotation, name=None, addtopage=1): count = self.annotationCount = self.annotationCount+1 if not name: name="NUMBER"+repr(count) self._doc.addAnnotation(name, annotation) if addtopage: self.annotatePage(name)
def annotatePage(self, name):
def _annotatePage(self, name):
def annotatePage(self, name): ref = self._doc.refAnnotation(name) self._annotationrefs.append(ref)
failTest('</a>',"Error Error: End tag </a> outside of any element\n in unnamed entity at line 1 char 4 of [unknown]\nEnd tag </a> outside of any element\nParse Failed!\n")
failTest('</a>',"error Error: End tag </a> outside of any element\n in unnamed entity at line 1 char 4 of [unknown]\nEnd tag </a> outside of any element\nParse Failed!\n")
def _runTests(pyRXP): global _pyRXP _pyRXP = pyRXP print >>_logf, '############# Testing',pyRXP.__name__ try: for k,v in pyRXP.parser_flags.items(): eval('pyRXP.Parser(%s=%d)' % (k,v)) print >>_logf,'Parser keywords OK' _dot('.') except: traceback.print_exc() print >>_logf,'Parser keywords BAD' _dot('E') try: for k,v i...
failTest('<?xml version="1.0" encoding="LATIN-1"?></a>',"Error Unknown declared encoding LATIN-1\nInternal error, ParserPush failed!\n")
failTest('<?xml version="1.0" encoding="LATIN-1"?></a>',"error Unknown declared encoding LATIN-1\nInternal error, ParserPush failed!\n")
def _runTests(pyRXP): global _pyRXP _pyRXP = pyRXP print >>_logf, '############# Testing',pyRXP.__name__ try: for k,v in pyRXP.parser_flags.items(): eval('pyRXP.Parser(%s=%d)' % (k,v)) print >>_logf,'Parser keywords OK' _dot('.') except: traceback.print_exc() print >>_logf,'Parser keywords BAD' _dot('E') try: for k,v i...
failTest(bigDepth(257),"""Error Internal error, stack limit reached!\n""", inOnly=1)
failTest(bigDepth(257),"""error Internal error, stack limit reached!\n""", inOnly=1)
def _runTests(pyRXP): global _pyRXP _pyRXP = pyRXP print >>_logf, '############# Testing',pyRXP.__name__ try: for k,v in pyRXP.parser_flags.items(): eval('pyRXP.Parser(%s=%d)' % (k,v)) print >>_logf,'Parser keywords OK' _dot('.') except: traceback.print_exc() print >>_logf,'Parser keywords BAD' _dot('E') try: for k,v i...
else:
elif glyph:
def getDifferences(self, otherEnc): """Return a compact list of the code points differing between two encodings
rawdata = open('../../rlextra/rml2pdf/doc/rml_user_guide.rml').read()
rawdata = open('../../rlextra/rml2pdf/doc/rml_user_guide.prep').read()
def testStringWidthAlgorithms(): rawdata = open('../../rlextra/rml2pdf/doc/rml_user_guide.rml').read() print 'rawdata length %d' % len(rawdata) print 'test one huge string...' test3widths([rawdata]) print words = string.split(rawdata) print 'test %d shorter strings (average length %0.2f chars)...' % (len(words), 1.0*le...
_attrMap = AttrMap( x = AttrMapValue(isNumber, desc='X position of the chart.'), y = AttrMapValue(isNumber, desc='Y position of the chart.'), width = AttrMapValue(isNumber), height = AttrMapValue(isNumber), data = AttrMapValue(isListOfNumbers), labels = AttrMapValue(isListOfStringsOrNone), startAngle = AttrMapValue(isN...
_attrMap = AttrMap( x = AttrMapValue(isNumber, desc='X position of the chart.'), y = AttrMapValue(isNumber, desc='Y position of the chart.'), width = AttrMapValue(isNumber), height = AttrMapValue(isNumber), data = AttrMapValue(isListOfNumbers), labels = AttrMapValue(isListOfStringsOrNone), startAngle = AttrMapValue(isN...
def __init__(self): self.strokeWidth = 0 self.fillColor = None self.strokeColor = STATE_DEFAULTS["strokeColor"] self.strokeDashArray = STATE_DEFAULTS["strokeDashArray"] self.popout = 0 self.fontName = STATE_DEFAULTS["fontName"] self.fontSize = STATE_DEFAULTS["fontSize"] self.fontColor = STATE_DEFAULTS["fillColor"] self...
_ElementWrapper={}
_ItemWrapper={}
def provideNode(self): return self.draw()
if Klass in _ElementWrapper.keys(): WKlass = _ElementWrapper[Klass]
if Klass in _ItemWrapper.keys(): WKlass = _ItemWrapper[Klass]
def __getitem__(self, index): try: return self._children[index] except KeyError: Klass = self._prototype if Klass in _ElementWrapper.keys(): WKlass = _ElementWrapper[Klass] else: class WKlass(Klass): def __getattr__(self,name): try: return Klass.__getattr__(self,name) except: return getattr(self._parent,name)
import md5, time
import md5
def __init__(self, encoding=rl_config.defaultEncoding, dummyoutline=0, compression=rl_config.pageCompression, invariant=rl_config.invariant): #self.defaultStreamFilters = [PDFBase85Encode, PDFZCompress] # for testing! #self.defaultStreamFilters = [PDFZCompress] # for testing! assert encoding in ['MacRomanEncoding', 'Wi...
sig.update(repr(time.time()))
if not self.invariant: import time sig.update(repr(time.time()))
def __init__(self, encoding=rl_config.defaultEncoding, dummyoutline=0, compression=rl_config.pageCompression, invariant=rl_config.invariant): #self.defaultStreamFilters = [PDFBase85Encode, PDFZCompress] # for testing! #self.defaultStreamFilters = [PDFZCompress] # for testing! assert encoding in ['MacRomanEncoding', 'Wi...
self.invariant = 1
self.invariant = rl_config.invariant
def __init__(self): self.invariant = 1 self.title = "untitled" self.author = "anonymous" self.subject = "unspecified" #now = time.localtime(time.time()) #self.datestr = '%04d%02d%02d%02d%02d%02d' % tuple(now[0:6])
if self.invariant: D["CreationDate"] = PDFString('19001231000000') else: D["CreationDate"] = PDFDate()
D["CreationDate"] = PDFDate(invariant=self.invariant)
def format(self, document): D = {} D["Title"] = PDFString(self.title) D["Author"] = PDFString(self.author) if self.invariant: D["CreationDate"] = PDFString('19001231000000') else: D["CreationDate"] = PDFDate() D["Producer"] = PDFString("ReportLab http://www.reportlab.com") D["Subject"] = PDFString(self.subject) PD = PD...
DATEFMT = '%04d%02d%02d%02d%02d%02d' import time (nowyyyy, nowmm, nowdd, nowhh, nowm, nows) = tuple(time.localtime(time.time())[:6])
_NOW=None
def format(self, document): A = PDFArray([self.llx, self.lly, self.ulx, self.ury]) return format(A, document)
def __init__(self, yyyy=nowyyyy, mm=nowmm, dd=nowdd, hh=nowhh, m=nowm, s=nows):
def __init__(self, yyyy=None, mm=None, dd=None, hh=None, m=None, s=None, invariant=rl_config.invariant): if None in (yyyy, mm, dd, hh, m, s): if invariant: now = 1900,01,01,00,00,00,0 else: global _NOW if _NOW is None: import time _NOW = tuple(time.localtime(time.time())[:6]) now = _NOW if yyyy is None: yyyy=now[0] if ...
def __init__(self, yyyy=nowyyyy, mm=nowmm, dd=nowdd, hh=nowhh, m=nowm, s=nows): self.yyyy=yyyy; self.mm=mm; self.dd=dd; self.hh=hh; self.m=m; self.s=s
S = PDFString(DATEFMT % (self.yyyy, self.mm, self.dd, self.hh, self.m, self.s))
S = PDFString('%04d%02d%02d%02d%02d%02d' % (self.yyyy, self.mm, self.dd, self.hh, self.m, self.s))
def format(self, doc): S = PDFString(DATEFMT % (self.yyyy, self.mm, self.dd, self.hh, self.m, self.s)) return format(S, doc)
self.fileName = fileName
self.fileName = self._image.fileName
def __init__(self, fileName): if isinstance(fileName,ImageReader): self.__dict__ = fileName.__dict__ #borgize return if not haveImages: raise RuntimeError('Imaging Library not available, unable to import bitmaps') #start wih lots of null private fields, to be populated by #the relevant engine. self.fileName = fileNam...
def _calc(self): if hasattr(self,'_width'): return
def _calc_width(self): W = self._argW canv = getattr(self,'canv',None) saved = None if None in W: W = W[:] self._colWidths = W while None in W: j = W.index(None) f = lambda x,j=j: operator.getitem(x,j) V = map(f,self._cellvalues) S = map(f,self._cellStyles) w = 0 i = 0 for v, s in map(None, V, S): i = i + 1 t = type...
def _calc(self): if hasattr(self,'_width'): return
if None in W: W = W[:] self._colWidths = W while None in W: j = W.index(None) f = lambda x,j=j: operator.getitem(x,j) V = map(f,self._cellvalues) S = map(f,self._cellStyles) w = 0 i = 0 for v, s in map(None, V, S): i = i + 1 t = type(v) if t in _SeqTypes or isinstance(v,Flowable): raise ValueError, "Flowable %s in cell...
def _calc(self): if hasattr(self,'_width'): return
width = 0 self._colpositions = [0] for w in W: width = width + w self._colpositions.append(width) self._width = width
def _calc(self): if hasattr(self,'_width'): return self._calc_height() if hasattr(self,'_width_calculated_once'): return self._width_calculated_once = 1 self._calc_width()
def _calc(self): if hasattr(self,'_width'): return
R0 = Table( data[:n], self._argW, self._argH[:n],
R0 = Table( data[:n], self._colWidths, self._argH[:n],
def _splitRows(self,availHeight): h = 0 n = 0 lim = len(self._rowHeights) while n<lim: hn = h + self._rowHeights[n] if hn>availHeight: break h = hn n = n + 1
R1 = Table(data[:repeatRows]+data[n:], self._argW, self._argH[:repeatRows]+self._argH[n:],
R1 = Table(data[:repeatRows]+data[n:],self._colWidths, self._argH[:repeatRows]+self._argH[n:],
def _splitRows(self,availHeight): h = 0 n = 0 lim = len(self._rowHeights) while n<lim: hn = h + self._rowHeights[n] if hn>availHeight: break h = hn n = n + 1
R1 = Table(data[n:], self._argW, self._argH[n:],
R1 = Table(data[n:], self._colWidths, self._argH[n:],
def _splitRows(self,availHeight): h = 0 n = 0 lim = len(self._rowHeights) while n<lim: hn = h + self._rowHeights[n] if hn>availHeight: break h = hn n = n + 1
if type(filename) is type(''):
if type(fileName) is type(''):
def __init__(self, fileName): if not haveImages: warnOnce('Imaging Library not available, unable to import bitmaps') return #start wih lots of null private fields, to be populated by #the relevant engine. self.fileName = fileName self._image = None self._width = None self._height = None self._transparent = None self._d...
elif Flag._attrMap['kind'].validate(name):
elif name[-5:]=='_Flag' and Flag._attrMap['kind'].validate(name[:-5]):
def makeMarker(name): if Marker._attrMap['kind'].validate(name): m = Marker() m.kind = name elif Flag._attrMap['kind'].validate(name): m = Flag() m.kind = name m.size = 10 else: raise ValueError, "Invalid marker name %s" % name return m
m.kind = name
m.kind = name[:-5]
def makeMarker(name): if Marker._attrMap['kind'].validate(name): m = Marker() m.kind = name elif Flag._attrMap['kind'].validate(name): m = Flag() m.kind = name m.size = 10 else: raise ValueError, "Invalid marker name %s" % name return m
if type(abf) not in (TupleType,ListType): abf = abf, abf
def _setRange(self, dataSeries): """Set minimum and maximum axis values.
canvas.drawString(100,700,'A Custom Shape')
canvas.drawString(600, 100, 'A Custom Shape')
def drawOn(self, canvas): canvas.saveState() canvas.setFont('Helvetica-Bold',24) canvas.drawString(100,700,'A Custom Shape')
def __init__(self, maxWidth, maxHeight, content=[], mergeSpace=None, mode=0, id=None):
def __init__(self, maxWidth, maxHeight, content=[], mergeSpace=1, mode=0, name=None):
def __init__(self, maxWidth, maxHeight, content=[], mergeSpace=None, mode=0, id=None): '''mode describes the action to take when overflowing 0 raise an error in the normal way 1 ignore ie just draw it and report maxWidth, maxHeight 2 shrinkToFit ''' self.id = id self.maxWidth = maxWidth self.maxHeight = maxHeight...
self.id = id
self.name = name or str(id(self))
def __init__(self, maxWidth, maxHeight, content=[], mergeSpace=None, mode=0, id=None): '''mode describes the action to take when overflowing 0 raise an error in the normal way 1 ignore ie just draw it and report maxWidth, maxHeight 2 shrinkToFit ''' self.id = id self.maxWidth = maxWidth self.maxHeight = maxHeight...
return "<%s at %d%s> size=%sx%s" % (self.__class__.__name__, id(self), self.id and ' id="%s"'%self.id, fp_str(self.maxWidth),fp_str(self.maxHeight))
return "<%s at %d%s> size=%sx%s" % (self.__class__.__name__, id(self), self.name and ' name="%s"'%self.name, fp_str(self.maxWidth),fp_str(self.maxHeight))
def identity(self, maxLen=None): return "<%s at %d%s> size=%sx%s" % (self.__class__.__name__, id(self), self.id and ' id="%s"'%self.id, fp_str(self.maxWidth),fp_str(self.maxHeight))
maxWidth = float(self.maxWidth)
maxWidth = float(self.maxWidth or availWidth)
def wrap(self,availWidth,availHeight): mode = self.mode maxWidth = float(self.maxWidth) maxHeight = float(self.maxHeight) W, H = _listWrapOn(self._content,availWidth,self.canv) if mode==0 or (W<=maxWidth and H<=maxHeight): self.width = W #we take what we get self.height = H elif mode==1: #we lie self.width = min(max...
w.text = t[:i] cline.append(w)
cline.append(w.clone(text=t[:i]))
def _getFragLines(frags): lines = [] cline = [] W = frags[:] while W != []: w = W[0] t = w.text del W[0] i = string.find(t,'\n') if i>=0: tleft = t[i+1:] w.text = t[:i] cline.append(w) lines.append(cline) cline = [] if tleft!='': W.insert(0,w.clone(text=tleft)) else: cline.append(w) if cline!=[]: lines.append(cline) re...
print 'dumpXPreforemattedLines(%s)' % str(P)
print '\n
def dumpXPreformattedLines(P): print 'dumpXPreforemattedLines(%s)' % str(P) lines = P.bfrags.lines n =len(lines) for l in range(n): line = lines[l] words = line.words nwords = len(words) print 'line%d: %d(%d)\n ' % (l,nwords,line.wordCount), for w in range(nwords): print "%d:'%s'"%(w,words[w].text), print
print 'dumpXPreforemattedFrags(%s)' % str(P)
print '\n
def dumpXPreformattedFrags(P): print 'dumpXPreforemattedFrags(%s)' % str(P) frags = P.frags n =len(frags) for l in range(n): print "frag%d: '%s'" % (l, frags[l].text) l = 0 for L in _getFragLines(frags): n=0 for W in _getFragWords(L): print "frag%d.%d: size=%d" % (l, n, W[0]), n = n + 1 for w in W[1:]: print "'%s'" % ...
def try_it(text,style,dedent):
def try_it(text,style,dedent,aW,aH):
def try_it(text,style,dedent): P=XPreformatted(text,style,dedent=dedent) dumpXPreformattedFrags(P) aW, aH = 456.0, 42.8 w,h = P.wrap(aW, aH) dumpXPreformattedLines(P) S = P.split(aW,aH) for s in S: s.wrap(aW,aH) dumpXPreformattedLines(s) aH = 500
aW, aH = 456.0, 42.8
def try_it(text,style,dedent): P=XPreformatted(text,style,dedent=dedent) dumpXPreformattedFrags(P) aW, aH = 456.0, 42.8 w,h = P.wrap(aW, aH) dumpXPreformattedLines(P) S = P.split(aW,aH) for s in S: s.wrap(aW,aH) dumpXPreformattedLines(s) aH = 500
for (text,dedent,style) in [('''
for (text,dedent,style, aW, aH, active) in [('''
def try_it(text,style,dedent): P=XPreformatted(text,style,dedent=dedent) dumpXPreformattedFrags(P) aW, aH = 456.0, 42.8 w,h = P.wrap(aW, aH) dumpXPreformattedLines(P) S = P.split(aW,aH) for s in S: s.wrap(aW,aH) dumpXPreformattedLines(s) aH = 500
''',0,DTstyle),
''',0,DTstyle, 456.0, 42.8, 0),
def try_it(text,style,dedent): P=XPreformatted(text,style,dedent=dedent) dumpXPreformattedFrags(P) aW, aH = 456.0, 42.8 w,h = P.wrap(aW, aH) dumpXPreformattedLines(P) S = P.split(aW,aH) for s in S: s.wrap(aW,aH) dumpXPreformattedLines(s) aH = 500
''',3,DTstyle),
''',3, DTstyle, 456.0, 42.8, 0), ("""\ <font color=blue>class </font><font color=red>FastXMLParser</font>: def nonsense(self): self.foo = 'bar' """,0, styleSheet['Code'], 456.0, 4.8, 1),
def try_it(text,style,dedent): P=XPreformatted(text,style,dedent=dedent) dumpXPreformattedFrags(P) aW, aH = 456.0, 42.8 w,h = P.wrap(aW, aH) dumpXPreformattedLines(P) S = P.split(aW,aH) for s in S: s.wrap(aW,aH) dumpXPreformattedLines(s) aH = 500
try_it(text,style,dedent)
if active: try_it(text,style,dedent,aW,aH)
def try_it(text,style,dedent): P=XPreformatted(text,style,dedent=dedent) dumpXPreformattedFrags(P) aW, aH = 456.0, 42.8 w,h = P.wrap(aW, aH) dumpXPreformattedLines(P) S = P.split(aW,aH) for s in S: s.wrap(aW,aH) dumpXPreformattedLines(s) aH = 500
msg = "Missing attribute %s from %s" % (key, self)
msg = "Missing attribute %s from %s" % (attr, self)
def verify(self): """If the _attrMap attribute is not None, this checks all expected attributes are present; no unwanted attributes are present; and (if a checking function is found) checks each attribute has a valid value. Either succeeds or raises an informative exception. """
print 'saved', self._filename
if type(self._filename)==StringType: name = self._filename else: if hasattr(self._filename,'name'): name = self._filename.name else: name = '<Unknown>' print 'saved', name
def save(self): """Saves the file. If holding data, do a showPage() to save them having to.""" if len(self._code): self.showPage()
self.fileName = im.fileName
self.fileName = fileName
def __init__(self, fileName): if isinstance(fileName,ImageReader): self.__dict__ = fileName.__dict__ #borgize return if not haveImages: raise RuntimeError('Imaging Library not available, unable to import bitmaps') #start wih lots of null private fields, to be populated by #the relevant engine. self.fileName = fileNam...
self.data = [1]
self.data = [1,1]
def __init__(self): self.x = 0 self.y = 0 self.width = 100 self.height = 100 self.data = [1] self.labels = None # or list of strings self.startAngle = 90 self.direction = "clockwise"
labels = [''] * n
labels = [] if type(n) not in (ListType,TupleType): labels = [''] * n else: for m in n: labels = labels + [''] * m
def makeSectors(self): # normalize slice data if type(self.data) in (ListType, TupleType) and type(self.data[0]) in (ListType, TupleType): #it's a nested list, more than one sequence normData = [] for l in self.data: t = self.normalizeData(l) normData.append(t) else: normData = self.normalizeData(self.data) n = len(nor...
i = n-len(labels) if i>0: labels = labels + ['']*i
if type(n) not in (ListType,TupleType): i = n-len(labels) if i>0: labels = labels + ['']*i else: tlab = 0 for m in n: tlab = tlab+m i = tlab-len(labels) if i>0: labels = labels + ['']*i
def makeSectors(self): # normalize slice data if type(self.data) in (ListType, TupleType) and type(self.data[0]) in (ListType, TupleType): #it's a nested list, more than one sequence normData = [] for l in self.data: t = self.normalizeData(l) normData.append(t) else: normData = self.normalizeData(self.data) n = len(nor...
styleCount = len(self.slices)
def makeSectors(self): # normalize slice data if type(self.data) in (ListType, TupleType) and type(self.data[0]) in (ListType, TupleType): #it's a nested list, more than one sequence normData = [] for l in self.data: t = self.normalizeData(l) normData.append(t) else: normData = self.normalizeData(self.data) n = len(nor...
if n > 1:
if type(n) in (ListType,TupleType):
def makeSectors(self): # normalize slice data if type(self.data) in (ListType, TupleType) and type(self.data[0]) in (ListType, TupleType): #it's a nested list, more than one sequence normData = [] for l in self.data: t = self.normalizeData(l) normData.append(t) else: normData = self.normalizeData(self.data) n = len(nor...
elif n==1:
else:
def makeSectors(self): # normalize slice data if type(self.data) in (ListType, TupleType) and type(self.data[0]) in (ListType, TupleType): #it's a nested list, more than one sequence normData = [] for l in self.data: t = self.normalizeData(l) normData.append(t) else: normData = self.normalizeData(self.data) n = len(nor...
i = i + 1
if labels[i] != "": averageAngle = (a1+a2)/2.0 aveAngleRadians = averageAngle*pi/180.0 labelRadius = sectorStyle.labelRadius labelX = centerx + (0.5 * self.width * cos(aveAngleRadians) * labelRadius) labelY = centery + (0.5 * self.height * sin(aveAngleRadians) * labelRadius) theLabel = String(labelX, labelY, labels[i]...
def makeSectors(self): # normalize slice data if type(self.data) in (ListType, TupleType) and type(self.data[0]) in (ListType, TupleType): #it's a nested list, more than one sequence normData = [] for l in self.data: t = self.normalizeData(l) normData.append(t) else: normData = self.normalizeData(self.data) n = len(nor...
i = 0 if labels[i] != "": averageAngle = (a1+a2)/2.0 aveAngleRadians = averageAngle*pi/180.0 labelRadius = sectorStyle.labelRadius labelX = centerx + (0.5 * self.width * cos(aveAngleRadians) * labelRadius) labelY = centery + (0.5 * self.height * sin(aveAngleRadians) * labelRadius) theLabel = String(labelX, labelY, lab...
def makeSectors(self): # normalize slice data if type(self.data) in (ListType, TupleType) and type(self.data[0]) in (ListType, TupleType): #it's a nested list, more than one sequence normData = [] for l in self.data: t = self.normalizeData(l) normData.append(t) else: normData = self.normalizeData(self.data) n = len(nor...
join = LINEJOINS[cap]
join = LINEJOINS[join]
def _addCommand(self,cmd): if cmd[0] in ('BACKGROUND','ROWBACKGROUNDS','COLBACKGROUNDS'): self._bkgrndcmds.append(cmd) elif cmd[0] == 'SPAN': self._spanCmds.append(cmd) elif _isLineCommand(cmd): # we expect op, start, stop, weight, colour, cap, dashes, join cmd = tuple(cmd) if len(cmd)<5: raise ValueError('bad line com...
cmd = cmd[:7]+(join,)
cmd = cmd[:7]+(join,)+cmd[8:]
def _addCommand(self,cmd): if cmd[0] in ('BACKGROUND','ROWBACKGROUNDS','COLBACKGROUNDS'): self._bkgrndcmds.append(cmd) elif cmd[0] == 'SPAN': self._spanCmds.append(cmd) elif _isLineCommand(cmd): # we expect op, start, stop, weight, colour, cap, dashes, join cmd = tuple(cmd) if len(cmd)<5: raise ValueError('bad line com...
fonts.addMapping(ttname, 0, 0, face.name)
if not face.name in standardFonts: fonts.addMapping(ttname, 0, 0, face.name)
def registerTypeFace(face): assert isinstance(face, TypeFace), 'Not a TypeFace: %s' % face _typefaces[face.name] = face # HACK - bold/italic do not apply for type 1, so egister # all combinations of mappings. from reportlab.lib import fonts ttname = string.lower(face.name) fonts.addMapping(ttname, 0, 0, face.name) font...
f = self.labelTextFormat or (self._allIntTicks() and '%d' or str) elif f is str and self._allIntTicks(): f = '%d'
f = self.labelTextFormat or (self._allIntTicks() and '%.0f' or str) elif f is str and self._allIntTicks(): f = '%.0f'
def makeTickLabels(self): g = Group() if not self.visibleLabels: return g
pn = os_path_normpath(pn)
pn = _startswith_rl(os_path_normpath(pn)) if not pn.endswith(os.sep): pn += os.sep
def rl_isdir(pn,os_path_isdir=os.path.isdir,os_path_normpath=os.path.normpath): if os_path_isdir(pn): return True if _isFSD or __loader__ is None: return False pn = os_path_normpath(pn) return len(filter(lambda x,pn=pn: x.startswith(pn),__loader__._files.keys()))>0
obj = self.__class__()
obj = isinstance(self,Drawing) and Drawing(self.width,self.height) or Group()
def expandUserNodes(self): """Return a new object which only contains primitive shapes."""