rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
tx.moveCursor(-offset + 0.5 * extraspace, 0)
tx.moveCursor(-m, 0)
def cleanBlockQuotedText(text): """This is an internal utility which takes triple- quoted text form within the document and returns (hopefully) the paragraph the user intended originally.""" stripped = string.strip(text) lines = string.split(stripped, '\n') trimmed_lines = map(string.lstrip, lines) return string.join(trimmed_lines, ' ')
tx.moveCursor(offset + extraspace, 0)
m = offset + extraspace tx.moveCursor(m, 0)
def cleanBlockQuotedText(text): """This is an internal utility which takes triple- quoted text form within the document and returns (hopefully) the paragraph the user intended originally.""" stripped = string.strip(text) lines = string.split(stripped, '\n') trimmed_lines = map(string.lstrip, lines) return string.join(trimmed_lines, ' ')
tx.moveCursor(-offset + extraspace, 0)
tx.moveCursor(-m, 0)
def cleanBlockQuotedText(text): """This is an internal utility which takes triple- quoted text form within the document and returns (hopefully) the paragraph the user intended originally.""" stripped = string.strip(text) lines = string.split(stripped, '\n') trimmed_lines = map(string.lstrip, lines) return string.join(trimmed_lines, ' ')
tx.moveCursor(offset + 0.5 * line.extraSpace, 0)
m = offset+0.5*line.extraSpace tx.moveCursor(m, 0)
def cleanBlockQuotedText(text): """This is an internal utility which takes triple- quoted text form within the document and returns (hopefully) the paragraph the user intended originally.""" stripped = string.strip(text) lines = string.split(stripped, '\n') trimmed_lines = map(string.lstrip, lines) return string.join(trimmed_lines, ' ')
tx.moveCursor(-offset + 0.5 * line.extraSpace, 0)
tx.moveCursor(-m, 0)
def cleanBlockQuotedText(text): """This is an internal utility which takes triple- quoted text form within the document and returns (hopefully) the paragraph the user intended originally.""" stripped = string.strip(text) lines = string.split(stripped, '\n') trimmed_lines = map(string.lstrip, lines) return string.join(trimmed_lines, ' ')
tx.moveCursor(offset + line.extraSpace, 0)
m = offset+line.extraSpace tx.moveCursor(m, 0)
def cleanBlockQuotedText(text): """This is an internal utility which takes triple- quoted text form within the document and returns (hopefully) the paragraph the user intended originally.""" stripped = string.strip(text) lines = string.split(stripped, '\n') trimmed_lines = map(string.lstrip, lines) return string.join(trimmed_lines, ' ')
tx.moveCursor(-offset + line.extraSpace, 0)
tx.moveCursor(-m, 0)
def cleanBlockQuotedText(text): """This is an internal utility which takes triple- quoted text form within the document and returns (hopefully) the paragraph the user intended originally.""" stripped = string.strip(text) lines = string.split(stripped, '\n') trimmed_lines = map(string.lstrip, lines) return string.join(trimmed_lines, ' ')
return setps, labels
return steps, labels
def _getStepsAndLabels(self,xVals): if self.dailyFreq: xEOM = [] pm = 0 px = xVals[0] for x in xVals: m = x.month() if pm!=m: if pm: xEOM.append(px) pm = m px = x px = xVals[-1] if xEOM[-1]!=x: xEOM.append(px) steps, labels = self._xAxisTicker(xEOM) else: steps, labels = self._xAxisTicker(xVals) return setps, labels
strokeWidth=strokeWidth, strokeColor=strokeColor, fillColor=fillColor))
strokeWidth=strokeWidth, strokeColor=strokeColor, fillColor=fillColor,strokeLineJoin=1))
def _add_3d_bar(x1, x2, y1, y2, xoff, yoff, G=G,strokeColor=strokeColor, strokeWidth=strokeWidth, fillColor=fillColor): G.add(Polygon((x1,y1,x1+xoff, y1+yoff,x2+xoff, y2+yoff,x2,y2), strokeWidth=strokeWidth, strokeColor=strokeColor, fillColor=fillColor))
strokeColor=strokeColor, strokeWidth=strokeWidth, fillColor=fillColor))
strokeColor=strokeColor, strokeWidth=strokeWidth, fillColor=fillColor,strokeLineJoin=1))
def _add_3d_bar(x1, x2, y1, y2, xoff, yoff, G=G,strokeColor=strokeColor, strokeWidth=strokeWidth, fillColor=fillColor): G.add(Polygon((x1,y1,x1+xoff, y1+yoff,x2+xoff, y2+yoff,x2,y2), strokeWidth=strokeWidth, strokeColor=strokeColor, fillColor=fillColor))
print 'Poly([%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f])'% tuple(_ystrip_poly(x[0], x[1], y.y0, y.y1, xdepth, -ydepth))
def F(x,i, slope=slope, y0=y0, x0=x0): return float((x-x0)*slope[i]+y0[i])
self.valueAxis.setPosition(self.x, self.y, length)
vA = self.valueAxis vA.setPosition(self.x, self.y, length)
def _drawBegin(self,org,length): '''Position and configure value axis, return crossing value''' self.valueAxis.setPosition(self.x, self.y, length) self._getConfigureData() self.valueAxis.configure(self._configureData)
self.valueAxis.configure(self._configureData) crossesAt = self.valueAxis.scale(0)
vA.configure(self._configureData) crossesAt = vA.scale(0)
def _drawBegin(self,org,length): '''Position and configure value axis, return crossing value''' self.valueAxis.setPosition(self.x, self.y, length) self._getConfigureData() self.valueAxis.configure(self._configureData)
try: if self._flipXY: cA.setPosition(self._drawBegin(self.x,self.width), self.y, self.height) else: cA.setPosition(self.x, self._drawBegin(self.y,self.height), self.width) return self._drawFinish() finally: if vA: vA.joinAxis = ovAjA if cA: cA.joinAxis = ocAjA
if self._flipXY: cA.setPosition(self._drawBegin(self.x,self.width), self.y, self.height) else: cA.setPosition(self.x, self._drawBegin(self.y,self.height), self.width) return self._drawFinish()
def draw(self): cA, vA = self.categoryAxis, self.valueAxis if vA: ovAjA, vA.joinAxis = vA.joinAxis, cA if cA: ocAjA, cA.joinAxis = cA.joinAxis, vA try: if self._flipXY: cA.setPosition(self._drawBegin(self.x,self.width), self.y, self.height) else: cA.setPosition(self.x, self._drawBegin(self.y,self.height), self.width) return self._drawFinish() finally: if vA: vA.joinAxis = ovAjA if cA: cA.joinAxis = ocAjA
_renderPM.makeT1Font(fontName,f.face.findT1File(),f.encoding.vector,open_and_read)
if _renderPM._version<='0.98': _renderPM.makeT1Font(fontName,f.face.findT1File(),f.encoding.vector) else: _renderPM.makeT1Font(fontName,f.face.findT1File(),f.encoding.vector,open_and_read)
def _setFont(gs,fontName,fontSize): try: gs.setFont(fontName,fontSize) except _renderPM.Error, errMsg: if errMsg.args[0]!="Can't find font!": raise #here's where we try to add a font to the canvas try: f = getFont(fontName) _renderPM.makeT1Font(fontName,f.face.findT1File(),f.encoding.vector,open_and_read) except: s1, s2 = map(str,sys.exc_info()[:2]) raise RenderPMError, "Can't setFont(%s) missing the T1 files?\nOriginally %s: %s" % (fontName,s1,s2) gs.setFont(fontName,fontSize)
if theme.lower()=='chomsky': return chomsky(sentences)
if type(theme)==type(''): if theme.lower()=='chomsky': return chomsky(sentences) elif theme.upper() in ('STARTUP','COMPUTERS','BLAH','BUZZWORD','STARTREK','PRINTING','PYTHON'): theme = globals()[theme] else: raise ValueError('Unknown theme "%s"' % theme)
def randomText(theme=STARTUP, sentences=5): #this may or may not be appropriate in your company if theme.lower()=='chomsky': return chomsky(sentences) from random import randint, choice RANDOMWORDS = theme #sentences = 5 output = "" for sentenceno in range(randint(1,sentences)): output = output + 'Blah' for wordno in range(randint(10,25)): if randint(0,4)==0: word = choice(RANDOMWORDS) else: word = 'blah' output = output + ' ' +word output = output+'. ' return output
if dx<>0 or dy<>0: self._code.append('%s Td' % fp_str(dx, -dy))
dx = dx + float(L[-3]) dy = dy - float(L[-2]) self._code.append('%s Td' % fp_str(dx, -dy))
def moveCursor(self, dx, dy): """Moves to a point dx, dy away from the start of the current line - NOT from the current point! So if you call it in mid-sentence, watch out.""" if self._code and self._code[-1][-3:]==' Td': L = string.split(self._code[-1]) if len(L)==3: del self._code[-1] else: self._code[-1] = string.join(L[:-4]) if dx<>0 or dy<>0: self._code.append('%s Td' % fp_str(dx, -dy))
if self._code[-1][-3:]==' Td': L = string.split(self._code[-1]) if len(L)==3: del self._code[-1] else: self._code[-1] = string.join(L[:-4]) if dx<>0: self._code.append('%s 0 Td' % fp_str(dx))
self.moveCursor(dx,0)
def setXPos(self, dx): """Moves to a point dx away from the start of the current line - NOT from the current point! So if you call it in mid-sentence, watch out.""" if self._code[-1][-3:]==' Td': L = string.split(self._code[-1]) if len(L)==3: del self._code[-1] else: self._code[-1] = string.join(L[:-4]) if dx<>0: self._code.append('%s 0 Td' % fp_str(dx))
def _AsciiBase85Encode(input): """This is a compact encoding used for binary data within a PDF file. Four bytes of binary data become five bytes of ASCII. This is the default method used for encoding images.""" outstream = cStringIO.StringIO() whole_word_count, remainder_size = divmod(len(input), 4) cut = 4 * whole_word_count body, lastbit = input[0:cut], input[cut:] for i in range(whole_word_count): offset = i*4 b1 = ord(body[offset]) b2 = ord(body[offset+1]) b3 = ord(body[offset+2]) b4 = ord(body[offset+3]) num = 16777216L * b1 + 65536 * b2 + 256 * b3 + b4 if num == 0: outstream.write('z') else:
try: import _streams _AsciiBase85Encode = _streams.ASCII85Encode except ImportError: def _AsciiBase85Encode(input): """This is a compact encoding used for binary data within a PDF file. Four bytes of binary data become five bytes of ASCII. This is the default method used for encoding images.""" outstream = cStringIO.StringIO() whole_word_count, remainder_size = divmod(len(input), 4) cut = 4 * whole_word_count body, lastbit = input[0:cut], input[cut:] for i in range(whole_word_count): offset = i*4 b1 = ord(body[offset]) b2 = ord(body[offset+1]) b3 = ord(body[offset+2]) b4 = ord(body[offset+3]) if b1<128: num = (((((b1<<8)|b2)<<8)|b3)<<8)|b4 else: num = 16777216L * b1 + 65536 * b2 + 256 * b3 + b4 if num == 0: outstream.write('z') else: temp, c5 = divmod(num, 85) temp, c4 = divmod(temp, 85) temp, c3 = divmod(temp, 85) c1, c2 = divmod(temp, 85) assert ((85**4) * c1) + ((85**3) * c2) + ((85**2) * c3) + (85*c4) + c5 == num, 'dodgy code!' outstream.write(chr(c1+33)) outstream.write(chr(c2+33)) outstream.write(chr(c3+33)) outstream.write(chr(c4+33)) outstream.write(chr(c5+33)) if remainder_size > 0: while len(lastbit) < 4: lastbit = lastbit + '\000' b1 = ord(lastbit[0]) b2 = ord(lastbit[1]) b3 = ord(lastbit[2]) b4 = ord(lastbit[3]) num = 16777216L * b1 + 65536 * b2 + 256 * b3 + b4
def _AsciiBase85Encode(input): """This is a compact encoding used for binary data within a PDF file. Four bytes of binary data become five bytes of ASCII. This is the default method used for encoding images.""" outstream = cStringIO.StringIO() # special rules apply if not a multiple of four bytes. whole_word_count, remainder_size = divmod(len(input), 4) cut = 4 * whole_word_count body, lastbit = input[0:cut], input[cut:] for i in range(whole_word_count): offset = i*4 b1 = ord(body[offset]) b2 = ord(body[offset+1]) b3 = ord(body[offset+2]) b4 = ord(body[offset+3]) num = 16777216L * b1 + 65536 * b2 + 256 * b3 + b4 if num == 0: #special case outstream.write('z') else: #solve for five base-85 numbers temp, c5 = divmod(num, 85) temp, c4 = divmod(temp, 85) temp, c3 = divmod(temp, 85) c1, c2 = divmod(temp, 85) assert ((85**4) * c1) + ((85**3) * c2) + ((85**2) * c3) + (85*c4) + c5 == num, 'dodgy code!' outstream.write(chr(c1+33)) outstream.write(chr(c2+33)) outstream.write(chr(c3+33)) outstream.write(chr(c4+33)) outstream.write(chr(c5+33)) # now we do the final bit at the end. I repeated this separately as # the loop above is the time-critical part of a script, whereas this # happens only once at the end. #encode however many bytes we have as usual if remainder_size > 0: while len(lastbit) < 4: lastbit = lastbit + '\000' b1 = ord(lastbit[0]) b2 = ord(lastbit[1]) b3 = ord(lastbit[2]) b4 = ord(lastbit[3]) num = 16777216L * b1 + 65536 * b2 + 256 * b3 + b4 #solve for c1..c5 temp, c5 = divmod(num, 85) temp, c4 = divmod(temp, 85) temp, c3 = divmod(temp, 85) c1, c2 = divmod(temp, 85) #print 'encoding: %d %d %d %d -> %d -> %d %d %d %d %d' % ( # b1,b2,b3,b4,num,c1,c2,c3,c4,c5) lastword = chr(c1+33) + chr(c2+33) + chr(c3+33) + chr(c4+33) + chr(c5+33) #write out most of the bytes. outstream.write(lastword[0:remainder_size + 1]) #terminator code for ascii 85 outstream.write('~>') outstream.reset() return outstream.read()
assert ((85**4) * c1) + ((85**3) * c2) + ((85**2) * c3) + (85*c4) + c5 == num, 'dodgy code!' outstream.write(chr(c1+33)) outstream.write(chr(c2+33)) outstream.write(chr(c3+33)) outstream.write(chr(c4+33)) outstream.write(chr(c5+33)) if remainder_size > 0: while len(lastbit) < 4: lastbit = lastbit + '\000' b1 = ord(lastbit[0]) b2 = ord(lastbit[1]) b3 = ord(lastbit[2]) b4 = ord(lastbit[3]) num = 16777216L * b1 + 65536 * b2 + 256 * b3 + b4 temp, c5 = divmod(num, 85) temp, c4 = divmod(temp, 85) temp, c3 = divmod(temp, 85) c1, c2 = divmod(temp, 85) lastword = chr(c1+33) + chr(c2+33) + chr(c3+33) + chr(c4+33) + chr(c5+33) outstream.write(lastword[0:remainder_size + 1]) outstream.write('~>') outstream.reset() return outstream.read()
lastword = chr(c1+33) + chr(c2+33) + chr(c3+33) + chr(c4+33) + chr(c5+33) outstream.write(lastword[0:remainder_size + 1]) outstream.write('~>') outstream.reset() return outstream.read()
def _AsciiBase85Encode(input): """This is a compact encoding used for binary data within a PDF file. Four bytes of binary data become five bytes of ASCII. This is the default method used for encoding images.""" outstream = cStringIO.StringIO() # special rules apply if not a multiple of four bytes. whole_word_count, remainder_size = divmod(len(input), 4) cut = 4 * whole_word_count body, lastbit = input[0:cut], input[cut:] for i in range(whole_word_count): offset = i*4 b1 = ord(body[offset]) b2 = ord(body[offset+1]) b3 = ord(body[offset+2]) b4 = ord(body[offset+3]) num = 16777216L * b1 + 65536 * b2 + 256 * b3 + b4 if num == 0: #special case outstream.write('z') else: #solve for five base-85 numbers temp, c5 = divmod(num, 85) temp, c4 = divmod(temp, 85) temp, c3 = divmod(temp, 85) c1, c2 = divmod(temp, 85) assert ((85**4) * c1) + ((85**3) * c2) + ((85**2) * c3) + (85*c4) + c5 == num, 'dodgy code!' outstream.write(chr(c1+33)) outstream.write(chr(c2+33)) outstream.write(chr(c3+33)) outstream.write(chr(c4+33)) outstream.write(chr(c5+33)) # now we do the final bit at the end. I repeated this separately as # the loop above is the time-critical part of a script, whereas this # happens only once at the end. #encode however many bytes we have as usual if remainder_size > 0: while len(lastbit) < 4: lastbit = lastbit + '\000' b1 = ord(lastbit[0]) b2 = ord(lastbit[1]) b3 = ord(lastbit[2]) b4 = ord(lastbit[3]) num = 16777216L * b1 + 65536 * b2 + 256 * b3 + b4 #solve for c1..c5 temp, c5 = divmod(num, 85) temp, c4 = divmod(temp, 85) temp, c3 = divmod(temp, 85) c1, c2 = divmod(temp, 85) #print 'encoding: %d %d %d %d -> %d -> %d %d %d %d %d' % ( # b1,b2,b3,b4,num,c1,c2,c3,c4,c5) lastword = chr(c1+33) + chr(c2+33) + chr(c3+33) + chr(c4+33) + chr(c5+33) #write out most of the bytes. outstream.write(lastword[0:remainder_size + 1]) #terminator code for ascii 85 outstream.write('~>') outstream.reset() return outstream.read()
num = ((85**4) * c1) + ((85**3) * c2) + ((85**2) * c3) + (85*c4) + c5
num = ((85L**4) * c1) + ((85**3) * c2) + ((85**2) * c3) + (85*c4) + c5
def _AsciiBase85Decode(input): """This is not used - Acrobat Reader decodes for you - but a round trip is essential for testing.""" outstream = cStringIO.StringIO() #strip all whitespace stripped = string.join(string.split(input),'') #check end assert stripped[-2:] == '~>', 'Invalid terminator for Ascii Base 85 Stream' stripped = stripped[:-2] #chop off terminator #may have 'z' in it which complicates matters - expand them stripped = string.replace(stripped,'z','!!!!!') # special rules apply if not a multiple of five bytes. whole_word_count, remainder_size = divmod(len(stripped), 5) #print '%d words, %d leftover' % (whole_word_count, remainder_size) assert remainder_size <> 1, 'invalid Ascii 85 stream!' cut = 5 * whole_word_count body, lastbit = stripped[0:cut], stripped[cut:] for i in range(whole_word_count): offset = i*5 c1 = ord(body[offset]) - 33 c2 = ord(body[offset+1]) - 33 c3 = ord(body[offset+2]) - 33 c4 = ord(body[offset+3]) - 33 c5 = ord(body[offset+4]) - 33 num = ((85**4) * c1) + ((85**3) * c2) + ((85**2) * c3) + (85*c4) + c5 temp, b4 = divmod(num,256) temp, b3 = divmod(temp,256) b1, b2 = divmod(temp, 256) assert num == 16777216 * b1 + 65536 * b2 + 256 * b3 + b4, 'dodgy code!' outstream.write(chr(b1)) outstream.write(chr(b2)) outstream.write(chr(b3)) outstream.write(chr(b4)) #decode however many bytes we have as usual if remainder_size > 0: while len(lastbit) < 5: lastbit = lastbit + '!' c1 = ord(lastbit[0]) - 33 c2 = ord(lastbit[1]) - 33 c3 = ord(lastbit[2]) - 33 c4 = ord(lastbit[3]) - 33 c5 = ord(lastbit[4]) - 33 num = ((85**4) * c1) + ((85**3) * c2) + ((85**2) * c3) + (85*c4) + c5 temp, b4 = divmod(num,256) temp, b3 = divmod(temp,256) b1, b2 = divmod(temp, 256) assert num == 16777216 * b1 + 65536 * b2 + 256 * b3 + b4, 'dodgy code!' #print 'decoding: %d %d %d %d %d -> %d -> %d %d %d %d' % ( # c1,c2,c3,c4,c5,num,b1,b2,b3,b4) #the last character needs 1 adding; the encoding loses #data by rounding the number to x bytes, and when #divided repeatedly we get one less if remainder_size == 2: lastword = chr(b1+1) elif remainder_size == 3: lastword = chr(b1) + chr(b2+1) elif remainder_size == 4: lastword = chr(b1) + chr(b2) + chr(b3+1) outstream.write(lastword) #terminator code for ascii 85 outstream.reset() return outstream.read()
return self.variColumn and [max(M[r:r+3]) for r in range(0,len(M),self.columnMaximum)] or max(M)
if not M: return 0 if self.variColumn: columnMaximum = self.columnMaximum return [max(M[r:r+columnMaximum]) for r in range(0,len(M),self.columnMaximum)] else: return max(M)
def _calculateMaxWidth(self, colorNamePairs): "Calculate the maximum width of some given strings." M = [] a = M.append for t in self._getTexts(colorNamePairs): m = [stringWidth(s, self.fontName, self.fontSize) for s in t.split('\n')] M.append(m and max(m) or 0) return self.variColumn and [max(M[r:r+3]) for r in range(0,len(M),self.columnMaximum)] or max(M)
self.onProgress('PASS', passes)
self._onProgress('PASS', passes)
def multiBuild(self, story, filename=None, canvasmaker=canvas.Canvas, maxPasses = 10): """Makes multiple passes until all indexing flowables are happy.""" self._indexingFlowables = [] #scan the story and keep a copy for thing in story: if thing.isIndexing(): self._indexingFlowables.append(thing) #print 'scanned story, found these indexing flowables:\n' #print self._indexingFlowables
print "file %s contains %d tab characters!" % (filename, tabCount)
self.output.write("file %s contains %d tab characters!\n" % (filename, tabCount))
def checkFileForTabs(self, filename): txt = open(filename, 'r').read() chunks = string.split(txt, '\t') tabCount = len(chunks) - 1 if tabCount: #raise Exception, "File %s contains %d tab characters!" % (filename, tabCount) print "file %s contains %d tab characters!" % (filename, tabCount)
print "file %s contains %d trailing spaces, or %0.2f%% wastage" % (filename, badChars, 100.0*badChars/initSize)
self.output.write("file %s contains %d trailing spaces, or %0.2f%% wastage" % (filename, badChars, 100.0*badChars/initSize))
def checkFileForTrailingSpaces(self, filename): txt = open(filename, 'r').read() initSize = len(txt) badLines = 0 badChars = 0 for line in string.split(txt, '\n'): stripped = string.rstrip(line) spaces = len(line) - len(stripped) # OK, so they might be trailing tabs, who cares? if spaces: badLines = badLines + 1 badChars = badChars + spaces
if canv._pagesize != self.pagesize: if self.pagesize:
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 != dp: if sp:
def checkPageSize(self,canv,doc): '''This gets called by the template framework''' if canv._pagesize != self.pagesize: if self.pagesize: canv.setPageSize(self.pagesize) elif canv._pagesize != doc.pagesize: canv.setPageSize(doc.pagesize)
elif canv._pagesize != doc.pagesize:
elif cp != dp:
def checkPageSize(self,canv,doc): '''This gets called by the template framework''' if canv._pagesize != self.pagesize: if self.pagesize: canv.setPageSize(self.pagesize) elif canv._pagesize != doc.pagesize: canv.setPageSize(doc.pagesize)
return ((enc.name == other.name) and (enc.vector == other.vector))
return ((self.name == other.name) and (self.vector == other.vector))
def isEqual(self, other): return ((enc.name == other.name) and (enc.vector == other.vector))
print 'Attempting to register', fontName
def _SWRecover(text, fontName, fontSize, encoding): '''This is called when _rl_accel's database doesn't know about a font. Currently encoding is always a dummy. ''' try: print 'Attempting to register', fontName font = getFont(fontName) registerFont(font) print 'registered font %s' % fontName dumpFontData() return _stringWidth(text,fontName,fontSize,encoding) except: warnOnce('Font %s:%s not found - using Courier:%s for widths'%(fontName,encoding,encoding)) return _stringWidth(text,'courier',fontSize,encoding)
print 'registered font %s' % fontName dumpFontData()
def _SWRecover(text, fontName, fontSize, encoding): '''This is called when _rl_accel's database doesn't know about a font. Currently encoding is always a dummy. ''' try: print 'Attempting to register', fontName font = getFont(fontName) registerFont(font) print 'registered font %s' % fontName dumpFontData() return _stringWidth(text,fontName,fontSize,encoding) except: warnOnce('Font %s:%s not found - using Courier:%s for widths'%(fontName,encoding,encoding)) return _stringWidth(text,'courier',fontSize,encoding)
assert len(dataSeries[0]) > 2, msg
assert len(dataSeries[0]) >= 2, msg
def configure(self, dataSeries): """Let the axis configure its scale and range based on the data. Called after setPosition.Let it look at a list of lists of numbers determine the tick mark intervals. If valueMin, valueMax and valueStep are configured then it will use them; if any of them are set to Auto it will look at the data and make some sensible decision. You may override this to build custom axes with irregular intervals. It creates an internal variable self._values, which is a list of numbers to use in plotting."""
captionFont="Times-Italic", captionSize=12, background=None):
captionFont="Times-Italic", captionSize=12, background=None, captionTextColor=toColor('black'), captionBackColor=None):
def __init__(self, width, height, caption="", captionFont="Times-Italic", captionSize=12, background=None): Flowable.__init__(self) self.width = width self.figureHeight = height self.caption = caption self.background = background if self.caption: self.captionHeight = 0 # work out later self.captionStyle = ParagraphStyle( 'Caption', fontName=captionFont, fontSize=captionSize, leading=1.2*captionSize, spaceBefore=captionSize * 0.5, alignment=TA_CENTER) #must build paragraph now to get sequencing in synch with rest of story self.captionPara = Paragraph(self.caption, self.captionStyle)
if self.caption: self.captionHeight = 0
self.spaceBefore = 12 self.spaceAfter = 12 def _getCaptionPara(self): caption = self.caption captionFont = self.captionFont captionSize = self.captionSize captionTextColor = self.captionTextColor captionBackColor = self.captionBackColor if self._captionData!=(caption,captionFont,captionSize,captionTextColor,captionBackColor): self._captionData = (caption,captionFont,captionSize,captionTextColor,captionBackColor)
def __init__(self, width, height, caption="", captionFont="Times-Italic", captionSize=12, background=None): Flowable.__init__(self) self.width = width self.figureHeight = height self.caption = caption self.background = background if self.caption: self.captionHeight = 0 # work out later self.captionStyle = ParagraphStyle( 'Caption', fontName=captionFont, fontSize=captionSize, leading=1.2*captionSize, spaceBefore=captionSize * 0.5, alignment=TA_CENTER) #must build paragraph now to get sequencing in synch with rest of story self.captionPara = Paragraph(self.caption, self.captionStyle)
self.spaceBefore = 12 self.spaceAfter = 12
def __init__(self, width, height, caption="", captionFont="Times-Italic", captionSize=12, background=None): Flowable.__init__(self) self.width = width self.figureHeight = height self.caption = caption self.background = background if self.caption: self.captionHeight = 0 # work out later self.captionStyle = ParagraphStyle( 'Caption', fontName=captionFont, fontSize=captionSize, leading=1.2*captionSize, spaceBefore=captionSize * 0.5, alignment=TA_CENTER) #must build paragraph now to get sequencing in synch with rest of story self.captionPara = Paragraph(self.caption, self.captionStyle)
def wrap(self, availWidth, availHeight):
def _scale(self,availWidth,availHeight):
def wrap(self, availWidth, availHeight): "Rescale to fit according to the rules, but only once" if self._scaleFactor is None or self.width>availWidth or self.height>availHeight: w, h = Figure.wrap(self, availWidth, availHeight) captionHeight = h - self.figureHeight if self.scaleFactor is None: #scale factor None means auto self._scaleFactor = min(availWidth/self.width,(availHeight-captionHeight)/self.figureHeight) else: #they provided a factor self._scaleFactor = self.scaleFactor if self._scaleFactor<1 and self.shrinkToFit: self.width = self.width * self._scaleFactor - 0.0001 self.figureHeight = self.figureHeight * self._scaleFactor elif self._scaleFactor>1 and self.growToFit: self.width = self.width*self._scaleFactor - 0.0001 self.figureHeight = self.figureHeight * self._scaleFactor return Figure.wrap(self, availWidth, availHeight)
Marius Gedminas $<[email protected]>$ with the help of Viktorija Zaksien $<[email protected]>$
Marius Gedminas [email protected]$ with the help of Viktorija Zaksien [email protected]$
def findFontName(path): "Extract a font name from an AFM file." f = open(path) found = 0 while not found: line = f.readline()[:-1] if not found and line[:16] == 'StartCharMetrics': raise FontNameNotFoundError, path if line[:8] == 'FontName': fontName = line[9:] found = 1 return fontName
disc("""Simple things are done simply; we use <b>$reportlab.pdfbase.ttfonts.TTFont<$</b> to create a true type
disc("""Simple things are done simply; we use <b>$reportlab.pdfbase.ttfonts.TTFont$</b> to create a true type
def findFontName(path): "Extract a font name from an AFM file." f = open(path) found = 0 while not found: line = f.readline()[:-1] if not found and line[:16] == 'StartCharMetrics': raise FontNameNotFoundError, path if line[:8] == 'FontName': fontName = line[9:] found = 1 return fontName
elif sys.platform in ('linux2',):
elif sys.platform in ('linux2','freebsd4',):
def _setOpt(name, value, conv=None): '''set a module level value from environ/default''' from os import environ ename = 'RL_'+name if environ.has_key(ename): value = environ[ename] if conv: value = conv(value) globals()[name] = value
fontDir = diskName + ':Applications:Python 2.1:reportlab:fonts'
fontDir = diskName + ':Applications:Python %s:reportlab:fonts' % sys_version
def _setOpt(name, value, conv=None): '''set a module level value from environ/default''' from os import environ ename = 'RL_'+name if environ.has_key(ename): value = environ[ename] if conv: value = conv(value) globals()[name] = value
sys_version = string.split(sys.version)[0]
def _setOpt(name, value, conv=None): '''set a module level value from environ/default''' from os import environ ename = 'RL_'+name if environ.has_key(ename): value = environ[ename] if conv: value = conv(value) globals()[name] = value
tx.setTextWordSpacing(1.0 * extraspace / len(words))
tx.setWordSpace(extraspace / float(len(words)-1))
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.setTextWordSpacing()
tx.setWordSpace(0.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."""
elif style.alignment == TA_RIGHT:
elif self.style.alignment == TA_RIGHT:
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."""
elif style.alignment == TA_JUSTIFY: if lineno == len(lines) - 1:
elif self.style.alignment == TA_JUSTIFY: if lineno == len(self.lines) - 1:
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."""
def calcBarPositions0(self):
def calcBarPositions(self):
def calcBarPositions0(self): """Works out where they go.
(groupX, groupWidth) = self.categoryAxis.scale(colNo) x = (groupX + (0.5 * self.groupSpacing * normFactor) + (rowNo * self.barWidth * normFactor) + (rowNo * self.barSpacing * normFactor) )
if self.useAbsolute: groupX = len(self.data) * self.barWidth + \ len(self.data) * self.barSpacing + \ self.groupSpacing groupX = groupX * colNo + 0.5 * self.groupSpacing + self.x x = groupX + rowNo * (self.barWidth + self.barSpacing) else: (groupX, groupWidth) = self.categoryAxis.scale(colNo) x = groupX + normFactor * (0.5 * self.groupSpacing \ + rowNo * (self.barWidth + self.barSpacing))
def calcBarPositions0(self): """Works out where they go.
y = self.valueAxis.scale(0) height = self.valueAxis.scale(datum) - y barRow.append((x, y, width, height)) if self.debug: print "x, y, width, height:", x, y, width, height print "self.valueAxis.scale(10)", self.valueAxis.scale(self.valueAxis.valueMin) self._barPositions.append(barRow) def calcBarPositions(self): """Works out where they go. Sets an attribute _barPositions which is a list of lists of (x, y, width, height) matching the data.""" self._seriesCount = len(self.data) self._rowLength = len(self.data[0]) if self.useAbsolute: normFactor = 1.0 else: normWidth = (self.groupSpacing + (self._seriesCount * self.barWidth) + ((self._seriesCount - 1) * self.barSpacing) ) availWidth = self.categoryAxis.scale(0)[1] normFactor = availWidth / normWidth if self.debug: print '%d series, %d points per series' % (self._seriesCount, self._rowLength) print 'width = %d group + (%d bars * %d barWidth) + (%d gaps * %d interBar) = %d total' % ( self.groupSpacing, self._seriesCount, self.barWidth, self._seriesCount - 1, self.barSpacing, normWidth) self._barPositions = [] for rowNo in range(len(self.data)): barRow = [] for colNo in range(len(self.data[0])): datum = self.data[rowNo][colNo] (groupX, groupWidth) = self.categoryAxis.scale(colNo) x = (groupX + (0.5 * self.groupSpacing * normFactor) + (rowNo * self.barWidth * normFactor) + (rowNo * self.barSpacing * normFactor) ) width = self.barWidth * normFactor
def calcBarPositions0(self): """Works out where they go.
if Auto in (self.valueAxis.valueMin, self.valueAxis.valueMax): y = self.valueAxis.scale(self._findMinMaxValues()[0]) elif self.valueAxis.valueMin <= 0 <= self.valueAxis.valueMax: y = self.valueAxis.scale(0) elif 0 < self.valueAxis.valueMin: y = self.valueAxis.scale(self.valueAxis.valueMin) elif self.valueAxis.valueMax < 0: y = self.valueAxis.scale(self.valueAxis.valueMax)
scale = self.valueAxis.scale vm, vM = self.valueAxis.valueMin, self.valueAxis.valueMax if Auto in (vm, vM): y = scale(self._findMinMaxValues()[0]) elif vm <= 0 <= vM: y = scale(0) elif 0 < vm: y = scale(vm) elif vM < 0: y = scale(vM)
def calcBarPositions(self): """Works out where they go.
dataSample5 = [(10, 20), (20, 30), (30, 40), (40, 50), (50, 60)]
dataSample5 = [(10, 60), (20, 50), (30, 40), (40, 30)]
def sample4d(): "Make a bar chart showing value axis region entirely *below* zero." drawing = Drawing(400, 200) data = [(-13, -20)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = -30 bc.valueAxis.valueMax = -10 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dy = -5 bc.categoryAxis.categoryNames = ['Ying', 'Yang'] drawing.add(bc) return drawing
assert not filter(lambda x: isinstance(x,LCActionFlowable),V),'LCActionFlowables not allowed in sublists'
assert not [x for x in V if isinstance(x,LCActionFlowable)],'LCActionFlowables not allowed in sublists'
def _flowableSublist(V): "if it isn't a list or tuple, wrap it in a list" if type(V) not in (ListType, TupleType): V = V is not None and [V] or [] from doctemplate import LCActionFlowable assert not filter(lambda x: isinstance(x,LCActionFlowable),V),'LCActionFlowables not allowed in sublists' return V
if getattr(self,'_width_calculated_once',None): return
def _calc_width(self,availWidth,W=None): #comments added by Andy to Robin's slightly #terse variable names if not W: W = _calc_pc(self._argW,availWidth) #widths array #print 'widths array = %s' % str(self._colWidths) canv = getattr(self,'canv',None) saved = None
canv = getattr(self,'canv',None) saved = None
def _calc_width(self,availWidth,W=None): #comments added by Andy to Robin's slightly #terse variable names if not W: W = _calc_pc(self._argW,availWidth) #widths array #print 'widths array = %s' % str(self._colWidths) canv = getattr(self,'canv',None) saved = None
if self._spanCmds: colspans = self._colSpannedCells else: colspans = {}
canv = getattr(self,'canv',None) saved = None colSpanCells = self._spanCmds and self._colSpanCells or ()
def _calc_width(self,availWidth,W=None): #comments added by Andy to Robin's slightly #terse variable names if not W: W = _calc_pc(self._argW,availWidth) #widths array #print 'widths array = %s' % str(self._colWidths) canv = getattr(self,'canv',None) saved = None
if colspans.has_key((j, i)):
if (j, i) in colSpanCells:
def _calc_width(self,availWidth,W=None): #comments added by Andy to Robin's slightly #terse variable names if not W: W = _calc_pc(self._argW,availWidth) #widths array #print 'widths array = %s' % str(self._colWidths) canv = getattr(self,'canv',None) saved = None
canv = getattr(self,'canv',None) saved = None if self._spanCmds: spans = self._rowSpannedCells else: spans = {}
def _calc_height(self, availHeight, availWidth, H=None, W=None):
if spans.has_key((j, i)):
ji = j,i if ji in rowSpanCells:
def _calc_height(self, availHeight, availWidth, H=None, W=None):
if hasattr(self,'_width_calculated_once'): return self._width_calculated_once = 1
def _calc(self, availWidth, availHeight): #if hasattr(self,'_width'): return
spanRanges = {} for row in range(self._nrows): for col in range(self._ncols): spanRanges[(col, row)] = (col, row, col, row)
self._spanRanges = spanRanges = {} for x in xrange(self._ncols): for y in xrange(self._nrows): spanRanges[x,y] = (x, y, x, y) self._colSpanCells = [] self._rowSpanCells = [] csa = self._colSpanCells.append rsa = self._rowSpanCells.append
def _calcSpanRanges(self): """Work out rects for tables which do row and column spanning.
if x0 > x1: x0, x1 = x1, x0 if y0 > y1: y0, y1 = y1, y0 for y in xrange(y0, y1+1): for x in xrange(x0, x1+1): spanRanges[x, y] = None spanRanges[x0,y0] = (x0, y0, x1, y1) self._spanRanges = spanRanges colSpannedCells = {} for (key, value) in spanRanges.items(): if value is None: colSpannedCells[key] = 1 elif len(value) == 4: if value[0] == value[2]: pass else: colSpannedCells[key] = 1 self._colSpannedCells = colSpannedCells rowSpannedCells = {} for (key, value) in spanRanges.items(): if value is None: rowSpannedCells[key] = 1 elif len(value) == 4: if value[1] == value[3]: pass else: rowSpannedCells[key] = 1 self._rowSpannedCells = rowSpannedCells
if x0 > x1: x0, x1 = x1, x0 if y0 > y1: y0, y1 = y1, y0 if x0!=x1 or y0!=y1: if x0!=x1: for y in xrange(y0, y1+1): for x in xrange(x0,x1+1): csa((x,y)) if y0!=y1: for y in xrange(y0, y1+1): for x in xrange(x0,x1+1): rsa((x,y)) for y in xrange(y0, y1+1): for x in xrange(x0,x1+1): spanRanges[x,y] = None spanRanges[x0,y0] = (x0, y0, x1, y1)
def _calcSpanRanges(self): """Work out rects for tables which do row and column spanning.
import logger
from reportlab.lib import logger
def stringWidth(self, text, fontName, fontSize, encoding=None): "gets width of a string in the given font and size" if encoding is not None: import logger logger.warnOnce('encoding argument to Canvas.stringWidth is deprecated and has no effect!') #if encoding is None: encoding = self._doc.encoding return pdfmetrics.stringWidth(text, fontName, fontSize)
val = string.atoi(val,16)
b = 16 elif string.lower(val[:2]) == '0x': b = 16 val = val[2:] val = string.atoi(val,b)
def HexColor(val): """This class converts a hex string, or an actual integer number, into the corresponding color. E.g., in "AABBCC" or 0xAABBCC, AA is the red, BB is the green, and CC is the blue (00-FF). HTML uses a hex string with a preceding hash; if this is present, it is stripped off. (AR, 3-3-2000) """ if type(val) == types.StringType: if val[:1] == '#': val = val[1:] val = string.atoi(val,16) factor = 1.0 / 255 return Color(factor * ((val >> 16) & 0xFF), factor * ((val >> 8) & 0xFF), factor * (val & 0xFF))
namedColors = {}
__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
namedColors[name] = value return namedColors
__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
if err != 'not all arguments converted': raise
if str(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
RXPUDIR=os.path.join('build','_pyRXPU') RXPDIR='rxp' if os.path.exists(RXPUDIR): shutil.rmtree(RXPUDIR) os.makedirs(RXPUDIR) RXPLIBSOURCES=[] uRXPLIBSOURCES=[] for f in ('xmlparser.c', 'url.c', 'charset.c', 'string16.c', 'ctype16.c', 'dtd.c', 'input.c', 'stdio16.c', 'system.c', 'hash.c', 'version.c', 'namespaces.c', 'http.c'): RXP_file = os.path.join(RXPDIR,f) uRXP_file = os.path.join(RXPUDIR,f.replace('.','U.')) RXPLIBSOURCES.append(RXP_file) shutil.copy2(RXP_file,uRXP_file) uRXPLIBSOURCES.append(uRXP_file) pyRXPU_c = os.path.join(RXPUDIR,'pyRXPU.c') shutil.copy2('pyRXP.c',pyRXPU_c) uRXPLIBSOURCES.append(pyRXPU_c)
def raiseConfigError(msg): import exceptions class ConfigError(exceptions.Exception): pass raise ConfigError(msg)
ext_modules = [Extension( 'pyRXP', ['pyRXP.c']+RXPLIBSOURCES, include_dirs=[RXPDIR], define_macros=[('CHAR_SIZE', 8),], library_dirs=[], libraries=LIBS, ), Extension( 'pyRXPU', uRXPLIBSOURCES, include_dirs=[RXPDIR], define_macros=[('CHAR_SIZE', 16),], library_dirs=[], libraries=LIBS, ), ],
ext_modules = EXT_MODULES,
def raiseConfigError(msg): import exceptions class ConfigError(exceptions.Exception): pass raise ConfigError(msg)
MovePYDs('pyRXPU.pyd',)
if buildU: MovePYDs('pyRXPU.pyd',)
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)
graphic.drawOn(canv)
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)
def drawOn(self, canv): for graphic in self.graphics: graphic.drawOn(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)
if self.filename: x, y = self.x, self.y w, h = self.width, self.height canv.drawInlineImage(self.filename, x, y, w, h)
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)
commands = commands + cmds
commands = commands + list(cmds)
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)
do_exec("mv reportlab %s" dst)
do_exec("mv reportlab %s" % dst)
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:%[email protected]:/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')
wrap fails. Stupid flowables should return (). Clever flowables
wrap fails. Stupid flowables should return []. Clever flowables
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 []
return flowable.wrap(self.width, y-p-s)
return flowable.split(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)
def doIt(file) : """Generates a PDF document, save it into file, and returns Python source code.
def doIt(file, regenerate=0) : """Generates a PDF document, save it into file.
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. """'''
returns : the equivalent Python source code as a string of text. """'''
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 '''
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. """'''
return str(c)
if regenerate : return str(c)
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. """'''
print doIt(sys.argv[1]) sys.exit(0) '''
print doIt(sys.argv[1], regenerate=1) sys.exit(0)'''
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. """'''
_in = 0
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
global _in if not _in :
if not self._parent._parent._in : self._precomment()
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
_in += 1
self._postcomment() self._parent._parent._in += 1
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
_in -= 1
self._parent._parent._in -= 1
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 try : if (not _in) and (self._action != "__nonzero__") : if self._action == "showPage" : self._parent._PyWrite("\n 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 self._parent._contextlevel += 1 elif self._action == "restoreState" : self._parent._contextlevel -= 1 self._parent._PyWrite("\n elif self._action == "beginForm" : self._parent._formnumber += 1 self._parent._PyWrite("\n elif self._action == "endForm" : self._parent._PyWrite("\n elif self._action == "save" : self._parent._PyWrite("\n 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 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 : _in -= 1 return 1
def _precomment(self) : """Outputs comments before the method call.""" if self._action == "showPage" : self._parent._PyWrite("\n 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 self._parent._contextlevel += 1 elif self._action == "restoreState" : self._parent._contextlevel -= 1 self._parent._PyWrite("\n elif self._action == "beginForm" : self._parent._formnumber += 1 self._parent._PyWrite("\n elif self._action == "endForm" : self._parent._PyWrite("\n elif self._action == "save" : self._parent._PyWrite("\n def _postcomment(self) : """Outputs comments after the method call.""" if self._action == "showPage" : self._parent._pagenumber += 1 self._parent._PyWrite("\n elif self._action == "endForm" : self._parent._PyWrite("")
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
self._PyWrite("
self._PyWrite(" def __nonzero__(self) : """This is needed by platypus' tables.""" return 1
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)))
scp = self._colpositions[sc] ecp = self._colpositions[ec+1] for rowpos in self._rowpositions[sr:er+1]:
scp = ecp[0] ecp = ecp[-1] for rowpos in rp:
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)
srp = self._rowpositions[sr] erp = self._rowpositions[er+1] for colpos in self._colpositions[sc:ec+1]:
srp = erp[0] erp = erp[-1] for colpos in cp:
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)
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
if sc < 0: sc = sc + ncols if ec < 0: ec = ec + ncols if sr < 0: sr = sr + nrows if er < 0: er = er + nrows
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)
x1 = self._colpositions[ec+1] y1 = self._rowpositions[er+1]
x1 = self._colpositions[min(ec+1,ncols)] y1 = self._rowpositions[min(er+1,nrows)]
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)
I = Image(os.path.join(os.path.dirname(reportlab.platypus.__file__),'..','demos','pythonpoint','leftlogo.gif'))
I = Image(os.path.join(os.path.dirname(reportlab.platypus.__file__),'..','tools','pythonpoint','demos','leftlogo.gif'))
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("""
self.init_graphics_state() self.state_stack = [] def init_graphics_state(self):
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)
dict["Mask"] = PDFArray(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)
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)
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 = [] while keepWithNext: collected.append(this) del flowables[0] if len(flowables) == 0: break else: this = flowables[0] keepWithNext = ((hasattr(this, 'keepWithNext') and this.keepTogether == 1) or (hasattr(this, 'style') and hasattr(this.style, 'keepWithNext') and this.style.keepWithNext == 1) ) if len(flowables) > 0: this = flowables[0] collected.append(this) del flowables[0] Keeper = KeepTogether(collected) Keeper._skipMeNextTime = 1 print 'gathered %d items into one KeepTogether' % len(collected) flowables.insert(0, Keeper)
i = 0 n = len(flowables) while i<n and flowables[i].getKeepWithNext(): i = i + 1 if i: i = i + 1 K = KeepTogether(flowables[:i]) for f in K._flowables: f.keepWithNext = 0 del flowables[:i] flowables.insert(0,K)
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 = []
if self.invariant: s = PDFString('constantconstant') self._ID = PDFArray([s,s]) else: digest = self.signature.digest() doc = DummyDoc() ID = PDFString(digest) IDs = ID.format(doc) self._ID = "%s %% ReportLab generated PDF document -- digest (http://www.reportlab.com) %s [%s %s] %s" % (
digest = self.signature.digest() doc = DummyDoc() ID = PDFString(digest) IDs = ID.format(doc) self._ID = "%s %% ReportLab generated PDF document -- digest (http://www.reportlab.com) %s [%s %s] %s" % (
def ID(self): "A unique fingerprint for the file (unless in invariant mode)" if self._ID: return self._ID if self.invariant: s = PDFString('constantconstant') self._ID = PDFArray([s,s]) else: digest = self.signature.digest() doc = DummyDoc() ID = PDFString(digest) IDs = ID.format(doc) self._ID = "%s %% ReportLab generated PDF document -- digest (http://www.reportlab.com) %s [%s %s] %s" % ( LINEEND, LINEEND, IDs, IDs, LINEEND) return self._ID
(tred, tgreen, tblue) = map(ord, PILImage.palette.data[transparency:transparency+3])
palette = PILImage.palette try: palette = palette.palette except: palette = palette.data (tred, tgreen, tblue) = map(ord, palette[transparency:transparency+3])
def _checkTransparency(self,PILImage): 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) else: self.mask = None elif hasattr(self.mask,'rgb'): self.mask = self.mask.rgb()+self.mask.rgb()
version="1.17",
version=get_version(),
def run(): LIBS = [] setup( name="Reportlab", version="1.17", licence="BSD license (see license.txt for details), Copyright (c) 2000-2003, ReportLab Inc.", description="The Reportlab Toolkit", long_description="""The ReportLab Toolkit.
cur_x = style.leftIndent
leftIndent = style.leftIndent cur_x = leftIndent
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."""
canvas.rect(style.leftIndent,
canvas.rect(leftIndent,
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."""
canvas.rect(0, 0, style.leftIndent, self.height)
canvas.rect(0, 0, leftIndent, self.height)
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."""
_do_under_lines(0, t_off, tx)
_do_under_lines(0, t_off+leftIndent, tx)
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."""
_do_under_lines(i, t_off, tx)
_do_under_lines(i, t_off+leftIndent, tx)
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."""
_do_under(0, t_off, tx)
_do_under(0, t_off+leftIndent, tx)
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."""