rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
_do_under(i, t_off, tx)
_do_under(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."""
img1 = PIL_Image.open(filename) img = img1.convert('RGB') imgwidth, imgheight = img.size code = [] code.append('BI') code.append('/W %s /H %s /BPC 8 /CS /RGB /F [/A85 /Fl]' % (imgwidth, imgheight)) code.append('ID') raw = img.tostring() assert(len(raw) == imgwidth * imgheight, "Wrong amount of data for image") compre...
cachedname = os.path.splitext(filename)[0] + '.a85' if filename==cachedname: if cachedImageExists(filename): if returnInMemory: return split(open(cachedname,'rb').read(),LINEEND)[:-1] else: raise IOError, 'No such cached image %s' % filename else: img1 = PIL_Image.open(filename) img = img1.convert('RGB') imgwidth, imgh...
def cacheImageFile(filename, returnInMemory=0): "Processes image as if for encoding, saves to a file with .a85 extension." from reportlab.lib.utils import PIL_Image import zlib img1 = PIL_Image.open(filename) img = img1.convert('RGB') imgwidth, imgheight = img.size code = [] code.append('BI') # begin image # this ...
code.append('EI') if returnInMemory: return code cachedname = os.path.splitext(filename)[0] + '.a85' f = open(cachedname,'wb') f.write(join(code, LINEEND)+LINEEND) f.close() if rl_config._verbose: print 'cached image as %s' % cachedname
while dataline <> "": code.append(dataline) dataline = outstream.read(60) code.append('EI') if returnInMemory: return code f = open(cachedname,'wb') f.write(join(code, LINEEND)+LINEEND) f.close() if rl_config._verbose: print 'cached image as %s' % cachedname
def cacheImageFile(filename, returnInMemory=0): "Processes image as if for encoding, saves to a file with .a85 extension." from reportlab.lib.utils import PIL_Image import zlib img1 = PIL_Image.open(filename) img = img1.convert('RGB') imgwidth, imgheight = img.size code = [] code.append('BI') # begin image # this ...
plains.append(frag.text)
if hasattr(frag, 'text'): plains.append(frag.text)
def getPlainText(self,identify=None): """Convenience function for templates which want access to the raw text, without XML tags. """ frags = getattr(self,'frags',None) if frags: plains = [] for frag in frags: plains.append(frag.text) return join(plains, '') elif identify: text = getattr(self,'text',None) if text is Non...
os.system("%s %s %s %s" % (sys.executable,pp,xml, quiet))
os.system(_quote(sys.executable,pp,xml, quiet))
def test1(self): "Test if pythonpoint.pdf can be created from pythonpoint.xml." import reportlab rlDir = os.path.dirname(reportlab.__file__) ppDir = os.path.join(rlDir, 'tools', 'pythonpoint') pdf = os.path.join(ppDir,'demos','pythonpoint.pdf') xml = os.path.join(ppDir,'demos','pythonpoint.xml') pp = os.path.join(ppDir...
os.system("%s %s %s" % (exe,xml, quiet))
print _quote(exe,xml,quiet) os.system(_quote(exe,xml,quiet))
def test1(self): "Test if pythonpoint.pdf can be created from pythonpoint.xml." import reportlab rlDir = os.path.dirname(reportlab.__file__) ppDir = os.path.join(rlDir, 'tools', 'pythonpoint') pdf = os.path.join(ppDir,'demos','pythonpoint.pdf') xml = os.path.join(ppDir,'demos','pythonpoint.xml') pp = os.path.join(ppDir...
intPart, fracPart = divmod(num, 1.0)
absNum = abs(num) if absNum == num: sign = 1 else: sign = -1 intPart, fracPart = divmod(absNum, 1.0)
def format(self, num): intPart, fracPart = divmod(num, 1.0) strInt = str(long(intPart)) if self.thousandSeparator is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.thousandSeparator + right + strNew strNew = right + strNew else: strNew = self.thousandSeparator ...
self._barWidth = self._length / self._catCount
self._barWidth = self._length / (self._catCount or 1)
def configure(self, multiSeries): self._catCount = len(multiSeries[0]) self._barWidth = self._length / self._catCount
self.linesep = os.linesep
self.linesep = '\n'
def __init__(self,stream): self.stream = stream if _isJPython: import java.lang.System self.linesep = java.lang.System.getProperty("line.separator") else: self.linesep = os.linesep
def copy(self): """Returns a deep copy""" obj = self.Drawing(self.width, self.height)
def _copy(self,obj): """copies to obj"""
def copy(self): """Returns a deep copy""" obj = self.Drawing(self.width, self.height) obj._attrMap = self._attrMap.clone()
image = PIL_Image.open(cStringIO.StringIO(logo.data))
image = PIL_Image.open(cStringIO.StringIO(str(logo.data)))
def getImageFromZODB(self, name) : """Retrieves an Image from the ZODB, converts it to PIL, and makes it 0.75 inch high. """ try : # try to get it from ZODB logo = getattr(self.parent.context, name) except AttributeError : # not found ! return None
if __name__=='__main__':
def test():
def drawToString(d,fmt='GIF', dpi=72, bg=0xfffffff, configPIL=None, showBoundary=rl_config.showBoundary): s = getStringIO() drawToFile(d,s,fmt=fmt, dpi=dpi, bg=bg, configPIL=configPIL) return s.getvalue()
def test(): import os from reportlab.graphics.testshapes import getAllTestDrawings drawings = [] if not os.path.isdir('pmout'): os.mkdir('pmout') htmlTop = """<html><head><title>renderPM output results</title></head> <body> <h1>renderPM results of output</h1> """ htmlBottom = """</body> </html> """ html = [htmlTop] ...
import os from reportlab.graphics.testshapes import getAllTestDrawings drawings = [] if not os.path.isdir('pmout'): os.mkdir('pmout') htmlTop = """<html><head><title>renderPM output results</title></head> <body> <h1>renderPM results of output</h1> """ htmlBottom = """</body> </html> """ html = [htmlTop] i = 0 for (dr...
def ext(x): if x=='tiff': x='tif' return x
html.append('<p>%s format</p>\n' % string.upper(k)) try: filename = 'renderPM%d.%s' % (i, ext(k)) fullpath = os.path.join('pmout', filename) if os.path.isfile(fullpath): os.remove(fullpath) drawToFile(drawing,fullpath,fmt=k) if k in ['gif','png','jpg','pct']: html.append('<img src="%s" border="1"><br>\n' % filename) pr...
html.append('<img src="%s" border="1"><br>\n' % filename) print 'wrote',fullpath except AttributeError: print 'Problem drawing %s file'%k raise i = i + 1 html.append(htmlBottom) htmlFileName = os.path.join('pmout', 'index.html') open(htmlFileName, 'w').writelines(html) print 'wrote %s' % htmlFileName if __name__=='__...
def test(): #grab all drawings from the test module and write out. #make a page of links in HTML to assist viewing. import os from reportlab.graphics.testshapes import getAllTestDrawings drawings = [] if not os.path.isdir('pmout'): os.mkdir('pmout') htmlTop = """<html><head><title>renderPM output results</title></head>...
lines = string.split(lines,'\r')
if lines: lines = string.split(lines[0],'\r')
def parseAFMFile(afmFileName): """Quick and dirty - gives back a top-level dictionary with top-level items, and a 'widths' key containing a dictionary of glyph names and widths. Just enough needed for embedding. A better parser would accept options for what data you wwanted, and preserve the order.""" lines = open_a...
if not os.path.isdir(dirname): continue
if not rl_isdir(dirname): continue
def bruteForceSearchForAFM(faceName): """Looks in all AFM files on path for face with given name. Returns AFM file name or None. Ouch!""" import glob from reportlab.rl_config import T1SearchPath for dirname in T1SearchPath: if not os.path.isdir(dirname): continue possibles = glob.glob(dirname + os.sep + '*.[aA][fF][...
if _rl_accel.version<'0.59': raise ValueError add32 = _rl_accel.add32 calcChecksum = _rl_accel.calcChecksum
add32 = _rl_accel.add32L calcChecksum = _rl_accel.calcChecksumL
def hex32(i): return '0X%8.8X' % (long(i)&0xFFFFFFFFL)
return ((x&0xFFFFFFFFL)+(y&0xFFFFFFFFL)) & 0xffffffffL
return (x+y) & 0xFFFFFFFFL
def add32(x, y): "Calculate (x + y) modulo 2**32" return ((x&0xFFFFFFFFL)+(y&0xFFFFFFFFL)) & 0xffffffffL
sum = 0 for n in unpack(">%dl" % (len(data)>>2), data): sum = add32(sum,n) return sum
return sum(unpack(">%dl" % (len(data)>>2), data)) & 0xFFFFFFFFL
def calcChecksum(data): """Calculates TTF-style checksums""" if len(data)&3: data = data + (4-(len(data)&3))*"\0" sum = 0 for n in unpack(">%dl" % (len(data)>>2), data): sum = add32(sum,n) return sum
or (type(uSymbol)==ClassType and issubclass(uSymbol,Widget))
or (type(x)==ClassType and issubclass(x,Widget))
def test(self,x): return callable(x) or isinstance(x,Marker) or isinstance(x,Flag) \ or (type(uSymbol)==ClassType and issubclass(uSymbol,Widget))
self._pos = self._pos + 4
self._pos += 4
def read_tag(self): "Read a 4-character tag" self._pos = self._pos + 4 return self._ttf_data[self._pos - 4:self._pos]
self._pos = self._pos + 2 return (ord(self._ttf_data[self._pos - 2]) << 8) + \ (ord(self._ttf_data[self._pos - 1]))
self._pos += 2 return unpack('>H',self._ttf_data[self._pos-2:self._pos])[0]
def read_ushort(self): "Reads an unsigned short" self._pos = self._pos + 2 return (ord(self._ttf_data[self._pos - 2]) << 8) + \ (ord(self._ttf_data[self._pos - 1]))
self._pos = self._pos + 4
self._pos += 4
def read_ulong(self): "Reads an unsigned long" self._pos = self._pos + 4 return unpack('>l',self._ttf_data[self._pos - 4:self._pos])[0]
us = self.read_ushort() if us >= 0x8000: return us - 0x10000 else: return us
self._pos += 2 return unpack('>h',self._ttf_data[self._pos-2:self._pos])[0]
def read_short(self): "Reads a signed short" us = self.read_ushort() if us >= 0x8000: return us - 0x10000 else: return us
return (ord(self._ttf_data[pos]) << 8) + \ (ord(self._ttf_data[pos + 1]))
return unpack('>H',self._ttf_data[pos:pos+2])[0]
def get_ushort(self, pos): "Return an unsigned short at given position" return (ord(self._ttf_data[pos]) << 8) + \ (ord(self._ttf_data[pos + 1]))
self.skip(11*2 + 10 + 4*4 + 4 + 3*2)
self.skip(58)
def extractInfo(self, charInfo=1): """Extract typographic information from the loaded font file.
self.skip(3*2 + 2*4 + 2)
self.skip(16)
def extractInfo(self, charInfo=1): """Extract typographic information from the loaded font file.
self.skip(2*2)
self.skip(4)
def extractInfo(self, charInfo=1): """Extract typographic information from the loaded font file.
if labels[0]==labels[1]:
if labels[0] and labels[0]==labels[1]:
def addTick(i, xVals=xVals, formatter=formatter, ticks=ticks, labels=labels): ticks.insert(0,xVals[i]) labels.insert(0,formatter(xVals[i]))
self.valueSteps = steps
self._tickValues = steps
def configure(self, data): self._convertXV(data) xVals = map(lambda dv: dv[0], data[0]) 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, label...
y1, y2, None = find_good_grid(y_min, y_max,grid=valueStep)
y1, y2, None = find_good_grid(y_min, y_max,n=n,grid=valueStep)
def _rangeAdjust(self): "Adjusts the value range of the axis."
T, L = ticks(self._valueMin, self._valueMax, split=1, percent=self.leftAxisPercent,grid=valueStep)
T, L = ticks(self._valueMin, self._valueMax, split=1, n=n, percent=self.leftAxisPercent,grid=valueStep)
def _rangeAdjust(self): "Adjusts the value range of the axis."
self.valueSteps = T
self._tickValues = self.valueSteps = T
def _rangeAdjust(self): "Adjusts the value range of the axis."
c.bookmarkPage("P2_XYZ",fitType="XYZ",top=7*inch,left=3*inch,zoom=2)
c.bookmarkPage("P2_XYZ",fit="XYZ",top=7*inch,left=3*inch,zoom=2)
def test1(self):
c.bookmarkPage("P2_FIT",fitType="Fit")
c.bookmarkPage("P2_FIT",fit="Fit")
def test1(self):
c.bookmarkPage("P2_FITH",fitType="FitH",top=2*inch)
c.bookmarkPage("P2_FITH",fit="FitH",top=2*inch)
def test1(self):
c.bookmarkPage("P2_FITV",fitType="FitV",left=10*inch)
c.bookmarkPage("P2_FITV",fit="FitV",left=10*inch)
def test1(self):
c.bookmarkPage("P2_FITR",fitType="FitR",left=1*inch,bottom=2*inch,right=5*inch,top=6*inch)
c.bookmarkPage("P2_FITR",fit="FitR",left=1*inch,bottom=2*inch,right=5*inch,top=6*inch)
def test1(self):
c.bookmarkPage("HYPER_1",fitType="XYZ",top=2.5*inch,bottom=2*inch)
c.bookmarkPage("HYPER_1",fit="XYZ",top=2.5*inch,bottom=2*inch)
def test1(self):
c.bookmarkPage("P3_XYZ",fitType="XYZ",top=7*inch,left=3*inch,zoom=0)
c.bookmarkPage("P3_XYZ",fit="XYZ",top=7*inch,left=3*inch,zoom=0)
def test1(self):
c.bookmarkPage("P3_FITV",fitType="FitV",left=10*inch)
c.bookmarkPage("P3_FITV",fit="FitV",left=10*inch)
def test1(self):
c.bookmarkPage("MOL",fitType="FitR",left=4*inch,top=7*inch,bottom=4*inch,right=6*inch)
c.bookmarkPage("MOL",fit="FitR",left=4*inch,top=7*inch,bottom=4*inch,right=6*inch)
def test1(self):
class SpiderChart(Widget): _attrMap = AttrMap( x = AttrMapValue(isNumber, desc='X position of the chart within its container.'), y = AttrMapValue(isNumber, desc='Y position of the chart within its container.'), width = AttrMapValue(isNumber, desc='width of spider bounding box. Need not be same as width.'), height = Att...
self.fontName = STATE_DEFAULTS["fontName"] self.fontSize = STATE_DEFAULTS["fontSize"] self.fontColor = STATE_DEFAULTS["fillColor"] self.labelRadius = 1.2 class SpiderChart(PlotArea): _attrMap = AttrMap(BASE=PlotArea,
def __init__(self): self.strokeWidth = 0 self.fillColor = None self.strokeColor = STATE_DEFAULTS["strokeColor"] self.strokeDashArray = STATE_DEFAULTS["strokeDashArray"]
self.x = 0 self.y = 0 self.width = 100 self.height = 100
PlotArea.__init__(self)
def __init__(self): self.x = 0 self.y = 0 self.width = 100 self.height = 100 self.data = [[10,12,14,16,14,12], [6,8,10,12,9,11]] self.labels = None # or list of strings self.startAngle = 90 self.direction = "clockwise"
g = Group() g.add(Rect(self.x, self.y, self.width, self.height, strokeColor=colors.red, fillColor=None))
g = self.makeBackground() or Group()
def draw(self): # normalize slice data g = Group()
print '%d slices each of %0.2f radians here: %s' % (n, angleBetween, repr(angles))
def draw(self): # normalize slice data g = Group()
print 'added spoke (%0.2f, %0.2f) -> (%0.2f, %0.2f)' % (spoke.x1, spoke.y1, spoke.x2, spoke.y2)
def draw(self): # normalize slice data g = Group()
pc.data = [[10,12,14,16,14,12], [6,8,10,12,9,11]]
pc.data = [[10,12,14,16,14,12], [6,8,10,12,9,15],[7,8,17,4,12,8,3]]
def sample1(): "Make a simple spider chart" d = Drawing(400, 400) pc = SpiderChart() pc.x = 50 pc.y = 50 pc.width = 300 pc.height = 300 pc.data = [[10,12,14,16,14,12], [6,8,10,12,9,11]] pc.labels = ['a','b','c','d','e','f'] d.add(pc) return d
pc.strands[2].fillColor=colors.palegreen
def sample1(): "Make a simple spider chart" d = Drawing(400, 400) pc = SpiderChart() pc.x = 50 pc.y = 50 pc.width = 300 pc.height = 300 pc.data = [[10,12,14,16,14,12], [6,8,10,12,9,11]] pc.labels = ['a','b','c','d','e','f'] d.add(pc) return d
print 'saved spider.pdf'
def sample1(): "Make a simple spider chart" d = Drawing(400, 400) pc = SpiderChart() pc.x = 50 pc.y = 50 pc.width = 300 pc.height = 300 pc.data = [[10,12,14,16,14,12], [6,8,10,12,9,11]] pc.labels = ['a','b','c','d','e','f'] d.add(pc) return d
def run(verbose=1, outDir=None):
def run(verbose=None, outDir=None):
def run(verbose=1, outDir=None): import os, sys, shutil from reportlab.tools.docco import yaml2pdf from reportlab.lib.utils import _RL_DIR yaml2pdf.run('reference.yml','reference.pdf') if verbose: print 'Saved reference.pdf' docdir = os.path.join(_RL_DIR,'docs') if outDir: docDir = outDir destfn = docdir + os.sep + 're...
run(verbose=('-s' not in sys.argv))
run()
def makeSuite(): "standard test harness support - run self as separate process" from reportlab.test.utils import ScriptThatMakesFileTest return ScriptThatMakesFileTest('../docs/reference', 'genreference.py', 'reference.pdf')
elif frag.sub:
elif frag.super:
def handle_data(self,data): "Creates an intermediate representation of string segments."
frag.fontSize = min(frag.fontSize-sizeDelta,3)
frag.fontSize = max(frag.fontSize-sizeDelta,3)
def handle_data(self,data): "Creates an intermediate representation of string segments."
of Jove, from whatsoever source you may know them.
of Jove, from whatsoever source you<super>1</super> may know them.
def parse(self, text, style): """Given a formatted string will return a list of ParaFrag objects with their calculated widths. If errors occur None will be returned and the self.errors holds a list of the error messages. """
print l.fontName,l.fontSize,l.textColor,l.bold, l.text[:25]
print l.fontName,l.fontSize,l.textColor,l.bold, l.rise, l.text[:25]
def parse(self, text, style): """Given a formatted string will return a list of ParaFrag objects with their calculated widths. If errors occur None will be returned and the self.errors holds a list of the error messages. """
if availableHeight<=needatleast:
if availableHeight < needatleast:
def wrap(self, availableWidth, availableHeight): if debug: print "WRAPPING", id(self), availableWidth, availableHeight print " ", self.formattedProgram print " ", self.program self.availableHeight = availableHeight self.myengine = p = paragraphEngine() p.baseindent = self.baseindent # for shifting bullets as needed...
print 'usage: aml.py source.txt'
print 'usage: yaml.py source.txt'
def getClassDoc(self, modulename, classname, pathname=None): """Documents the class and its public methods""" docco = codegrab.getObjectsDefinedIn(modulename, pathname) found = 0 for cls in docco.classes: if cls.name == classname: found = 1 self._results.append(('Preformatted','FunctionHeader', 'Class %s:' % cls.name))...
self._code.append('[%s %s] 0 d' % (array, phase))
self._code.append('[%s] %s d' % (array, phase))
def setDash(self, array=[], phase=0): """Two notations. pass two numbers, or an array and phase""" if type(array) == IntType or type(array) == FloatType: self._code.append('[%s %s] 0 d' % (array, phase)) elif type(array) == ListType or type(array) == TupleType: assert phase >= 0, "phase is a length in user space" text...
textarray = join(map(str, array))
textarray = ' '.join(map(str, array))
def setDash(self, array=[], phase=0): """Two notations. pass two numbers, or an array and phase""" if type(array) == IntType or type(array) == FloatType: self._code.append('[%s %s] 0 d' % (array, phase)) elif type(array) == ListType or type(array) == TupleType: assert phase >= 0, "phase is a length in user space" text...
f=lambda T,x=x,special=special: special(T,x,func)
f=lambda T,x=x,special=special,func=func: special(T,x,func)
def _findMinMaxValue(V, x, default, func, special=None): if type(V[0][0]) in (TupleType,ListType): if special: f=lambda T,x=x,special=special: special(T,x,func) else: f=lambda T,x=x: T[x] V=map(lambda e,f=f: map(f,e),V) V = filter(len,map(lambda x: filter(lambda x: x is not None,x),V)) if len(V)==0: return default retu...
from widgets import (BarcodeI2of5, BarcodeCode128, BarcodeStandard93, BarcodeExtended93, BarcodeStandard39, BarcodeExtended39, BarcodeMSI, BarcodeCodabar, BarcodeCode11, BarcodeFIM, BarcodePOSTNET, BarcodeUSPS_4State)
from widgets import BarcodeI2of5, BarcodeCode128, BarcodeStandard93,\ BarcodeExtended93, BarcodeStandard39, BarcodeExtended39,\ BarcodeMSI, BarcodeCodabar, BarcodeCode11, BarcodeFIM,\ BarcodePOSTNET, BarcodeUSPS_4State
def getCodes(): """Returns a dict mapping code names to widgets""" from widgets import (BarcodeI2of5, BarcodeCode128, BarcodeStandard93, BarcodeExtended93, BarcodeStandard39, BarcodeExtended39, BarcodeMSI, BarcodeCodabar, BarcodeCode11, BarcodeFIM, BarcodePOSTNET, BarcodeUSPS_4State) #newer codes will typically get t...
if self._code[-1][-3:]==' cm':
if len(self._code) and self._code[-1][-3:]==' cm':
def transform(self, a,b,c,d,e,f): """adjoin a mathematical transform to the current graphics state matrix. Not recommended for beginners.""" #"""How can Python track this?""" #a0,b0,c0,d0,e0,f0 = self._currentMatrix #self._currentMatrix = (a0*a+c0*b, b0*a+d0*b, # a0*c+c0*d, b0*c+d0*d, # ...
self.code.append('%'+msg)
if self.comments: self.code.append('%'+msg)
def comment(self,msg): self.code.append('%'+msg)
lc.lines.symbol = makeFilledDiamond
lc.lines.symbol = makeMarker('FilledDiamond')
def sample1(): drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (5, 20, 46, 38, 23, 21, 6, 14) ] lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 125 lc.width = 300 lc.data = data lc.joinedLines = 1 lc.lines.symbol = makeFilledDiamond lc.lineLabelFormat = '%2.0f' catNames = string.spli...
lc.lines.symbol = makeFilledDiamond
lc.lines.symbol = makeMarker('FilledDiamond')
def sample1a(): drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (5, 20, 46, 38, 23, 21, 6, 14) ] lc = SampleHorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 125 lc.width = 300 lc.data = data lc.joinedLines = 1 lc.strokeColor = colors.white lc.fillColor = colors.HexColor(0xCCCCCC) lc.lines.s...
lc.lines.symbol = makeSmiley lc.lines.symbol = Marker() lc.lines.symbol.kind = 'Smiley'
lc.lines.symbol = makeMarker('Smiley')
def sample2(): drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (5, 20, 46, 38, 23, 21, 6, 14) ] lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 125 lc.width = 300 lc.data = data lc.joinedLines = 1 lc.lines.symbol = makeSmiley lc.lines.symbol = Marker() lc.lines.symbol.kind = 'Smiley' ...
outline = self.outline outline.prepare(self, canvas)
def SaveToFile(self, filename, canvas): from types import StringType # prepare outline outline = self.outline outline.prepare(self, canvas) if type(filename) is StringType: myfile = 1 f = open(filename, "wb") else: myfile = 0 f = filename # IT BETTER BE A FILE-LIKE OBJECT! txt = self.format() f.write(txt) if myfile: f....
if next >= end:
if inc > 0 and next >= end: break elif inc < 0 and next <= end:
def frange(start, end=None, inc=None): "A range function, that does accept float increments..." if end == None: end = start + 0.0 start = 0.0 if inc == None: inc = 1.0 L = [] while 1: next = start + len(L) * inc if next >= end: break L.append(next) return L
FT_INC_DIR = ['/usr/local/include/freetype2']
FT_INC_DIR = ['/usr/local/include','/usr/local/include/freetype2']
def main(): cwd = os.getcwd() os.chdir(os.path.dirname(os.path.abspath(sys.argv[0]))) MACROS=[('ROBIN_DEBUG',None)] MACROS=[] from glob import glob from distutils.core import setup, Extension pJoin=os.path.join LIBART_VERSION = libart_version() SOURCES=['_renderPM.c'] DEVEL_DIR=os.curdir LIBART_DIR=pJoin(DEVEL_DIR,'li...
(file, pathname, description) = imp.find_module(name, parentModule.__path__)
(file, pathname, description) = imp.find_module(name, parentModule.__file__)
def recursiveImport(modulename, baseDir=None, noCWD=0): """Dynamically imports possible packagized module, or raises ImportError""" import imp parts = string.split(modulename, '.') part = parts[0] path = list(baseDir and (type(baseDir) not in SeqTypes and [baseDir] or filter(None,baseDir)) or None) if not noCWD and '.'...
"""Draws a string right-aligned with the y coordinate. I
"""Draws a string right-aligned with the x coordinate. I
def drawCentredString(self, x, y, text): """Draws a string right-aligned with the y coordinate. I am British so the spelling is correct, OK?""" width = self.stringWidth(text, self._fontname, self._fontsize) t = self.beginText(x - 0.5*width, y) t.textLine(text) self.drawText(t)
self.width = 200 self.height = 100
self.x = 20 self.y = 10 self.height = 85 self.width = 180
def __init__(self): self.debug = 0
data = map(lambda x: map(lambda x: x is not None and x or 0,x), self.data) return min(min(data)), max(max(data))
D = [] for d in self.data: for e in d: if e is None: e = 0 D.append(e) return min(D), max(D)
def _findMinMaxValues(self): "Find the minimum and maximum value of the data we have." data = map(lambda x: map(lambda x: x is not None and x or 0,x), self.data) return min(min(data)), max(max(data))
data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ]
def demo(self): """Shows basic use of a bar chart"""
bc.x = 20 bc.y = 10 bc.height = 85 bc.width = 180 bc.data = data
def demo(self): """Shows basic use of a bar chart"""
if hasattr(self,saveLogger):
if hasattr(self,'saveLogger'):
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')) chartId = getattr(self,'chartId',0) if callable(fnRoot): fnRoot =...
print >>sys.stderr, '\n
sys.stderr.write('\n
def makeSuite(folder, exclude=[],nonImportable=[]): "Build a test suite of all available test files." allTests = unittest.TestSuite() sys.path.insert(0, folder) for filename in GlobDirectoryWalker(folder, 'test_*.py'): modname = os.path.splitext(os.path.basename(filename))[0] if modname not in exclude: try: module = ...
def _listCellGeom(V,w,s,W=None):
def _listCellGeom(V,w,s,W=None,H=None):
def _listCellGeom(V,w,s,W=None): aW = w-s.leftPadding-s.rightPadding t = 0 w = 0 for v in V: vw, vh = v.wrap(aW, 72000) if W is not None: W.append(vw) w = max(w,vw) t = t + vh + v.getSpaceBefore()+v.getSpaceAfter() return w, t - V[0].getSpaceBefore()-V[-1].getSpaceAfter()
if t in _SeqTypes:
if t in _SeqTypes or isinstance(v,Flowable): if not t in _SeqTypes: v = (v,)
def _calc(self): if hasattr(self,'_width'): return
if t is not _stringtype: v = str(v)
if t is not StringType: v = v is None and '' or str(v)
def _calc(self): if hasattr(self,'_width'): return
t = s.leading*len(v)+s.bottomPadding+s.topPadding
t = s.leading*len(v) t = t+s.bottomPadding+s.topPadding
def _calc(self): if hasattr(self,'_width'): return
if t in _SeqTypes:
if t in _SeqTypes or isinstance(v,Flowable):
def _calc(self): if hasattr(self,'_width'): return
elif t is not _stringtype: v = str(v)
elif t is not StringType: v = v is None and '' or str(v)
def _calc(self): if hasattr(self,'_width'): return
if sr<(n-1) and er>=n:
if sr<n and er>=(n-1):
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 n in _SeqTypes:
if n in _SeqTypes or isinstance(cellval,Flowable): if not n in _SeqTypes: cellval = (cellval,)
def _drawCell(self, cellval, cellstyle, (colpos, rowpos), (colwidth, rowheight)): if self._curcellstyle is not cellstyle: cur = self._curcellstyle if cur is None or cellstyle.color != cur.color: self.canv.setFillColor(cellstyle.color) if cur is None or cellstyle.leading != cur.leading or cellstyle.fontname != cur.fontn...
if valign != 'BOTTOM' or just != 'LEFT': W = [] w, h = _listCellGeom(cellval,colwidth,cellstyle,W=W)
W = [] H = [] w, h = _listCellGeom(cellval,colwidth,cellstyle,W=W, H=H) if valign=='TOP': y = rowpos + rowheight - cellstyle.topPadding elif valign=='BOTTOM': y = rowpos+cellstyle.bottomPadding + h
def _drawCell(self, cellval, cellstyle, (colpos, rowpos), (colwidth, rowheight)): if self._curcellstyle is not cellstyle: cur = self._curcellstyle if cur is None or cellstyle.color != cur.color: self.canv.setFillColor(cellstyle.color) if cur is None or cellstyle.leading != cur.leading or cellstyle.fontname != cur.fontn...
W = len(cellval)*[0] if valign=='TOP': y = rowpos + rowheight - cellstyle.topPadding+h elif valign=='BOTTOM': y = rowpos+cellstyle.bottomPadding else: y = rowpos+(rowheight+cellstyle.bottomPadding-cellstyle.topPadding-h)/2.0
y = rowpos+(rowheight+cellstyle.bottomPadding-cellstyle.topPadding+h)/2.0
def _drawCell(self, cellval, cellstyle, (colpos, rowpos), (colwidth, rowheight)): if self._curcellstyle is not cellstyle: cur = self._curcellstyle if cur is None or cellstyle.color != cur.color: self.canv.setFillColor(cellstyle.color) if cur is None or cellstyle.leading != cur.leading or cellstyle.fontname != cur.fontn...
for v, w in map(None,cellval,W):
for v, w, h in map(None,cellval,W,H):
def _drawCell(self, cellval, cellstyle, (colpos, rowpos), (colwidth, rowheight)): if self._curcellstyle is not cellstyle: cur = self._curcellstyle if cur is None or cellstyle.color != cur.color: self.canv.setFillColor(cellstyle.color) if cur is None or cellstyle.leading != cur.leading or cellstyle.fontname != cur.fontn...
else: x = colpos+(colwidth+cellstyle.leftPadding-cellstyle.rightPadding-w)/2.0
elif just in ('CENTRE', 'CENTER'): x = colpos+(colwidth+cellstyle.leftPadding-cellstyle.rightPadding-w)/2.0 else: raise ValueError, 'Invalid justification %s' % just
def _drawCell(self, cellval, cellstyle, (colpos, rowpos), (colwidth, rowheight)): if self._curcellstyle is not cellstyle: cur = self._curcellstyle if cur is None or cellstyle.color != cur.color: self.canv.setFillColor(cellstyle.color) if cur is None or cellstyle.leading != cur.leading or cellstyle.fontname != cur.fontn...
if n is _stringtype: val = cellval
if n is StringType: val = cellval
def _drawCell(self, cellval, cellstyle, (colpos, rowpos), (colwidth, rowheight)): if self._curcellstyle is not cellstyle: cur = self._curcellstyle if cur is None or cellstyle.color != cur.color: self.canv.setFillColor(cellstyle.color) if cur is None or cellstyle.leading != cur.leading or cellstyle.fontname != cur.fontn...
t=Table(data,style=[('GRID',(1,1),(-2,-2),1,colors.green),
t=Table(data,style=[ ('GRID',(0,0),(-1,-1),0.5,colors.grey), ('GRID',(1,1),(-2,-2),1,colors.green),
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,...
data= [['A', 'B', 'C', (Paragraph("<b>A paragraph</b>",styleSheet["BodyText"]),), 'D'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'],
import os, reportlab.platypus I = Image(os.path.join(os.path.dirname(reportlab.platypus.__file__),'..','demos','pythonpoint','leftlogo.gif')) I.drawHeight = 1.25*inch*I.drawHeight / I.drawWidth I.drawWidth = 1.25*inch I.noImageCaching = 1 P = Paragraph("<para align=center spaceb=3>The <b>ReportLab Left <font color=red>...
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,...
if f.style.name[:8] == 'Heading0':
if name7 == 'Heading' and not hasattr(self.canv, 'headerLine'): self.canv.headerLine = [] if name8 == 'Heading0':
def afterFlowable(self, flowable): "Takes care of header line, TOC and outline entries." if flowable.__class__.__name__ == 'Paragraph': f = flowable
elif f.style.name[:8] == 'Heading1':
elif name8 == 'Heading1':
def afterFlowable(self, flowable): "Takes care of header line, TOC and outline entries." if flowable.__class__.__name__ == 'Paragraph': f = flowable
elif f.style.name[:8] == 'Heading2':
elif name8 == 'Heading2':
def afterFlowable(self, flowable): "Takes care of header line, TOC and outline entries." if flowable.__class__.__name__ == 'Paragraph': f = flowable
if f.style.name[:7] == 'Heading':
if name7 == 'Heading':
def afterFlowable(self, flowable): "Takes care of header line, TOC and outline entries." if flowable.__class__.__name__ == 'Paragraph': f = flowable
lev = int(f.style.name[7:])
def afterFlowable(self, flowable): "Takes care of header line, TOC and outline entries." if flowable.__class__.__name__ == 'Paragraph': f = flowable
if lev == 0:
if headLevel == 0:
def afterFlowable(self, flowable): "Takes care of header line, TOC and outline entries." if flowable.__class__.__name__ == 'Paragraph': f = flowable
c.addOutlineEntry(title, key, level=lev,
c.addOutlineEntry(title, key, level=headLevel,
def afterFlowable(self, flowable): "Takes care of header line, TOC and outline entries." if flowable.__class__.__name__ == 'Paragraph': f = flowable