rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
except:
except ValueError:
def afterFlowable(self, flowable): "Takes care of header line, TOC and outline entries." if flowable.__class__.__name__ == 'Paragraph': f = flowable
"""
u """
def makeHtmlSection(text, bgcolor='#FFA0FF'): """Create HTML code for a section. This is usually a header for all classes or functions. """ text = htmlescape(expandtabs(text)) result = [] result.append("""<TABLE WIDTH="100\%" BORDER="0">""") result.append("""<TR><TD BGCOLOR="%s" VALIGN="CENTER">""" % bgcolor) result.a...
def begin(self):
def begin(self, name='', typ=''):
def begin(self): styleSheet = getSampleStyleSheet() self.h1 = styleSheet['Heading1'] self.h2 = styleSheet['Heading2'] self.h3 = styleSheet['Heading3'] self.code = styleSheet['Code'] self.bt = styleSheet['BodyText'] self.story = [] self.classCompartment = '' self.methodCompartment = []
story.append(Paragraph('Imported modules', h2))
story.append(Paragraph('Imported modules', self.makeHeadingStyle(self.indentLevel + 1)))
def beginModule(self, name, doc, imported): story = self.story h1, h2, h3, bt = self.h1, self.h2, self.h3, self.bt styleSheet = getSampleStyleSheet() bt1 = styleSheet['BodyText']
story.append(Paragraph(m, bt1))
p = Paragraph('<bullet>\201</bullet> %s' % m, bt1) p.style.bulletIndent = 10 p.style.leftIndent = 18 story.append(p)
def beginModule(self, name, doc, imported): story = self.story h1, h2, h3, bt = self.h1, self.h2, self.h3, self.bt styleSheet = getSampleStyleSheet() bt1 = styleSheet['BodyText']
else:
elif abs(width)>1e-7 and abs(height)>=1e-7 and (rowStyle.fillColor is not None or rowStyle.strokeColor is not None):
def makeBars(self): g = Group()
valueSteps = AttrMapValue(isListOfNumbers),
valueSteps = AttrMapValue(isListOfNumbersOrNone),
def makeTickLabels(self): g = Group()
if hasattr(self, 'valueSteps'):
if hasattr(self, 'valueSteps') and self.valueSteps:
def _calcTickmarkPositions(self): """Calculate a list of tick positions on the axis.
if lev == 0:
if lev == 0 or title != 'Functions':
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, closed=isClosed)
c.addOutlineEntry(title, key, level=lev, closed=isClosed) c.showOutline()
def afterFlowable(self, flowable): "Takes care of header line, TOC and outline entries." if flowable.__class__.__name__ == 'Paragraph': f = flowable
widget.verify()
def _showWidgetDemo(self, widget): """Show a graphical demo of the widget."""
dept = self.EPS_info[0], company = self.EPS_info[1], preview = self.preview, showBorder=self.showBorder)
dept = getattr(self,'EPS_info',['Testing'])[0], company = getattr(self,'EPS_info',['','ReportLab'])[1], preview = getattr(self,'preview',1), showBorder=getattr(self,'showBorder',0))
def save(self, formats=None, verbose=None, fnRoot=None, outDir=None): "Saves copies of self in desired location and formats" ext = '' outDir = outDir or getattr(self,'outDir','.') if not os.path.isabs(outDir): outDir = os.path.join(os.path.dirname(sys.argv[0]),outDir) if not os.path.isdir(outDir): os.makedirs(outDir) f...
text = join(lines[i][1])
text = join(tx.lines[i][1])
def _do_under_lines(i, t_off, tx): y = tx.XtraState.cur_y - i*tx.XtraState.style.leading - tx.XtraState.f.fontSize/8.0 # 8.0 factor copied from para.py text = join(lines[i][1]) textlen = tx._canvas.stringWidth(text, tx._fontname, tx._fontsize) tx._canvas.line(t_off, y, t_off+textlen, y)
def polarToRect(self, r, theta): "Convert to rectangular based on current size" return (self._centerx + r * sin(theta),self._centery + r * cos(theta))
def polarToRect(self, r, theta): "Convert to rectangular based on current size" return (self._centerx + r * sin(theta),self._centery + r * cos(theta))
self._centerx = centerx = self.x + xradius self._centery = centery = self.y + yradius
centerx = self.x + xradius centery = self.y + yradius
def draw(self): # normalize slice data g = self.makeBackground() or Group()
n = len(self.data[0]) angleBetween = (2 * pi)/n angles = [] a = (self.startAngle * pi / 180) for i in range(n): angles.append(a) a = a + angleBetween if self.direction == "anticlockwise": whichWay = 1 else: whichWay = -1
n = len(data[0])
def draw(self): # normalize slice data g = self.makeBackground() or Group()
i = 0 startAngle = self.startAngle
def draw(self): # normalize slice data g = self.makeBackground() or Group()
for angle in angles: sa = sin(angle)*radius ca = cos(angle)*radius spoke = Line(centerx, centery, centerx + ca, centery + sa, strokeWidth = 0.5)
csa = [] angle = self.startAngle*pi/180 direction = self.direction == "clockwise" and -1 or 1 angleBetween = direction*(2 * pi)/n for i in xrange(n): car = cos(angle)*radius sar = sin(angle)*radius csa.append((car,sar,angle)) spoke = Line(centerx, centery, centerx + car, centery + sar, strokeWidth = 0.5)
def draw(self): # normalize slice data g = self.makeBackground() or Group()
ex = centerx + labelRadius*ca ey = centery + labelRadius*sa
ex = centerx + labelRadius*car ey = centery + labelRadius*sar
def draw(self): # normalize slice data g = self.makeBackground() or Group()
i = i + 1
angle = angle + angleBetween
def draw(self): # normalize slice data g = self.makeBackground() or Group()
theta = angles[-1]
car, sar = csa[-1][:2]
def draw(self): # normalize slice data g = self.makeBackground() or Group()
x0, y0 = self.polarToRect(r*radius, theta) points.append(x0) points.append(y0) for i in range(n): theta = angles[i]
points.append(centerx+car*r) points.append(centery+sar*r) for i in xrange(n): car, sar = csa[i][:2]
def draw(self): # normalize slice data g = self.makeBackground() or Group()
x1, y1 = self.polarToRect(r*radius, theta) x0, y0 = x1, y1 points.append(x0) points.append(y0)
points.append(centerx+car*r) points.append(centery+sar*r)
def draw(self): # normalize slice data g = self.makeBackground() or Group()
thisy = upperlefty = self.y - self.dx
thisy = upperlefty = self.y - self.dy
def draw(self): g = Group() colorNamePairs = self.colorNamePairs thisx = upperleftx = self.x thisy = upperlefty = self.y - self.dx dx, dy = self.dx, self.dy
G.add(Polygon(_ystrip_poly(x[0], x[1], y.y0, y.y1, xdepth, ydepth),
print 'Poly([%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%.2f])'% tuple(_ystrip_poly(x[0], x[1], y.y0, y.y1, xdepth, -ydepth)) G.add(Polygon(_ystrip_poly(x[0], x[1], y.y0, y.y1, xdepth, -ydepth),
def F(x,i, slope=slope, y0=y0): return float((x-x0)*slope[i]+y0[i])
if x is X[0]: G.add(Line(x[0], y.y1, x[0]+xdepth, y.y1+ydepth,strokeColor=c,strokeWidth=0.6*xdelta))
def F(x,i, slope=slope, y0=y0): return float((x-x0)*slope[i]+y0[i])
return cmp(_rl_accel_dir_info(b),__rl_accel_dir_info(a))
return cmp(_rl_accel_dir_info(b),_rl_accel_dir_info(a))
def _cmp_rl_accel_dirs(a,b): return cmp(_rl_accel_dir_info(b),__rl_accel_dir_info(a))
text = escape(opcode) code.append('(%s) Tj' % text)
textobject.textOut(opcode)
def runOpCodes(self, program, canvas, textobject): "render the line(s)"
text = escape(text) code.append('(%s) Tj' % text)
textobject.textOut(text)
def draw(self): style = self.style lines = self.lines rightIndent = style.rightIndent leftIndent = style.leftIndent leading = style.leading font = style.fontName size = style.fontSize alignment = style.alignment firstindent = style.firstLineIndent c = self.canv escape = c._escape #if debug: # print "FAST", id(self),...
from paraparser import greeks, symenc
from paraparser import greeks
def handleSpecialCharacters(engine, text, program=None): from paraparser import greeks, symenc from string import whitespace, atoi, atoi_error standard={'lt':'<', 'gt':'>', 'amp':'&'} # add space prefix if space here if text[0:1] in whitespace: program.append(" ") #print "handling", repr(text) # shortcut if 0 and "&" n...
if 0<=n<=255: fragment = chr(n)+fragment[semi+1:] elif symenc.has_key(n): fragment = fragment[semi+1:] (f,b,i) = engine.shiftfont(program, face="symbol") program.append(symenc[n]) engine.shiftfont(program, face=f) if fragment and fragment[0] in whitespace: program.append(" ")
if n>=0: fragment = unichr(n).encode('utf8')+fragment[semi+1:]
def handleSpecialCharacters(engine, text, program=None): from paraparser import greeks, symenc from string import whitespace, atoi, atoi_error standard={'lt':'<', 'gt':'>', 'amp':'&'} # add space prefix if space here if text[0:1] in whitespace: program.append(" ") #print "handling", repr(text) # shortcut if 0 and "&" n...
fragment = fragment[semi+1:] greeksub = greeks[name] (f,b,i) = engine.shiftfont(program, face="symbol") program.append(greeksub) engine.shiftfont(program, face=f) if fragment and fragment[0] in whitespace: program.append(" ")
fragment = greeks[name]+fragment[semi+1:]
def handleSpecialCharacters(engine, text, program=None): from paraparser import greeks, symenc from string import whitespace, atoi, atoi_error standard={'lt':'<', 'gt':'>', 'amp':'&'} # add space prefix if space here if text[0:1] in whitespace: program.append(" ") #print "handling", repr(text) # shortcut if 0 and "&" n...
justified text paragraph example
justified text paragraph example with a pound sign \xc2\xa3
def splitspace(text): # split on spacing but include spaces at element ends stext = text.split() result = [] for e in stext: result.append(e+" ") return result
pagesize=(595.27,841.89),
pagesize=None,
def __init__(self,filename, pagesize=(595.27,841.89), bottomup = 1, pageCompression=None, encoding=rl_config.defaultEncoding, invariant=rl_config.invariant, 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 s...
encoding=rl_config.defaultEncoding, invariant=rl_config.invariant,
encoding = None, invariant = None,
def __init__(self,filename, pagesize=(595.27,841.89), bottomup = 1, pageCompression=None, encoding=rl_config.defaultEncoding, invariant=rl_config.invariant, 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 s...
do_exec(cvs+(' export -r %s reportlab' % tagname), 'the export phase')
do_exec(cvs+(' export -r %s %s' % (tagname,projdir)), 'the export phase')
def cvs_checkout(d): os.chdir(d) recursive_rmdir(cvsdir) cvs = find_exe('cvs') if cvs is None: os.exit(1) os.environ['CVSROOT']=':pserver:%s@cvs.reportlab.sourceforge.net:/cvsroot/reportlab' % USER if release: do_exec(cvs+(' export -r %s reportlab' % tagname), 'the export phase') else: if py2pdf: do_exec(cvs+' co rep...
do_exec(cvs+' co reportlab', 'the checkout phase')
def cvs_checkout(d): os.chdir(d) recursive_rmdir(cvsdir) cvs = find_exe('cvs') if cvs is None: os.exit(1) os.environ['CVSROOT']=':pserver:%s@cvs.reportlab.sourceforge.net:/cvsroot/reportlab' % USER if release: do_exec(cvs+(' export -r %s reportlab' % tagname), 'the export phase') else: if py2pdf: do_exec(cvs+' co rep...
do_exec("mv reportlab %s" % dst)
do_exec("mv %s %s" % (projdir,dst), "moving %s to %s" %(projdir,py2pdf_dir))
def cvs_checkout(d): os.chdir(d) recursive_rmdir(cvsdir) cvs = find_exe('cvs') if cvs is None: os.exit(1) os.environ['CVSROOT']=':pserver:%s@cvs.reportlab.sourceforge.net:/cvsroot/reportlab' % USER if release: do_exec(cvs+(' export -r %s reportlab' % tagname), 'the export phase') else: if py2pdf: do_exec(cvs+' co rep...
else: do_exec(cvs+' co reportlab', 'the checkout phase')
def cvs_checkout(d): os.chdir(d) recursive_rmdir(cvsdir) cvs = find_exe('cvs') if cvs is None: os.exit(1) os.environ['CVSROOT']=':pserver:%s@cvs.reportlab.sourceforge.net:/cvsroot/reportlab' % USER if release: do_exec(cvs+(' export -r %s reportlab' % tagname), 'the export phase') else: if py2pdf: do_exec(cvs+' co rep...
This document is both the user guide and the output of the test script.
This document is both the user guide &amp; the output of the test script.
def getCommentary(): """Returns the story for the commentary - all the paragraphs.""" styleSheet = getSampleStyleSheet() story = [] story.append(Paragraph(""" PLATYPUS User Guide and Test Script """, styleSheet['Heading1'])) spam = """ Welcome to PLATYPUS! Platypus stands for "Page Layout and Typography Using Scri...
unittest.TextTestRunner().run(makeSuite)
unittest.TextTestRunner().run(makeSuite())
def makeSuite(): return makeSuiteForClasses(PlatypusTestCase)
logger.debug("enter Frame.addFromlist() for frame %s" % self.id)
if self._debug: logger.debug("enter Frame.addFromlist() for frame %s" % self.id)
def addFromList(self, drawlist, canv): """Consumes objects from the front of the list until the frame is full. If it cannot fit one object, raises an exception."""
if self.filename: canv.drawInlineImage( self.filename, self.x, self.y, self.width, self.height )
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(filen...
def drawOn(self, canv): if self.filename: canv.drawInlineImage( self.filename, self.x, self.y, self.width, self.height )
print """PythonPoint - copyright ReportLab Inc. 1999-2000
print """PythonPoint - copyright ReportLab Inc. 1999-2001
def process(datafilename, speakerNotes=0): parser = stdparser.PPMLParser() rawdata = open(datafilename).read() parser.feed(rawdata) pres = parser.getPresentation() pres.speakerNotes = speakerNotes pres.save() print 'saved presentation %s.pdf' % os.path.splitext(datafilename)[0] parser.close()
return type(t) in SeqTypes
return type(v) in SeqTypes
def isSeqType(v): return type(t) in SeqTypes
print find_intersections([[(0,0.5),(1,0.5),(0.5,0),(0.5,1)],[(2666666667,0.4),(0.1,0.4),(0.1,0.2),(0,0),(1,1)],[(0,1),(0.4,0.1),(1,0.1)]])
print find_intersections([[(0,0.5),(1,0.5),(0.5,0),(0.5,1)],[(.2666666667,0.4),(0.1,0.4),(0.1,0.2),(0,0),(1,1)],[(0,1),(0.4,0.1),(1,0.1)]])
def find_intersections(data,small=0): ''' data is a sequence of series each series is a list of (x,y) coordinates where x & y are ints or floats find_intersections returns a sequence of 4-tuples i, j, x, y where i is a data index j is an insertion position for data[i] and x, y are coordinates of an intersection of se...
f = self.labelTextFormat and self._allIntTicks() and '%d' or str
f = self.labelTextFormat or (self._allIntTicks() and '%d' or str)
def makeTickLabels(self): g = Group()
if self.bottomup: self._preamble = '1 0 0 1 0 0 cm BT /F9 12 Tf 14.4 TL ET' else: self._preamble = '1 0 0 -1 0 %0.2f cm BT /F9 12 Tf 14.4 TL ET' % self._pagesize[1]
self._make_preamble()
def __init__(self,filename,pagesize=(595.27,841.89), bottomup = 1, pageCompression=0 ): """Most of the attributes are private - we will use set/get methods as the preferred interface. Default page size is A4.""" self._filename = filename self._doc = pdfdoc.PDFDocument() self._pagesize = pagesize self._currentPageHasIm...
txt = open(filename, 'r').read()
txt = open_and_read(filename, 'r')
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) self.output.write("file %s contains %d tab characters!\n" % (filename, tabCount))
txt = open(filename, 'r').read()
txt = open_and_read(filename, 'r')
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 badCh...
bc.x = 10
bc.x = 20
def demo(self): """Shows basic use of a bar chart"""
bc.width = 90
bc.width = 180
def demo(self): """Shows basic use of a bar chart"""
def calcBarPositions(self):
def _findMinMaxValues(self): """Find the minimum and maximum value of the data we have.""" data = self.data m, M = Auto, Auto for row in data: for val in row: if val < m: m = val if val > M: M = val return m, M def calcBarPositions0(self):
def calcBarPositions(self): """Works out where they go.
"Make a bar chart showing value axis region staring at *exactly* zero."
"Make a bar chart showing value axis region starting at *exactly* zero."
def sample4a(): "Make a bar chart showing value axis region staring at *exactly* 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 = 0 ### bc.valueAxis.valueMax = 60 bc.v...
"Make a bar chart showing value axis region staring *below* zero."
"Make a bar chart showing value axis region starting *below* zero."
def sample4b(): "Make a bar chart showing value axis region staring *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 = -10 ### bc.valueAxis.valueMax = 60 bc.valu...
self._img = None
def __init__(self, filename, width=None, height=None, kind='direct', mask="auto", lazy=1): """If size to draw at not specified, get it from the image.""" self.hAlign = 'CENTER' self._mask = mask # if it is a JPEG, will be inlined within the file - # but we still need to know its size now fp = hasattr(filename,'read') i...
(self.imageWidth, self.imageHeight) = self._img.getSize()
img = self._img if img: self.imageWidth, self.imageHeight = img.getSize()
def _setup_inner(self): width = self._width height = self._height kind = self._kind (self.imageWidth, self.imageHeight) = self._img.getSize() if self._lazy>=2: del self._img if kind in ['direct','absolute']: self.drawWidth = width or self.imageWidth self.drawHeight = height or self.imageHeight elif kind in ['percentage...
ReportLabBlue = HexColor(0x4e5688)
ReportLabBlueOLD = HexColor(0x4e5688) ReportLabBlue = HexColor(0x00337f) ReportLabBluePCMYK = PCMYKColor(100,65,0,30,spotName='Pantone 288U')
def linearlyInterpolatedColor(c0, c1, x0, x1, x): """ Linearly interpolates colors. Can handle RGB, CMYK and PCMYK colors - give ValueError if colours aren't the same. Doesn't currently handle 'Spot Color Interpolation'. """ if c0.__class__ != c1.__class__: raise ValueError, "Color classes must be the same for interpo...
y = scale(self._findMinMaxValues()[0])
y = self._findMinMaxValues()[0] if vm is not None: y = min(y,vm) y = scale(y)
def calcBarPositions(self): """Works out where they go. default vertical.
org = flipXY and self.y or self.x
if flipXY: org = self.y else: org = self.x
def calcBarPositions(self): """Works out where they go. default vertical.
fontSize = self.labelFontSize))
fontSize = self.labelFontSize)
def draw(self): g = Group() ys = self.bottomPadding+(self.triangleHeight/2)+self.sourceLabelOffset+self.sourceLabelFontSize if self.background: x,y = self._getDrawingDimensions() g.add(Rect(-self.leftPadding,-ys,x,y, strokeColor=None, strokeWidth=0, fillColor=self.background))
self.syntax_error('%s: invalid value %s'%(k,v))
self._syntax_error('%s: invalid value %s'%(k,v))
def getAttributes(self,attr,attrMap): A = {} for k, v in attr.items(): k = string.lower(k) if k in attrMap.keys(): j = attrMap[k] func = j[1] try: A[j[0]] = (func is None) and v or apply(func,(v,)) except: self.syntax_error('%s: invalid value %s'%(k,v)) else: self.syntax_error('invalid attribute name %s'%k) return A
self.syntax_error('invalid attribute name %s'%k)
self._syntax_error('invalid attribute name %s'%k)
def getAttributes(self,attr,attrMap): A = {} for k, v in attr.items(): k = string.lower(k) if k in attrMap.keys(): j = attrMap[k] func = j[1] try: A[j[0]] = (func is None) and v or apply(func,(v,)) except: self.syntax_error('%s: invalid value %s'%(k,v)) else: self.syntax_error('invalid attribute name %s'%k) return A
def syntax_error(self,message): if message[:11]=="attribute `" and message[-18:]=="' value not quoted": return self.errors.append(message)
def _reset(self, style): '''reset the parser''' xmllib.XMLParser.reset(self)
elif self.forceZero:
if self.forceZero:
def _setRange(self, dataSeries): """Set minimum and maximum axis values.
data.append(0, """Chapter %d with a really long name which will hopefully
data.append((0, """Chapter %d with a really long name which will hopefully
def getSampleTOCData(depth=3): """Returns a longish block of page numbers and headings over 3 levels""" from random import randint pgNum = 2 data = [] for chapter in range(1,8): data.append(0, """Chapter %d with a really long name which will hopefully wrap onto a second line, fnding out if the right things happen with ...
full paragraphs n the table of contents""" % chapter, pgNum)
full paragraphs n the table of contents""" % chapter, pgNum))
def getSampleTOCData(depth=3): """Returns a longish block of page numbers and headings over 3 levels""" from random import randint pgNum = 2 data = [] for chapter in range(1,8): data.append(0, """Chapter %d with a really long name which will hopefully wrap onto a second line, fnding out if the right things happen with ...
data.append(1, 'Chapter %d Section %d' % (chapter, section), pgNum)
data.append((1, 'Chapter %d Section %d' % (chapter, section), pgNum))
def getSampleTOCData(depth=3): """Returns a longish block of page numbers and headings over 3 levels""" from random import randint pgNum = 2 data = [] for chapter in range(1,8): data.append(0, """Chapter %d with a really long name which will hopefully wrap onto a second line, fnding out if the right things happen with ...
fp=image.fp
fp=im._image.fp
def loadImageFromSRC(self, im): "Extracts the stream, width and height" if im._image.format=='JPEG': fp=image.fp fp.seek(0) self.loadImageFromJPEG(fp) else: zlib = import_zlib() if not zlib: return self.width, self.height = im.getSize() raw = im.getRGBData() assert(len(raw) == self.width*self.height, "Wrong amount of d...
return Color(arg[0],arg[1],arg[2])
assert 3<=len(arg)<=4, 'Can only convert 3 and 4 sequences to color' assert 0<=min(arg) and max(arg)<=1 return len(arg)==3 and Color(arg[0],arg[1],arg[2]) or CMYKColor(arg[0],arg[1],arg[2],arg[3])
def toColor(arg,default=None): '''try to map an arbitrary arg to a color instance''' if isinstance(arg,Color): return arg tArg = type(arg) if tArg in _SeqTypes: return Color(arg[0],arg[1],arg[2]) elif tArg == StringType: C = getAllNamedColors() s = string.lower(arg) if C.has_key(s): return C[s] try: s = eval(arg) if is...
s = eval(arg) if isinstance(s,Color): return s
return toColor(eval(arg))
def toColor(arg,default=None): '''try to map an arbitrary arg to a color instance''' if isinstance(arg,Color): return arg tArg = type(arg) if tArg in _SeqTypes: return Color(arg[0],arg[1],arg[2]) elif tArg == StringType: C = getAllNamedColors() s = string.lower(arg) if C.has_key(s): return C[s] try: s = eval(arg) if is...
if oldValue in self.contents: pos = mylist.index(oldValue)
if oldValue in self_contents: pos = self_contents.index(oldValue)
def expandUserNodes0(self): """Return a new drawing which only contains primitive shapes."""
if pagesize is None: pagesize rl_config.defaultPageSize
if pagesize is None: pagesize = rl_config.defaultPageSize
def __init__(self,filename, pagesize=None, bottomup = 1, pageCompression=None, encoding = None, invariant = None, 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.""" if pagesize is None: pagesize...
if cp != dp:
if cp!=sp:
def checkPageSize(self,canv,doc): '''This gets called by the template framework If canv size != doc size then the canv size is set to the template size or if that's not available to the doc size. ''' #### NEVER EVER EVER COMPARE FLOATS FOR EQUALITY #RGB converting pagesizes to ints means we are accurate to one point #R...
else:
elif cp!=dp:
def checkPageSize(self,canv,doc): '''This gets called by the template framework If canv size != doc size then the canv size is set to the template size or if that's not available to the doc size. ''' #### NEVER EVER EVER COMPARE FLOATS FOR EQUALITY #RGB converting pagesizes to ints means we are accurate to one point #R...
f = open(filename, 'wb')
if type(f)==type(''): f = open(filename, 'wb') else: f = filename
def SaveToFile(self, filename,canvas): """Open a file, and ask each object in turn to write itself to the file. Keep track of the file position at each point for use in the index at the end""" f = open(filename, 'wb') i = 1 self.xref = [] f.write("%PDF-1.2" + LINEEND) # for CID support f.write("%\355\354\266\276" + L...
if type(baseDir) not in SeqTypes
if type(baseDir) not in SeqTypes:
def recursiveImport(modulename, baseDir=None, noCWD=0, debug=0): """Dynamically imports possible packagized module, or raises ImportError""" import imp parts = string.split(modulename, '.') name = parts[0] if baseDir is None: path = sys.path[:] else: if type(baseDir) not in SeqTypes path = [baseDir] else: path = list(...
sys.argv.apend('pythonpoint.xml')
sys.argv.append('pythonpoint.xml')
def process(datafilename): parser = stdparser.PPMLParser() rawdata = open(datafilename).read() parser.feed(rawdata) pres = parser.getPresentation() pres.save() parser.close()
def __init__(self, encoding=DEFAULT_ENCODING):
def __init__(self, encoding=DEFAULT_ENCODING, dummyoutline=0):
def __init__(self, encoding=DEFAULT_ENCODING): self.encoding = encoding # mapping of internal identifier ("Page001") to PDF objectnumber and generation number (34, 0) self.idToObjectNumberAndVersion = {} # mapping of internal identifier ("Page001") to PDF object (PDFPage instance) self.idToObject = {} # internal id to ...
outlines = self.Outlines = self.outline = PDFOutlines()
if dummyoutline: outlines = PDFOutlines0() else: outlines = PDFOutlines() self.Outlines = self.outline = outlines
def __init__(self, encoding=DEFAULT_ENCODING): self.encoding = encoding # mapping of internal identifier ("Page001") to PDF objectnumber and generation number (34, 0) self.idToObjectNumberAndVersion = {} # mapping of internal identifier ("Page001") to PDF object (PDFPage instance) self.idToObject = {} # internal id to ...
outline = self.outline outline.prepare(self, canvas)
def format(self): # register the Catalog/INfo and then format the objects one by one until exhausted # (possible infinite loop if there is a bug that continually makes new objects/refs...) # prepare outline outline = self.outline outline.prepare(self, canvas) cat = self.Catalog info = self.Info self.Reference(self.Cata...
'''
def testpage(document): P = PDFPage() P.Contents = teststream() pages = document.Pages P.Parent = document.Reference(pages) P.MediaBox = PDFArray([0, 0, 595, 841]) resources = PDFResourceDictionary() resources.allProcs() # enable all procsets resources.basicFonts() P.Resources = resources pages.addPage(P)
class PDFOutlines:
class PDFOutlines0:
def testpage(document): P = PDFPage() P.Contents = teststream() pages = document.Pages P.Parent = document.Reference(pages) P.MediaBox = PDFArray([0, 0, 595, 841]) resources = PDFResourceDictionary() resources.allProcs() # enable all procsets resources.basicFonts() P.Resources = resources pages.addPage(P)
'''
def format(self, document): return self.text '''
D = PDFDocument()
D = PDFDocument(dummyoutline=1)
def format(self, document): self.BBox = self.BBox or PDFArray([self.lowerx, self.lowery, self.upperx, self.uppery]) self.Matrix = self.Matrix or PDFArray([1, 0, 0, 1, 0, 0]) if not self.Annots: self.Annots = None else: raise ValueError, "annotations not reimplemented yet" if not self.Contents: stream = self.stream if n...
return string.join(self.strings, "")
return string.join(strings, "")
def format(self, document): strings = map(str, self.strings) # final conversion, in case of lazy objects return string.join(self.strings, "")
'sigmaf': 'v',
'sigmaf': 'V',
def _applyAttributes(obj, attr): for k, v in attr.items(): if type(v) is TupleType and v[0]=='relative': #AR 20/5/2000 - remove 1.5.2-ism #v = v[1]+getattr(obj,k,0) if hasattr(obj, k): v = v[1]+getattr(obj,k) else: v = v[1] setattr(obj,k,v)
'thetasym': 'j', 'thetav': 'j',
'thetasym': 'J', 'thetav': 'J',
def _applyAttributes(obj, attr): for k, v in attr.items(): if type(v) is TupleType and v[0]=='relative': #AR 20/5/2000 - remove 1.5.2-ism #v = v[1]+getattr(obj,k,0) if hasattr(obj, k): v = v[1]+getattr(obj,k) else: v = v[1] setattr(obj,k,v)
962:'v',
962:'V',
def _applyAttributes(obj, attr): for k, v in attr.items(): if type(v) is TupleType and v[0]=='relative': #AR 20/5/2000 - remove 1.5.2-ism #v = v[1]+getattr(obj,k,0) if hasattr(obj, k): v = v[1]+getattr(obj,k) else: v = v[1] setattr(obj,k,v)
977:'j',
977:'J',
def _applyAttributes(obj, attr): for k, v in attr.items(): if type(v) is TupleType and v[0]=='relative': #AR 20/5/2000 - remove 1.5.2-ism #v = v[1]+getattr(obj,k,0) if hasattr(obj, k): v = v[1]+getattr(obj,k) else: v = v[1] setattr(obj,k,v)
try: c = symenc[n] except KeyError: self.unknown_charref(name) return self._push(greek=1) self.handle_data(c) self._pop(greek=1)
self.unknown_charref(name)
def handle_charref(self, name): try: if name[0] == 'x': n = string.atoi(name[1:], 16) else: n = string.atoi(name) except string.atoi_error: self.unknown_charref(name) return if 0 <=n<=255: self.handle_data(chr(n)) else: try: c = symenc[n] except KeyError: self.unknown_charref(name) return self._push(greek=1) self.handl...
def _copyNamedContents(self,obj):
def _copyContents(self,obj): for child in self.contents: obj.contents.append(child) def _copyNamedContents(self,obj,aKeys=None,noCopy=('contents',)): from copy import copy
def _copyNamedContents(self,obj): self_contents = self.contents for (oldKey, oldValue) in self.__dict__.items(): if oldValue in self_contents: pos = self_contents.index(oldValue) setattr(obj, oldKey, obj.contents[pos])
for (oldKey, oldValue) in self.__dict__.items(): if oldValue in self_contents: pos = self_contents.index(oldValue)
if not aKeys: aKeys = self._attrMap.keys() for (k, v) in self.__dict__.items(): if k in self_contents: pos = self_contents.index(v)
def _copyNamedContents(self,obj): self_contents = self.contents for (oldKey, oldValue) in self.__dict__.items(): if oldValue in self_contents: pos = self_contents.index(oldValue) setattr(obj, oldKey, obj.contents[pos])
def copy(self): """returns a copy""" obj = self.__class__() obj.transform = self.transform[:] self_contents = self.contents for child in self_contents: obj.append(child.copy())
elif k in aKeys and k not in noCopy: setattr(obj, k, copy(v)) def _copy(self,obj): """copies to obj""" obj._attrMap = self._attrMap.clone() self._copyContents(obj)
def _copyNamedContents(self,obj): self_contents = self.contents for (oldKey, oldValue) in self.__dict__.items(): if oldValue in self_contents: pos = self_contents.index(oldValue) setattr(obj, oldKey, obj.contents[pos])
def _copy(self,obj): """copies to obj""" obj._attrMap = self._attrMap.clone() self_contents = self.contents for child in self_contents: obj.contents.append(child) self_contents = self.contents for (oldKey, oldValue) in self.__dict__.items(): if oldValue in self_contents: pos = self_contents.index(oldValue) setattr(ob...
def _copy(self,obj): """copies to obj""" obj._attrMap = self._attrMap.clone()
self.page = page; self.top=top; self.zoom=zoom
self.page = page self.top = top self.zoom = zoom self.left = left
def __init__(self, page, left, top, zoom): self.page = page; self.top=top; self.zoom=zoom
cvsdir = os.path.join(groupdir,projdir)
cvsdir = os.path.join(d,projdir)
def cvs_checkout(d): os.chdir(d) cvsdir = os.path.join(groupdir,projdir) recursive_rmdir(cvsdir) cvs = find_exe('cvs') if cvs is None: os.exit(1) os.environ['CVSROOT']=':pserver:%s@cvs.reportlab.sourceforge.net:/cvsroot/reportlab' % USER if release: do_exec(cvs+(' export -r %s %s' % (tagname,projdir)), 'the export ph...
self._tempdir = get_rl_tempdir('reportlab_test','tmp_%d' % time()) _testmodulename = os.path.join(self._tempdir,'test_module_%d.py' % time())
s = `int(time())` + `self.count` self.count += 1 self._tempdir = get_rl_tempdir('reportlab_test','tmp_%s' % s) _testmodulename = os.path.join(self._tempdir,'test_module_%s.py' % s)
def setUp(self): from time import time from reportlab.lib.utils import get_rl_tempdir self._tempdir = get_rl_tempdir('reportlab_test','tmp_%d' % time()) _testmodulename = os.path.join(self._tempdir,'test_module_%d.py' % time()) f = open(_testmodulename,'w') f.write('__all__=[]\n') f.close() self._testmodulename = os.pa...
htmlTop = """<html><head><title>renderGD output results</title></head>
htmlTop = """<html><head><title>renderPM output results</title></head>
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>renderGD output results</title></head>...
def __init__(self,fn='rl_dbgmemo.dbg',mode='w',getScript=1,modules=(),**kw):
def __init__(self,fn='rl_dbgmemo.dbg',mode='w',getScript=1,modules=(),capture_traceback=1, **kw):
def __init__(self,fn='rl_dbgmemo.dbg',mode='w',getScript=1,modules=(),**kw): import time, socket self.fn = fn if mode!='w': return self.store = store = {} if sys.exc_info() != (None,None,None): import traceback s = getStringIO() traceback.print_exc(None,s) store['__traceback'] = s.getvalue() cwd=os.getcwd() lcwd = os.l...