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") compressed = zlib.compress(raw) encoded = _AsciiBase85Encode(compressed) outstream = cStringIO.StringIO(encoded) dataline = outstream.read(60) while dataline <> "": code.append(dataline)
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, 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") compressed = zlib.compress(raw) encoded = _AsciiBase85Encode(compressed) outstream = cStringIO.StringIO(encoded)
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 describes what is in the image itself code.append('/W %s /H %s /BPC 8 /CS /RGB /F [/A85 /Fl]' % (imgwidth, imgheight)) code.append('ID') #use a flate filter and Ascii Base 85 raw = img.tostring() assert(len(raw) == imgwidth * imgheight, "Wrong amount of data for image") compressed = zlib.compress(raw) #this bit is very fast... encoded = _AsciiBase85Encode(compressed) #...sadly this isn't #write in blocks of 60 characters per line outstream = cStringIO.StringIO(encoded) dataline = outstream.read(60) while dataline <> "": code.append(dataline) dataline = outstream.read(60) code.append('EI') if returnInMemory: return code #save it to a file 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
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 describes what is in the image itself code.append('/W %s /H %s /BPC 8 /CS /RGB /F [/A85 /Fl]' % (imgwidth, imgheight)) code.append('ID') #use a flate filter and Ascii Base 85 raw = img.tostring() assert(len(raw) == imgwidth * imgheight, "Wrong amount of data for image") compressed = zlib.compress(raw) #this bit is very fast... encoded = _AsciiBase85Encode(compressed) #...sadly this isn't #write in blocks of 60 characters per line outstream = cStringIO.StringIO(encoded) dataline = outstream.read(60) while dataline <> "": code.append(dataline) dataline = outstream.read(60) code.append('EI') if returnInMemory: return code #save it to a file 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
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 None: text = repr(self) return text else: return ''
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,'pythonpoint.py') exe = os.path.abspath(os.path.join(rlDir,'..','pythonpoint.exe'))
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,'pythonpoint.py') exe = os.path.abspath(os.path.join(rlDir,'..','pythonpoint.exe'))
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 + right + strNew strInt = left strInt = strNew pattern = '%0.' + str(self.decimalPlaces) + 'f' strFrac = (pattern % fracPart)[2:] strBody = strInt + self.decimalSeparator + strFrac if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody
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] i = 0 for (drawing, docstring, name) in getAllTestDrawings(): if 1 or i==10: w = int(drawing.width) h = int(drawing.height) html.append('<hr><h2>Drawing %s %d</h2>\n<pre>%s</pre>' % (name, i, docstring)) for k in ['gif','tiff', 'png', 'jpg', 'pct']:
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 (drawing, docstring, name) in getAllTestDrawings(): if 1 or i==10: w = int(drawing.width) h = int(drawing.height) html.append('<hr><h2>Drawing %s %d</h2>\n<pre>%s</pre>' % (name, i, docstring)) for k in ['gif','tiff', 'png', 'jpg', 'pct']: if k in ['gif','png','jpg','pct']: 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)
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) 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
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__=='__main__':
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> <body> <h1>renderPM results of output</h1> """ htmlBottom = """</body> </html> """ html = [htmlTop]
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_and_readlines(afmFileName, 'r') if len(lines)<=1: #likely to be a MAC file lines = string.split(lines,'\r') if len(lines)<=1: raise ValueError, 'AFM file %s hasn\'t enough data' % afmFileName topLevel = {} glyphLevel = [] lines = map(string.strip, lines) #pass 1 - get the widths inMetrics = 0 # os 'TOP', or 'CHARMETRICS' for line in lines: if line[0:16] == 'StartCharMetrics': inMetrics = 1 elif line[0:14] == 'EndCharMetrics': inMetrics = 0 elif inMetrics: chunks = string.split(line, ';') chunks = map(string.strip, chunks) cidChunk, widthChunk, nameChunk = chunks[0:3] # character ID l, r = string.split(cidChunk) assert l == 'C', 'bad line in font file %s' % line cid = string.atoi(r) # width l, r = string.split(widthChunk) assert l == 'WX', 'bad line in font file %s' % line width = string.atoi(r) # name l, r = string.split(nameChunk) assert l == 'N', 'bad line in font file %s' % line name = r glyphLevel.append((cid, width, name)) # pass 2 font info inHeader = 0 for line in lines: if line[0:16] == 'StartFontMetrics': inHeader = 1 if line[0:16] == 'StartCharMetrics': inHeader = 0 elif inHeader: if line[0:7] == 'Comment': pass try: left, right = string.split(line,' ',1) except: raise ValueError, "Header information error in afm %s: line='%s'" % (afmFileName, line) try: right = string.atoi(right) except: pass topLevel[left] = right return (topLevel, glyphLevel)
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][mM]') for possible in possibles: (topDict, glyphDict) = parseAFMFile(possible) if topDict['FontName'] == faceName: return possible return None
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, labels = self._xAxisTicker(xVals) valueMin, valueMax = self.valueMin, self.valueMax if valueMin is None: valueMin = xVals[0] if valueMax is None: valueMax = xVals[-1] self._valueMin, self._valueMax = valueMin, valueMax self.valueSteps = steps self.labelTextFormat = labels
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 = AttrMapValue(isNumber, desc='height of spider bounding box. Need not be same as height.'),
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 + 'reference.pdf' shutil.copyfile('reference.pdf', destfn) if verbose: print 'copied to %s' % destfn
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 parsedText = self.parsedText formattedProgram = self.formattedProgram state = self.state if state: leading = state["leading"] else: leading = self.style1.leading program = self.program self.cansplit = 1 # until proven otherwise if state: p.resetState(state) p.x = 0 p.y = 0 needatleast = state["leading"] else: needatleast = self.style1.leading if availableHeight<=needatleast: self.cansplit = 0 #if debug: # print "CANNOT COMPILE, NEED AT LEAST", needatleast, 'AVAILABLE', availableHeight return (availableHeight+1, availableWidth) # cannot split if parsedText is None and program is None: raise ValueError, "need parsedText for formatting" if not program: self.program = program = self.compileProgram(parsedText) if not self.formattedProgram: (formattedProgram, remainder, \ laststate, heightused) = p.format(availableWidth, availableHeight, program, leading) self.formattedProgram = formattedProgram self.height = heightused self.laststate = laststate self.remainderProgram = remainder else: heightused = self.height remainder = None # too big if there is a remainder if remainder: # lie about the height: it must be split anyway #if debug: # print "I need to split", self.formattedProgram # print "heightused", heightused, "available", availableHeight, "remainder", len(remainder) height = availableHeight + 1 #print "laststate is", laststate #print "saving remainder", remainder self.remainder = Para(self.style1, parsedText=None, bulletText=None, \ state=laststate, context=self.context) self.remainder.program = remainder self.remainder.spaceAfter = self.spaceAfter self.spaceAfter = 0 else: self.remainder = None # no extra height = heightused if height>availableHeight: height = availableHeight-0.1 #if debug: # print "giving height", height, "of", availableHeight, self.parsedText result = (availableWidth, height) if debug: (w, h) = result if abs(availableHeight-h)<0.2: print "exact match???" + repr(availableHeight, h) print "wrap is", (availableWidth, availableHeight), result return result
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._results.append(('Preformatted','DocString', cls.doc)) for mth in cls.methods: if mth.status == 'official': self._results.append(('Preformatted','FunctionHeader', mth.proto)) self._results.append(('Preformatted','DocStringIndent', mth.doc)) break assert found, 'No Classes Defined in ' + modulename
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" textarray = join(map(str, array)) self._code.append('[%s] %s d' % (textarray, phase))
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" textarray = join(map(str, array)) self._code.append('[%s] %s d' % (textarray, phase))
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 return func(map(func,V))
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 their own module from eanbc import Ean13BarcodeWidget, Ean8BarcodeWidget #the module exports a dictionary of names to widgets, to make it easy for #apps and doc tools to display information about them. codes = {} for widget in ( BarcodeI2of5, BarcodeCode128, BarcodeStandard93, BarcodeExtended93, BarcodeStandard39, BarcodeExtended39, BarcodeMSI, BarcodeCodabar, BarcodeCode11, BarcodeFIM, BarcodePOSTNET, BarcodeUSPS_4State, Ean13BarcodeWidget, Ean8BarcodeWidget, ): codeName = widget.codeName codes[codeName] = widget return codes
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, # a0*e+c0*f+e0, b0*e+d0*f+f0) if self._code[-1][-3:]==' cm': L = string.split(self._code[-1]) a0, b0, c0, d0, e0, f0 = map(float,L[-7:-1]) s = len(L)>7 and string.join(L)+ ' %s cm' or '%s cm' self._code[-1] = s % fp_str(a0*a+c0*b,b0*a+d0*b,a0*c+c0*d,b0*c+d0*d,a0*e+c0*f+e0,b0*e+d0*f+f0) else: self._code.append('%s cm' % fp_str(a,b,c,d,e,f))
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.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 drawing.add(lc) return drawing
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.symbol = makeFilledDiamond lc.lineLabelFormat = '%2.0f' catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 drawing.add(lc) return drawing
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' lc.lineLabelFormat = '%2.0f' lc.strokeColor = colors.black lc.fillColor = colors.lightblue catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 drawing.add(lc) return drawing
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.close() markfilename(filename) # do platform specific file junk
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,'libart_lgpl') LIBART_SRCS=glob(pJoin(LIBART_DIR, 'art_*.c')) GT1_DIR=pJoin(DEVEL_DIR,'gt1') GLIB_DIR=pJoin(DEVEL_DIR,'glib') platform = sys.platform if platform in ['darwin', 'win32', 'sunos5', 'freebsd4', 'freebsd6', 'mac', 'linux2','linux-i386','aix4']: LIBS=[] else: raise ValueError, "Don't know about platform", platform if os.path.isdir('/usr/local/include/freetype2'): FT_LIB = ['freetype'] FT_LIB_DIR = ['/usr/local/lib'] FT_MACROS = [('RENDERPM_FT',None)] FT_INC_DIR = ['/usr/local/include/freetype2'] else: ft_lib = check_ft_lib() if ft_lib: FT_LIB = [os.path.splitext(os.path.basename(ft_lib))[0]] FT_LIB_DIR = [os.path.dirname(ft_lib)] FT_MACROS = [('RENDERPM_FT',None)] FT_INC_DIR = [FT_INCLUDE or os.path.join(os.path.dirname(os.path.dirname(ft_lib)),'include')] else: FT_LIB = [] FT_LIB_DIR = [] FT_MACROS = [] FT_INC_DIR = [] setup( name = "_renderPM", version = VERSION, description = "Python low level render interface", author = "Robin Becker", author_email = "[email protected]", url = "http://www.reportlab.com", packages = [], libraries=[('_renderPM_libart', { 'sources': LIBART_SRCS, 'include_dirs': [DEVEL_DIR,LIBART_DIR,], 'macros': [('LIBART_COMPILATION',None),]+BIGENDIAN('WORDS_BIGENDIAN')+MACROS, #'extra_compile_args':['/Z7'], } ), ('_renderPM_gt1', { 'sources': pfxJoin(GT1_DIR,'gt1-dict.c','gt1-namecontext.c','gt1-parset1.c','gt1-region.c','parseAFM.c'), 'include_dirs': [DEVEL_DIR,GT1_DIR,GLIB_DIR,], 'macros': MACROS, #'extra_compile_args':['/Z7'], } ), ], ext_modules = [Extension( '_renderPM', SOURCES, include_dirs=[DEVEL_DIR,LIBART_DIR,GT1_DIR]+FT_INC_DIR, define_macros=FT_MACROS+[('LIBART_COMPILATION',None)]+MACROS+[('LIBART_VERSION',LIBART_VERSION)], library_dirs=[]+FT_LIB_DIR, # libraries to link against libraries=LIBS+FT_LIB, #extra_objects=['gt1.lib','libart.lib',], #extra_compile_args=['/Z7'], extra_link_args=[] ), ], ) if sys.hexversion<0x2030000 and sys.platform=='win32' and ('install' in sys.argv or 'install_ext' in sys.argv): 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: srcf = os.path.join(src,f) if not os.path.isfile(srcf): continue dstf = os.path.join(dst,f) if os.path.isfile(dstf): os.remove(dstf) os.rename(srcf,dstf) MovePYDs('_renderPM.pyd','_renderPM.pdb')
(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 '.' not in path: path.insert(0,'.') #make import errors a bit more informative try: (file, pathname, description) = imp.find_module(part, path) childModule = parentModule = imp.load_module(part, file, pathname, description) for name in parts[1:]: (file, pathname, description) = imp.find_module(name, parentModule.__path__) childModule = imp.load_module(name, file, pathname, description) setattr(parentModule, name, childModule) parentModule = childModule except ImportError: msg = "cannot import '%s' while attempting recursive import of '%s'" % (part, modulename) if baseDir: msg = msg + " under paths '%s'" % `path` raise ImportError, msg return childModule
"""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 = fnRoot(chartId) else: try: fnRoot = fnRoot % getattr(self,'chartId',0) except TypeError, err: if str(err) != 'not all arguments converted': raise
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 = __import__(modname) allTests.addTest(module.makeSuite()) except: tt, tv, tb = sys.exc_info()[:] nonImportable.append((filename,traceback.format_exception(tt,tv,tb))) del tt,tv,tb del sys.path[0] return allTests
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.fontname or cellstyle.fontsize != cur.fontsize: self.canv.setFont(cellstyle.fontname, cellstyle.fontsize, cellstyle.leading) self._curcellstyle = cellstyle
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.fontname or cellstyle.fontsize != cur.fontsize: self.canv.setFont(cellstyle.fontname, cellstyle.fontsize, cellstyle.leading) self._curcellstyle = cellstyle
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.fontname or cellstyle.fontsize != cur.fontsize: self.canv.setFont(cellstyle.fontname, cellstyle.fontsize, cellstyle.leading) self._curcellstyle = cellstyle
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.fontname or cellstyle.fontsize != cur.fontsize: self.canv.setFont(cellstyle.fontname, cellstyle.fontsize, cellstyle.leading) self._curcellstyle = cellstyle
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.fontname or cellstyle.fontsize != cur.fontsize: self.canv.setFont(cellstyle.fontname, cellstyle.fontsize, cellstyle.leading) self._curcellstyle = cellstyle
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.fontname or cellstyle.fontsize != cur.fontsize: self.canv.setFont(cellstyle.fontname, cellstyle.fontsize, cellstyle.leading) self._curcellstyle = cellstyle
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, -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("""
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>Logo</font></b> Image</para>", styleSheet["BodyText"]) data= [['A', 'B', 'C', Paragraph("<b>A pa<font color=red>r</font>a<i>graph</i></b><super><font color=yellow>1</font></super>",styleSheet["BodyText"]), 'D'], ['00', '01', '02', [I,P], '04'], ['10', '11', '12', [I,P], '14'],
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("""
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