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.append("""<H2>%s</H2>""" % text) result.append("""</TD></TR></TABLE>""") result.append('') return join(result, '\n') |
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) fnroot = os.path.normpath(os.path.join(outDir, fnRoot or (getattr(self,'fileNamePattern',(self.__class__.__name__+'%03d')) % getattr(self,'chartId',0)))) |
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), "page number", c.getPageNumber() height = self.height #if debug: # c.rect(0,0,-1, height-size, fill=1, stroke=1) c.translate(0, height-size) textobject = c.beginText() code = textobject._code #textobject.setTextOrigin(0,firstindent) textobject.setFont(font, size) if style.textColor: textobject.setFillColor(style.textColor) first = 1 y = 0 basicWidth = self.availableWidth - rightIndent count = 0 nlines = len(lines) while count<nlines: (text, length, nwords) = lines[count] count = count+1 thisindent = leftIndent if first: thisindent = firstindent if alignment==TA_LEFT: x = thisindent elif alignment==TA_CENTER: extra = basicWidth - length x = thisindent + extra/2.0 elif alignment==TA_RIGHT: extra = basicWidth - length x = thisindent + extra elif alignment==TA_JUSTIFY: x = thisindent if count<nlines and nwords>1: # patch from [email protected], 9 Nov 2002, no extraspace on last line textobject.setWordSpace((basicWidth-length)/(nwords-1.0)) else: textobject.setWordSpace(0.0) textobject.setTextOrigin(x,y) text = escape(text) code.append('(%s) Tj' % text) #textobject.textOut(text) y = y-leading c.drawText(textobject) |
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 "&" not in text: result = [] for x in text.split(): result.append(x+" ") if result: last = result[-1] if text[-1:] not in whitespace: result[-1] = last.strip() program.extend(result) return program if program is None: program = [] amptext = text.split("&") first = 1 lastfrag = amptext[-1] for fragment in amptext: if not first: # check for special chars semi = fragment.find(";") if semi>0: name = fragment[:semi] if name[0]=='#': try: if name[1] == 'x': n = atoi(name[2:], 16) else: n = atoi(name[1:]) except atoi_error: n = -1 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(" ") # follow with a space else: fragment = "&"+fragment elif standard.has_key(name): fragment = standard[name]+fragment[semi+1:] elif greeks.has_key(name): 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(" ") # follow with a space else: # add back the & fragment = "&"+fragment else: # add back the & fragment = "&"+fragment # add white separated components of fragment followed by space sfragment = fragment.split() for w in sfragment[:-1]: program.append(w+" ") # does the last one need a space? if sfragment and fragment: # reader 3 used to go nuts if you don't special case the last frag, but it's fixed? if fragment[-1] in whitespace: # or fragment==lastfrag: program.append( sfragment[-1]+" " ) else: last = sfragment[-1].strip() if last: #print "last is", repr(last) program.append( last ) first = 0 #print "HANDLED", program return program |
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 "&" not in text: result = [] for x in text.split(): result.append(x+" ") if result: last = result[-1] if text[-1:] not in whitespace: result[-1] = last.strip() program.extend(result) return program if program is None: program = [] amptext = text.split("&") first = 1 lastfrag = amptext[-1] for fragment in amptext: if not first: # check for special chars semi = fragment.find(";") if semi>0: name = fragment[:semi] if name[0]=='#': try: if name[1] == 'x': n = atoi(name[2:], 16) else: n = atoi(name[1:]) except atoi_error: n = -1 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(" ") # follow with a space else: fragment = "&"+fragment elif standard.has_key(name): fragment = standard[name]+fragment[semi+1:] elif greeks.has_key(name): 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(" ") # follow with a space else: # add back the & fragment = "&"+fragment else: # add back the & fragment = "&"+fragment # add white separated components of fragment followed by space sfragment = fragment.split() for w in sfragment[:-1]: program.append(w+" ") # does the last one need a space? if sfragment and fragment: # reader 3 used to go nuts if you don't special case the last frag, but it's fixed? if fragment[-1] in whitespace: # or fragment==lastfrag: program.append( sfragment[-1]+" " ) else: last = sfragment[-1].strip() if last: #print "last is", repr(last) program.append( last ) first = 0 #print "HANDLED", program return program |
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 "&" not in text: result = [] for x in text.split(): result.append(x+" ") if result: last = result[-1] if text[-1:] not in whitespace: result[-1] = last.strip() program.extend(result) return program if program is None: program = [] amptext = text.split("&") first = 1 lastfrag = amptext[-1] for fragment in amptext: if not first: # check for special chars semi = fragment.find(";") if semi>0: name = fragment[:semi] if name[0]=='#': try: if name[1] == 'x': n = atoi(name[2:], 16) else: n = atoi(name[1:]) except atoi_error: n = -1 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(" ") # follow with a space else: fragment = "&"+fragment elif standard.has_key(name): fragment = standard[name]+fragment[semi+1:] elif greeks.has_key(name): 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(" ") # follow with a space else: # add back the & fragment = "&"+fragment else: # add back the & fragment = "&"+fragment # add white separated components of fragment followed by space sfragment = fragment.split() for w in sfragment[:-1]: program.append(w+" ") # does the last one need a space? if sfragment and fragment: # reader 3 used to go nuts if you don't special case the last frag, but it's fixed? if fragment[-1] in whitespace: # or fragment==lastfrag: program.append( sfragment[-1]+" " ) else: last = sfragment[-1].strip() if last: #print "last is", repr(last) program.append( last ) first = 0 #print "HANDLED", program return program |
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 size is A4.""" self._filename = filename self._encodingName = encoding self._doc = pdfdoc.PDFDocument(encoding, compression=pageCompression, invariant=invariant) |
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 size is A4.""" self._filename = filename self._encodingName = encoding self._doc = pdfdoc.PDFDocument(encoding, compression=pageCompression, invariant=invariant) |
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:%[email protected]:/cvsroot/reportlab' % USER if release: do_exec(cvs+(' export -r %s reportlab' % tagname), 'the export phase') else: if py2pdf: do_exec(cvs+' co reportlab', 'the checkout phase') # now we need to move the files & delete those we don't need dst = py2pdf_dir recursive_rmdir(dst) os.mkdir(dst) do_exec("mv reportlab/demos/py2pdf/py2pdf.py %s"%dst, "mv py2pdf.py") do_exec("mv reportlab/demos/py2pdf/PyFontify.py %s" % dst, "mv pyfontify.py") do_exec("rm -r reportlab/demos reportlab/platypus reportlab/lib/styles.py reportlab/README.pdfgen.txt", "rm") do_exec("mv reportlab %s" % dst) CVS_remove(dst) else: do_exec(cvs+' co reportlab', 'the checkout phase') |
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:%[email protected]:/cvsroot/reportlab' % USER if release: do_exec(cvs+(' export -r %s reportlab' % tagname), 'the export phase') else: if py2pdf: do_exec(cvs+' co reportlab', 'the checkout phase') # now we need to move the files & delete those we don't need dst = py2pdf_dir recursive_rmdir(dst) os.mkdir(dst) do_exec("mv reportlab/demos/py2pdf/py2pdf.py %s"%dst, "mv py2pdf.py") do_exec("mv reportlab/demos/py2pdf/PyFontify.py %s" % dst, "mv pyfontify.py") do_exec("rm -r reportlab/demos reportlab/platypus reportlab/lib/styles.py reportlab/README.pdfgen.txt", "rm") do_exec("mv reportlab %s" % dst) CVS_remove(dst) else: do_exec(cvs+' co reportlab', 'the checkout phase') |
|
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:%[email protected]:/cvsroot/reportlab' % USER if release: do_exec(cvs+(' export -r %s reportlab' % tagname), 'the export phase') else: if py2pdf: do_exec(cvs+' co reportlab', 'the checkout phase') # now we need to move the files & delete those we don't need dst = py2pdf_dir recursive_rmdir(dst) os.mkdir(dst) do_exec("mv reportlab/demos/py2pdf/py2pdf.py %s"%dst, "mv py2pdf.py") do_exec("mv reportlab/demos/py2pdf/PyFontify.py %s" % dst, "mv pyfontify.py") do_exec("rm -r reportlab/demos reportlab/platypus reportlab/lib/styles.py reportlab/README.pdfgen.txt", "rm") do_exec("mv reportlab %s" % dst) CVS_remove(dst) else: do_exec(cvs+' co reportlab', 'the checkout phase') |
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:%[email protected]:/cvsroot/reportlab' % USER if release: do_exec(cvs+(' export -r %s reportlab' % tagname), 'the export phase') else: if py2pdf: do_exec(cvs+' co reportlab', 'the checkout phase') # now we need to move the files & delete those we don't need dst = py2pdf_dir recursive_rmdir(dst) os.mkdir(dst) do_exec("mv reportlab/demos/py2pdf/py2pdf.py %s"%dst, "mv py2pdf.py") do_exec("mv reportlab/demos/py2pdf/PyFontify.py %s" % dst, "mv pyfontify.py") do_exec("rm -r reportlab/demos reportlab/platypus reportlab/lib/styles.py reportlab/README.pdfgen.txt", "rm") do_exec("mv reportlab %s" % dst) CVS_remove(dst) else: do_exec(cvs+' co reportlab', 'the checkout phase') |
|
This document is both the user guide and the output of the test script. | This document is both the user guide & 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 Scripts". It is a high level page layout library which lets you programmatically create complex documents with a minimum of effort. This document is both the user guide and the output of the test script. In other words, a script used platypus to create the document you are now reading, and the fact that you are reading it proves that it works. Or rather, that it worked for this script anyway. It is a first release! Platypus is built 'on top of' PDFgen, the Python library for creating PDF documents. To learn about PDFgen, read the document testpdfgen.pdf. """ for text in getParagraphs(spam): story.append(Paragraph(text, styleSheet['BodyText'])) story.append(Paragraph(""" What concepts does PLATYPUS deal with? """, styleSheet['Heading2'])) story.append(Paragraph(""" The central concepts in PLATYPUS are Flowable Objects, Frames, Flow Management, Styles and Style Sheets, Paragraphs and Tables. This is best explained in contrast to PDFgen, the layer underneath PLATYPUS. PDFgen is a graphics library, and has primitive commans to draw lines and strings. There is nothing in it to manage the flow of text down the page. PLATYPUS works at the conceptual level fo a desktop publishing package; you can write programs which deal intelligently with graphic objects and fit them onto the page. """, styleSheet['BodyText'])) story.append(Paragraph(""" How is this document organized? """, styleSheet['Heading2'])) story.append(Paragraph(""" Since this is a test script, we'll just note how it is organized. the top of each page contains commentary. The bottom half contains example drawings and graphic elements to whicht he commentary will relate. Down below, you can see the outline of a text frame, and various bits and pieces within it. We'll explain how they work on the next page. """, styleSheet['BodyText'])) story.append(FrameBreak()) ####################################################################### # Commentary Page 2 ####################################################################### story.append(Paragraph(""" Flowable Objects """, styleSheet['Heading2'])) spam = """ The first and most fundamental concept is that of a 'Flowable Object'. In PDFgen, you draw stuff by calling methods of the canvas to set up the colors, fonts and line styles, and draw the graphics primitives. If you set the pen color to blue, everything you draw after will be blue until you change it again. And you have to handle all of the X-Y coordinates yourself. A 'Flowable object' is exactly what it says. It knows how to draw itself on the canvas, and the way it does so is totally independent of what you drew before or after. Furthermore, it draws itself at the location on the page you specify. The most fundamental Flowable Objects in most documents are likely to be paragraphs, tables, diagrams/charts and images - but there is no restriction. You can write your own easily, and I hope that people will start to contribute them. PINGO users - we provide a "PINGO flowable" object to let you insert platform-independent graphics into the flow of a document. When you write a flowable object, you inherit from Flowable and must implement two methods. object.wrap(availWidth, availHeight) will be called by other parts of the system, and tells you how much space you have. You should return how much space you are going to use. For a fixed-size object, this is trivial, but it is critical - PLATYPUS needs to figure out if things will fit on the page before drawing them. For other objects such as paragraphs, the height is obviously determined by the available width. The second method is object.draw(). Here, you do whatever you want. The Flowable base class sets things up so that you have an origin of (0,0) for your drawing, and everything will fit nicely if you got the height and width right. It also saves and restores the graphics state around your calls, so you don;t have to reset all the properties you changed. Programs which actually draw a Flowable don't call draw() this directly - they call object.drawOn(canvas, x, y). So you can write code in your own coordinate system, and things can be drawn anywhere on the page (possibly even scaled or rotated). """ for text in getParagraphs(spam): story.append(Paragraph(text, styleSheet['BodyText'])) story.append(FrameBreak()) ####################################################################### # Commentary Page 3 ####################################################################### story.append(Paragraph(""" Available Flowable Objects """, styleSheet['Heading2'])) story.append(Paragraph(""" Platypus comes with a basic set of flowable objects. Here we list their class names and tell you what they do: """, styleSheet['BodyText'])) #we can use the bullet feature to do a definition list story.append(Paragraph(""" <para color=green bcolor=red bg=pink>This is a contrived object to give an example of a Flowable - just a fixed-size box with an X through it and a centred string.</para>""", styleSheet['Definition'], bulletText='XBox ' #hack - spot the extra space after )) story.append(Paragraph(""" This is the basic unit of a document. Paragraphs can be finely tuned and offer a host of properties through their associated ParagraphStyle.""", styleSheet['Definition'], bulletText='Paragraph ' #hack - spot the extra space after )) story.append(Paragraph(""" This is used for printing code and other preformatted text. There is no wrapping, and line breaks are taken where they occur. Many paragraph style properties do not apply. You may supply an optional 'dedent' parameter to trim a number of characters off the front of each line.""", styleSheet['Definition'], bulletText='Preformatted ' #hack - spot the extra space after )) story.append(Paragraph(""" This is a straight wrapper around an external image file. By default the image will be drawn at a scale of one pixel equals one point, and centred in the frame. You may supply an optional width and height.""", styleSheet['Definition'], bulletText='Image ' #hack - spot the extra space after )) story.append(Paragraph(""" This is a table drawing class; it is intended to be simpler than a full HTML table model yet be able to draw attractive output, and behave intelligently when the numbers of rows and columns vary. Still need to add the cell properties (shading, alignment, font etc.)""", styleSheet['Definition'], bulletText='Table ' #hack - spot the extra space after )) story.append(Paragraph(""" This is a 'null object' which merely takes up space on the page. Use it when you want some extra padding betweene elements.""", styleSheet['Definition'], bulletText='Spacer ' #hack - spot the extra space after )) story.append(Paragraph(""" A FrameBreak causes the document to call its handle_frameEnd method.""", styleSheet['Definition'], bulletText='FrameBreak ' #hack - spot the extra space after )) story.append(Paragraph(""" This is in progress, but a macro is basically a chunk of Python code to be evaluated when it is drawn. It could do lots of neat things.""", styleSheet['Definition'], bulletText='Macro ' #hack - spot the extra space after )) story.append(FrameBreak()) story.append(Paragraph( "The next example uses a custom font", styleSheet['Italic'])) story.append(FrameBreak()) return story |
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(filename) | 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 series data[i] with some other series. If correctly implemented we get all such intersections. We don't count endpoint intersections and consider parallel lines as non intersecting (even when coincident). We ignore segments that have an estimated size less than small. ''' #find all line segments S = [] a = S.append for s in xrange(len(data)): ds = data[s] if not ds: continue n = len(ds) if n==1: continue for i in xrange(1,n): seg = _Segment(s,i,data) if seg.a+abs(seg.b)>=small: a(seg) S.sort(_segCmp) I = [] n = len(S) for i in xrange(0,n-1): s = S[i] for j in xrange(i+1,n): if s.intersect(S[j],I)==1: break I.sort() return I |
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._currentPageHasImages = 1 self._pageTransitionString = '' |
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 badChars = badChars + spaces |
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.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dy = -5 bc.categoryAxis.categoryNames = ['Ying', 'Yang'] drawing.add(bc) return drawing |
"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.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dy = -5 bc.categoryAxis.categoryNames = ['Ying', 'Yang'] drawing.add(bc) return drawing |
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') if fp: self._file = filename self.filename = `filename` else: self._file = self.filename = filename if not fp and os.path.splitext(filename)[1] in ['.jpg', '.JPG', '.jpeg', '.JPEG']: from reportlab.lib.utils import open_for_read f = open_for_read(filename, 'b') info = pdfutils.readJPEGInfo(f) f.close() self.imageWidth = info[0] self.imageHeight = info[1] self._setup(width,height,kind,0) self._img = None elif fp: self._setup(width,height,kind,0) else: self._setup(width,height,kind,lazy) |
|
(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','%']: self.drawWidth = self.imageWidth*width*0.01 self.drawHeight = self.imageHeight*height*0.01 elif kind in ['bound','proportional']: factor = min(float(width)/self.imageWidth,float(height)/self.imageHeight) self.drawWidth = self.imageWidth*factor self.drawHeight = self.imageHeight*factor |
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 interpolation!" if x1<x0: x0,x1,c0,c1 = x1,x0,c1,c0 # normalized so x1>x0 if x<x0-1e-8 or x>x1+1e-8: # fudge factor for numerical problems raise ValueError, "Can't interpolate: x=%f is not between %f and %f!" % (x,x0,x1) if x<=x0: return c0 elif x>=x1: return c1 cname = c0.__class__.__name__ dx = float(x1-x0) x = x-x0 if cname == 'Color': # RGB r = c0.red+x*(c1.red - c0.red)/dx g = c0.green+x*(c1.green- c0.green)/dx b = c0.blue+x*(c1.blue - c0.blue)/dx return Color(r,g,b) elif cname == 'CMYKColor': c = c0.cyan+x*(c1.cyan - c0.cyan)/dx m = c0.magenta+x*(c1.magenta - c0.magenta)/dx y = c0.yellow+x*(c1.yellow - c0.yellow)/dx k = c0.black+x*(c1.black - c0.black)/dx d = c0.density+x*(c1.density - c0.density)/dx return CMYKColor(c,m,y,k, density=d) elif cname == 'PCMYKColor': if cmykDistance(c0,c1)<1e-8: #colors same do density and preserve spotName if any assert c0.spotName == c1.spotName, "Identical cmyk, but different spotName" c = c0.cyan m = c0.magenta y = c0.yellow k = c0.black d = c0.density+x*(c1.density - c0.density)/dx return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100, spotName=c0.spotName) elif cmykDistance(c0,_CMYK_white)<1e-8: #special c0 is white c = c1.cyan m = c1.magenta y = c1.yellow k = c1.black d = x*c1.density/dx return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100, spotName=c1.spotName) elif cmykDistance(c1,_CMYK_white)<1e-8: #special c1 is white c = c0.cyan m = c0.magenta y = c0.yellow k = c0.black d = x*c0.density/dx d = c0.density*(1-x/dx) return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100, spotName=c0.spotName) else: c = c0.cyan+x*(c1.cyan - c0.cyan)/dx m = c0.magenta+x*(c1.magenta - c0.magenta)/dx y = c0.yellow+x*(c1.yellow - c0.yellow)/dx k = c0.black+x*(c1.black - c0.black)/dx d = c0.density+x*(c1.density - c0.density)/dx return PCMYKColor(c*100,m*100,y*100,k*100, density=d*100) else: raise ValueError, "Can't interpolate: Unknown color class %s!" % cname |
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) pgNum = pgNum + randint(0,2) if depth > 1: for section in range(1,5): data.append(1, 'Chapter %d Section %d' % (chapter, section), pgNum) pgNum = pgNum + randint(0,2) if depth > 2: for subSection in range(1,6): data.append(2, 'Chapter %d Section %d Subsection %d' % (chapter, section, subSection), pgNum) pgNum = pgNum + randint(0,1) return data |
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 full paragraphs n the table of contents""" % chapter, pgNum) pgNum = pgNum + randint(0,2) if depth > 1: for section in range(1,5): data.append(1, 'Chapter %d Section %d' % (chapter, section), pgNum) pgNum = pgNum + randint(0,2) if depth > 2: for subSection in range(1,6): data.append(2, 'Chapter %d Section %d Subsection %d' % (chapter, section, subSection), pgNum) pgNum = pgNum + randint(0,1) return data |
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 full paragraphs n the table of contents""" % chapter, pgNum) pgNum = pgNum + randint(0,2) if depth > 1: for section in range(1,5): data.append(1, 'Chapter %d Section %d' % (chapter, section), pgNum) pgNum = pgNum + randint(0,2) if depth > 2: for subSection in range(1,6): data.append(2, 'Chapter %d Section %d Subsection %d' % (chapter, section, subSection), pgNum) pgNum = pgNum + randint(0,1) return data |
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 data for image") self.streamContent = pdfutils._AsciiBase85Encode(zlib.compress(raw)) self.colorSpace = 'DeviceRGB' self.bitsPerComponent = 8 self._filters = 'ASCII85Decode','FlateDecode' #'A85','Fl' self._checkTransparency(im) |
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 isinstance(s,Color): return s except: pass try: return HexColor(arg) except: if default is None: raise 'Invalid color value', str(arg) return default |
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 isinstance(s,Color): return s except: pass try: return HexColor(arg) except: if default is None: raise 'Invalid color value', str(arg) return default |
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 rl_config.defaultPageSize if encoding is None: encoding = rl_config.defaultEncoding if invariant is None: invariant = rl_config.invariant self._filename = filename self._encodingName = encoding self._doc = pdfdoc.PDFDocument(encoding, compression=pageCompression, invariant=invariant) |
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 #RGB I suggest we should be aiming a little better cp = None dp = None sp = None if canv._pagesize: cp = map(int, canv._pagesize) if self.pagesize: sp = map(int, self.pagesize) if doc.pagesize: dp = map(int, doc.pagesize) if cp != dp: if sp: canv.setPageSize(self.pagesize) else: canv.setPageSize(doc.pagesize) |
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 #RGB I suggest we should be aiming a little better cp = None dp = None sp = None if canv._pagesize: cp = map(int, canv._pagesize) if self.pagesize: sp = map(int, self.pagesize) if doc.pagesize: dp = map(int, doc.pagesize) if cp != dp: if sp: canv.setPageSize(self.pagesize) else: canv.setPageSize(doc.pagesize) |
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" + LINEEND) # do preprocessing as needed # prepare outline outline = self.outline outline.prepare(self, canvas) for obj in self.objects: pos = f.tell() self.xref.append(pos) f.write(str(i) + ' 0 obj' + LINEEND) obj.save(f) f.write('endobj' + LINEEND) i = i + 1 self.writeXref(f) self.writeTrailer(f) f.write('%%EOF') # no lineend needed on this one! f.close() # with the Mac, we need to tag the file in a special #way so the system knows it is a PDF file. #This supplied by Joe Strout if os.name == 'mac': import macfs try: macfs.FSSpec(filename).SetCreatorType('CARO','PDF ') except: pass |
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(baseDir) path = filter(None,basDir) if noCWD: if '.' in path: path.remove('.') abspath = os.path.abspath('.') if abspath in path: path.remove(abspath) else: if '.' not in path: path.insert(0,'.') if debug: import pprint pp = pprint.pprint print 'path=',pp(path) #make import errors a bit more informative fullName = name try: (file, pathname, description) = imp.find_module(name, path) childModule = parentModule = imp.load_module(name, file, pathname, description) if debug: print 'imported module = %s' % parentModule for name in parts[1:]: fullName = fullName + '.' + name if debug: print 'trying part %s' % name (file, pathname, description) = imp.find_module(name, [os.path.dirname(parentModule.__file__)]) childModule = imp.load_module(fullName, file, pathname, description) if debug: print 'imported module = %s' % childModule setattr(parentModule, name, childModule) parentModule = childModule except ImportError: msg = "cannot import '%s' while attempting recursive import of '%s'" % (fullName, modulename) if baseDir: msg = msg + " under paths '%s'" % `path` raise ImportError, msg return childModule |
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 file location self.idToOffset = {} # number to id self.numberToId = {} cat = self.Catalog = self._catalog = PDFCatalog() pages = self.Pages = PDFPages() cat.Pages = pages outlines = self.Outlines = self.outline = PDFOutlines() cat.Outlines = outlines self.info = self.Info = PDFInfo() self.Reference(self.Catalog) self.Reference(self.Info) # make std fonts (this could be made optional self.fontMapping = {} MakeStandardEnglishFontObjects(self, encoding) |
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 file location self.idToOffset = {} # number to id self.numberToId = {} cat = self.Catalog = self._catalog = PDFCatalog() pages = self.Pages = PDFPages() cat.Pages = pages outlines = self.Outlines = self.outline = PDFOutlines() cat.Outlines = outlines self.info = self.Info = PDFInfo() self.Reference(self.Catalog) self.Reference(self.Info) # make std fonts (this could be made optional self.fontMapping = {} MakeStandardEnglishFontObjects(self, encoding) |
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.Catalog) self.Reference(self.Info) # make std fonts (this could be made optional counter = 0 # start at first object (object 1 after preincrement) ids = [] # the collection of object ids in object number order numbertoid = self.numberToId idToNV = self.idToObjectNumberAndVersion idToOb = self.idToObject idToOf = self.idToOffset ### note that new entries may be "appended" DURING FORMATTING done = None File = PDFFile() # output collector while done is None: counter = counter+1 # do next object... if numbertoid.has_key(counter): id = numbertoid[counter] #printidToOb obj = idToOb[id] IO = PDFIndirectObject(id, obj) IOf = IO.format(self) # add a comment to the PDF output if DoComments: File.add("%% %s %s %s" % (repr(id), repr(repr(obj)[:50]), LINEEND)) offset = File.add(IOf) idToOf[id] = offset ids.append(id) else: done = 1 # sanity checks (must happen AFTER formatting) lno = len(numbertoid) if counter-1!=lno: raise ValueError, "counter %s doesn't match number to id dictionary %s" %(counter, lno) # now add the xref xref = PDFCrossReferenceTable() xref.addsection(0, ids) xreff = xref.format(self) xrefoffset = File.add(xreff) # now add the trailer trailer = PDFTrailer( startxref = xrefoffset, Size = lno, Root = self.Reference(cat), Info = self.Reference(info) ) trailerf = trailer.format(self) File.add(trailerf) # return string format for pdf file return File.format(self) |
|
''' | 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 not stream: self.Contents = teststream() else: S = PDFStream() S.content = stream # need to add filter stuff (?) S.__Comment__ = "xobject form stream" self.Contents = S if not self.Resources: resources = PDFResourceDictionary() # fonts! resources.basicFonts() if self.hasImages: resources.allProcs() else: resources.basicProcs() sdict = self.Contents.dictionary sdict["Type"] = PDFName("XObject") sdict["Subtype"] = PDFName("Form") sdict["FormType"] = 1 sdict["BBox"] = self.BBox sdict["Matrix"] = self.Matrix sdict["Resources"] = resources return self.Contents.format(document) |
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.handle_data(c) self._pop(greek=1) |
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(obj, oldKey, obj.contents[pos]) return obj | 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:%[email protected]:/cvsroot/reportlab' % USER if release: do_exec(cvs+(' export -r %s %s' % (tagname,projdir)), 'the export phase') else: do_exec(cvs+' co %s' % projdir, 'the checkout phase') if py2pdf: # now we need to move the files & delete those we don't need dst = py2pdf_dir recursive_rmdir(dst) os.mkdir(dst) do_exec("mv reportlab/demos/py2pdf/py2pdf.py %s"%dst, "mv py2pdf.py") do_exec("mv reportlab/demos/py2pdf/PyFontify.py %s" % dst, "mv pyfontify.py") do_exec("mv reportlab/demos/py2pdf/idle_print.py %s" % dst, "mv idle_print.py") do_exec("rm -r reportlab/demos reportlab/platypus reportlab/lib/styles.py reportlab/README.pdfgen.txt reportlab/pdfgen/test", "rm") do_exec("mv %s %s" % (projdir,dst), "moving %s to %s" %(projdir,py2pdf_dir)) do_exec("chmod a+x %s/py2pdf.py %s/idle_print.py" % (dst, dst), "chmod") CVS_remove(dst) |
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.path.splitext(os.path.basename(_testmodulename))[0] |
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> <body> <h1>renderPM results of output</h1> """ htmlBottom = """</body> </html> """ html = [htmlTop] |
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.listdir(cwd) exed = os.path.abspath(os.path.dirname(sys.argv[0])) store.update({ 'gmt': time.asctime(time.gmtime(time.time())), 'platform': sys.platform, 'version': sys.version, 'executable': sys.executable, 'prefix': sys.prefix, 'path': sys.path, 'argv': sys.argv, 'cwd': cwd, 'hostname': socket.gethostname(), 'lcwd': lcwd, }) if exed!=cwd: store.update({'exed': exed, 'lexed': os.listdir(exed), }) if hasattr(os,'uname'): store.update({ 'uname': os.uname(), 'ctermid': os.ctermid(), 'getgid': os.getgid(), 'getuid': os.getuid(), 'getegid': os.getegid(), 'geteuid': os.geteuid(), 'getlogin': os.getlogin(), 'getgroups': os.getgroups(), 'getpgrp': os.getpgrp(), 'getpid': os.getpid(), 'getppid': os.getppid(), }) if getScript: fn = os.path.abspath(sys.argv[0]) if os.path.isfile(fn): store['__script'] = open(fn,'r').read() module_versions = {} for n,m in sys.modules.items(): if n=='reportlab' or n=='rlextra' or n[:10]=='reportlab.' or n[:8]=='rlextra.': v = getattr(m,'__version__',None) if v: module_versions[n] = v store['__module_versions'] = module_versions self.store['__payload'] = {} self._add(kw) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.