def getTypeFace(faceName): """Lazily construct known typefaces if not found""" try: return _typefaces[faceName] except KeyError: # not found, construct it if known if faceName in standardFonts: face = TypeFace(faceName) (face.familyName, face.bold, face.italic) = _fontdata.standardFontAttributes[faceName] registerTypeFace(face) ## print 'auto-constructing type face %s with family=%s, bold=%d, italic=%d' % ( ## face.name, face.familyName, face.bold, face.italic) return face else: #try a brute force search afm = bruteForceSearchForAFM(faceName) if afm: for e in ('.pfb', '.PFB'): pfb = os.path.splitext(afm)[0] + e if rl_isfile(pfb): break assert rl_isfile(pfb), 'file %s not found!' % pfb face = EmbeddedType1Face(afm, pfb) registerTypeFace(face) return face else: raise
def test2(self): "try under a well known directory NOT on the path" from reportlab.lib.testutils import testsFolder D = os.path.join(testsFolder,'..','tools','pythonpoint') fn = os.path.join(D,'stdparser.py') if rl_isfile(fn) or rl_isfile(fn+'c') or rl_isfile(fn+'o'): m1 = recursiveImport('stdparser', baseDir=D)
def findT1File(self, ext='.pfb'): possible_exts = (ext.lower(), ext.upper()) if hasattr(self,'pfbFileName'): r_basename = os.path.splitext(self.pfbFileName)[0] for e in possible_exts: if rl_isfile(r_basename + e): return r_basename + e try: r = _fontdata.findT1File(self.name) except: afm = bruteForceSearchForAFM(self.name) if afm: if ext.lower() == '.pfb': for e in possible_exts: pfb = os.path.splitext(afm)[0] + e if rl_isfile(pfb): r = pfb else: r = None elif ext.lower() == '.afm': r = afm else: r = None if r is None: warnOnce("Can't find %s for face '%s'" % (ext, self.name)) return r
def test2(self): "try under a well known directory NOT on the path" from reportlab.lib.testutils import testsFolder D = os.path.join(testsFolder, '..', 'tools', 'pythonpoint') fn = os.path.join(D, 'stdparser.py') if rl_isfile(fn) or rl_isfile(fn + 'c') or rl_isfile(fn + 'o'): m1 = recursiveImport('stdparser', baseDir=D)
def test2(self): "try under a well known directory NOT on the path" from reportlab.lib.testutils import testsFolder D = os.path.join(testsFolder, "..", "tools", "pythonpoint") fn = os.path.join(D, "stdparser.py") if rl_isfile(fn) or rl_isfile(fn + "c") or rl_isfile(fn + "o"): m1 = recursiveImport("stdparser", baseDir=D)
def bruteForceSearchForFile(fn,searchPath=None): if searchPath is None: from reportlab.rl_config import T1SearchPath as searchPath if rl_isfile(fn): return fn bfn = os.path.basename(fn) for dirname in searchPath: if not rl_isdir(dirname): continue tfn = os.path.join(dirname,bfn) if rl_isfile(tfn): return tfn return fn
def _processPackageDir(p,dn,P,allowCompiled=True): if _ofile: print('searching package', p, 'dn=',dn, file=_ofile) from reportlab.lib.utils import rl_glob, rl_isfile, rl_isdir, isCompactDistro if isCompactDistro(): ext = '.pyc' init = '__init__'+ext FN = [normpath(x) for x in rl_glob(path_join(dn,'*'))] D = [] dn = normpath(dn) for x in FN: x = path_dirname(x) if x not in D and rl_isdir(x) and path_dirname(x)==dn and rl_isfile(path_join(x,init)): D.append(x) F = [x for x in FN if x.endswith(ext) and path_dirname(x)==dn and not path_basename(x).startswith('__init__.')] else: ext = '.py' init = '__init__'+ext FN = [path_join(dn,x) for x in os.listdir(dn)] D = [x for x in FN if path_isdir(x) and isPyFile(path_join(x,init))] F = [x for x in FN if (x.endswith(ext) or (allowCompiled and (x.endswith(ext+'c') or x.endswith(ext+'o')))) and not path_basename(x).startswith('__init__.')] for f in F: mn = path_splitext(path_basename(f))[0] if p: mn = p+'.'+mn if mn not in P: if _ofile: print('appending 1',mn, file=_ofile) P.append(mn) for f in D: mn = p+('.'+path_basename(f)) if mn not in P: if _ofile: print('appending 2',mn, file=_ofile) P.append(mn)
def _searchT1Dirs(n, rl_isfile=rl_isfile, T1SearchPath=T1SearchPath): assert T1SearchPath != [], "No Type-1 font search path" for d in T1SearchPath: f = os.path.join(d, n) if rl_isfile(f): return f return None
def validate(rawdata): global _pyRXP_Parser if not _pyRXP_Parser: try: import pyRXP except ImportError: return from reportlab.lib.utils import open_and_read, rl_isfile dtd = 'pythonpoint.dtd' if not rl_isfile(dtd): dtd = os.path.join(toolsDir(),'pythonpoint','pythonpoint.dtd') if not rl_isfile(dtd): return def eocb(URI,dtdText=open_and_read(dtd),dtd=dtd): if os.path.basename(URI)=='pythonpoint.dtd': return dtd,dtdText return URI _pyRXP_Parser = pyRXP.Parser(eoCB=eocb) return _pyRXP_Parser.parse(rawdata)
def eoCB(s,targets=targets,dtdDirs=dtdDirs): from reportlab.lib.utils import open_and_read, rl_isfile bn = os.path.basename(s) if bn in targets: for d in dtdDirs: fn = os.path.join(d,bn) if rl_isfile(fn): return fn, open_and_read(fn,'t') return s
def eoCB(s, targets=targets, dtdDirs=dtdDirs): from reportlab.lib.utils import open_and_read, rl_isfile bn = os.path.basename(s) if bn in targets: for d in dtdDirs: fn = os.path.join(d, bn) if rl_isfile(fn): return fn, open_and_read(fn, 't') return s
def test(self): from reportlab.lib.testutils import testsFolder from reportlab.lib.utils import rl_isfile imageFileName = os.path.join(testsFolder,'pythonpowered.gif') assert rl_isfile(imageFileName), "%s not found!" % imageFileName ir = ImageReader(imageFileName) assert ir.getSize() == (110,44) pixels = ir.getRGBData() assert md5(pixels).hexdigest() == '02e000bf3ffcefe9fc9660c95d7e27cf'
def test(self): from reportlab.lib.testutils import testsFolder from reportlab.lib.utils import rl_isfile imageFileName = os.path.join(testsFolder, 'pythonpowered.gif') assert rl_isfile(imageFileName), "%s not found!" % imageFileName ir = ImageReader(imageFileName) assert ir.getSize() == (110, 44) pixels = ir.getRGBData() assert md5(pixels).hexdigest() == '02e000bf3ffcefe9fc9660c95d7e27cf'
def test(self): import reportlab.test from reportlab.lib.utils import rl_isfile imageFileName = os.path.dirname(reportlab.test.__file__) + os.sep + 'pythonpowered.gif' assert rl_isfile(imageFileName), "%s not found!" % imageFileName ir = ImageReader(imageFileName) assert ir.getSize() == (110,44) pixels = ir.getRGBData() assert md5.md5(pixels).hexdigest() == '02e000bf3ffcefe9fc9660c95d7e27cf'
def _loadGlyphs(self, pfbFileName): """Loads in binary glyph data, and finds the four length measurements needed for the font descriptor""" assert rl_isfile(pfbFileName), 'file %s not found' % pfbFileName d = open_and_read(pfbFileName, 'b') s1, l1 = _pfbCheck(0,d,PFB_ASCII,pfbFileName) s2, l2 = _pfbCheck(l1,d,PFB_BINARY,pfbFileName) s3, l3 = _pfbCheck(l2,d,PFB_ASCII,pfbFileName) _pfbCheck(l3,d,PFB_EOF,pfbFileName) self._binaryData = d[s1:l1]+d[s2:l2]+d[s3:l3] self._length = len(self._binaryData) self._length1 = l1-s1 self._length2 = l2-s2 self._length3 = l3-s3
def _loadGlyphs(self, pfbFileName): """Loads in binary glyph data, and finds the four length measurements needed for the font descriptor""" pfbFileName = bruteForceSearchForFile(pfbFileName) assert rl_isfile(pfbFileName), 'file %s not found' % pfbFileName d = open_and_read(pfbFileName, 'b') s1, l1 = _pfbCheck(0,d,PFB_ASCII,pfbFileName) s2, l2 = _pfbCheck(l1,d,PFB_BINARY,pfbFileName) s3, l3 = _pfbCheck(l2,d,PFB_ASCII,pfbFileName) _pfbCheck(l3,d,PFB_EOF,pfbFileName) self._binaryData = d[s1:l1]+d[s2:l2]+d[s3:l3] self._length = len(self._binaryData) self._length1 = l1-s1 self._length2 = l2-s2 self._length3 = l3-s3
def TTFOpenFile(fn): '''Opens a TTF file possibly after searching TTFSearchPath returns (filename,file) ''' from reportlab.lib.utils import rl_isfile, open_for_read try: f = open_for_read(fn, 'rb') return fn, f except IOError: import os if not os.path.isabs(fn): for D in rl_config.TTFSearchPath: tfn = os.path.join(D, fn) if rl_isfile(tfn): f = open_for_read(tfn, 'rb') return tfn, f raise TTFError('Can\'t open file "%s"' % fn)
def TTFOpenFile(fn): '''Opens a TTF file possibly after searching TTFSearchPath returns (filename,file) ''' from reportlab.lib.utils import rl_isfile, open_for_read try: f = open_for_read(fn,'rb') return fn, f except IOError: import os if not os.path.isabs(fn): for D in rl_config.TTFSearchPath: tfn = os.path.join(D,fn) if rl_isfile(tfn): f = open_for_read(tfn,'rb') return tfn, f raise TTFError('Can\'t open file "%s"' % fn)
def _processPackageDir(p, dn, P, allowCompiled=True): if _ofile: print('searching package', p, 'dn=', dn, file=_ofile) from reportlab.lib.utils import rl_glob, rl_isfile, rl_isdir, isCompactDistro if isCompactDistro(): ext = '.pyc' init = '__init__' + ext FN = [normpath(x) for x in rl_glob(path_join(dn, '*'))] D = [] dn = normpath(dn) for x in FN: x = path_dirname(x) if x not in D and rl_isdir(x) and path_dirname( x) == dn and rl_isfile(path_join(x, init)): D.append(x) F = [ x for x in FN if x.endswith(ext) and path_dirname(x) == dn and not path_basename(x).startswith('__init__.') ] else: ext = '.py' init = '__init__' + ext FN = [path_join(dn, x) for x in os.listdir(dn)] D = [x for x in FN if path_isdir(x) and isPyFile(path_join(x, init))] F = [ x for x in FN if (x.endswith(ext) or (allowCompiled and ( x.endswith(ext + 'c') or x.endswith(ext + 'o')))) and not path_basename(x).startswith('__init__.') ] for f in F: mn = path_splitext(path_basename(f))[0] if p: mn = p + '.' + mn if mn not in P: if _ofile: print('appending 1', mn, file=_ofile) P.append(mn) for f in D: mn = p + ('.' + path_basename(f)) if mn not in P: if _ofile: print('appending 2', mn, file=_ofile) P.append(mn)
def _searchT1Dirs(n,rl_isfile=rl_isfile,T1SearchPath=T1SearchPath): assert T1SearchPath!=[], "No Type-1 font search path" for d in T1SearchPath: f = os.path.join(d,n) if rl_isfile(f): return f return None
def test2(self): "try under a well known directory NOT on the path" D = os.path.join(os.path.dirname(reportlab.__file__), "tools", "pythonpoint") fn = os.path.join(D, "stdparser.py") if rl_isfile(fn) or rl_isfile(fn + "c") or rl_isfile(fn + "o"): m1 = recursiveImport("stdparser", baseDir=D)
def makeDocument(filename, pageCallBack=None): #the extra arg is a hack added later, so other #tests can get hold of the canvas just before it is #saved c = pycanvas.Canvas(filename) c.setPageCompression(0) c.setPageCallBack(pageCallBack) framePageForm(c) # define the frame form c.showOutline() framePage(c, 'PDFgen graphics API test script') makesubsection(c, "PDFgen and PIDDLE", 10 * inch) t = c.beginText(inch, 10 * inch) t.setFont('Times-Roman', 10) drawCrossHairs(c, t.getX(), t.getY()) t.textLines(""" The ReportLab library permits you to create PDF documents directly from your Python code. The "pdfgen" subpackage is the lowest level exposed to the user and lets you directly position test and graphics on the page, with access to almost the full range of PDF features. The API is intended to closely mirror the PDF / Postscript imaging model. There is an almost one to one correspondence between commands and PDF operators. However, where PDF provides several ways to do a job, we have generally only picked one. The test script attempts to use all of the methods exposed by the Canvas class, defined in reportlab/pdfgen/canvas.py First, let's look at text output. There are some basic commands to draw strings: - canvas.setFont(fontname, fontsize [, leading]) - canvas.drawString(x, y, text) - canvas.drawRightString(x, y, text) - canvas.drawCentredString(x, y, text) The coordinates are in points starting at the bottom left corner of the page. When setting a font, the leading (i.e. inter-line spacing) defaults to 1.2 * fontsize if the fontsize is not provided. For more sophisticated operations, you can create a Text Object, defined in reportlab/pdfgen/testobject.py. Text objects produce tighter PDF, run faster and have many methods for precise control of spacing and position. Basic usage goes as follows: - tx = canvas.beginText(x, y) - tx.textOut('Hello') # this moves the cursor to the right - tx.textLine('Hello again') # prints a line and moves down - y = tx.getY() # getX, getY and getCursor track position - canvas.drawText(tx) # all gets drawn at the end The green crosshairs below test whether the text cursor is working properly. They should appear at the bottom left of each relevant substring. """) t.setFillColorRGB(1, 0, 0) t.setTextOrigin(inch, 4 * inch) drawCrossHairs(c, t.getX(), t.getY()) t.textOut('textOut moves across:') drawCrossHairs(c, t.getX(), t.getY()) t.textOut('textOut moves across:') drawCrossHairs(c, t.getX(), t.getY()) t.textOut('textOut moves across:') drawCrossHairs(c, t.getX(), t.getY()) t.textLine('') drawCrossHairs(c, t.getX(), t.getY()) t.textLine('textLine moves down') drawCrossHairs(c, t.getX(), t.getY()) t.textLine('textLine moves down') drawCrossHairs(c, t.getX(), t.getY()) t.textLine('textLine moves down') drawCrossHairs(c, t.getX(), t.getY()) t.setTextOrigin(4 * inch, 3.25 * inch) drawCrossHairs(c, t.getX(), t.getY()) t.textLines( 'This is a multi-line\nstring with embedded newlines\ndrawn with textLines().\n' ) drawCrossHairs(c, t.getX(), t.getY()) t.textLines(['This is a list of strings', 'drawn with textLines().']) c.drawText(t) t = c.beginText(2 * inch, 2 * inch) t.setFont('Times-Roman', 10) drawCrossHairs(c, t.getX(), t.getY()) t.textOut('Small text.') drawCrossHairs(c, t.getX(), t.getY()) t.setFont('Courier', 14) t.textOut('Bigger fixed width text.') drawCrossHairs(c, t.getX(), t.getY()) t.setFont('Times-Roman', 10) t.textOut('Small text again.') drawCrossHairs(c, t.getX(), t.getY()) c.drawText(t) #mark the cursor where it stopped c.showPage() ############################################################## # # page 2 - line styles # ############################################################### #page 2 - lines and styles framePage(c, 'Line Drawing Styles') # three line ends, lines drawn the hard way #firt make some vertical end markers c.setDash(4, 4) c.setLineWidth(0) c.line(inch, 9.2 * inch, inch, 7.8 * inch) c.line(3 * inch, 9.2 * inch, 3 * inch, 7.8 * inch) c.setDash() #clears it c.setLineWidth(5) c.setLineCap(0) p = c.beginPath() p.moveTo(inch, 9 * inch) p.lineTo(3 * inch, 9 * inch) c.drawPath(p) c.drawString(4 * inch, 9 * inch, 'the default - butt caps project half a width') makesubsection(c, "caps and joins", 8.5 * inch) c.setLineCap(1) p = c.beginPath() p.moveTo(inch, 8.5 * inch) p.lineTo(3 * inch, 8.5 * inch) c.drawPath(p) c.drawString(4 * inch, 8.5 * inch, 'round caps') c.setLineCap(2) p = c.beginPath() p.moveTo(inch, 8 * inch) p.lineTo(3 * inch, 8 * inch) c.drawPath(p) c.drawString(4 * inch, 8 * inch, 'square caps') c.setLineCap(0) # three line joins c.setLineJoin(0) p = c.beginPath() p.moveTo(inch, 7 * inch) p.lineTo(2 * inch, 7 * inch) p.lineTo(inch, 6.7 * inch) c.drawPath(p) c.drawString(4 * inch, 6.8 * inch, 'Default - mitered join') c.setLineJoin(1) p = c.beginPath() p.moveTo(inch, 6.5 * inch) p.lineTo(2 * inch, 6.5 * inch) p.lineTo(inch, 6.2 * inch) c.drawPath(p) c.drawString(4 * inch, 6.3 * inch, 'round join') c.setLineJoin(2) p = c.beginPath() p.moveTo(inch, 6 * inch) p.lineTo(2 * inch, 6 * inch) p.lineTo(inch, 5.7 * inch) c.drawPath(p) c.drawString(4 * inch, 5.8 * inch, 'bevel join') c.setDash(6, 6) p = c.beginPath() p.moveTo(inch, 5 * inch) p.lineTo(3 * inch, 5 * inch) c.drawPath(p) c.drawString(4 * inch, 5 * inch, 'dash 6 points on, 6 off- setDash(6,6) setLineCap(0)') makesubsection(c, "dash patterns", 5 * inch) c.setLineCap(1) p = c.beginPath() p.moveTo(inch, 4.5 * inch) p.lineTo(3 * inch, 4.5 * inch) c.drawPath(p) c.drawString(4 * inch, 4.5 * inch, 'dash 6 points on, 6 off- setDash(6,6) setLineCap(1)') c.setLineCap(0) c.setDash([1, 2, 3, 4, 5, 6], 0) p = c.beginPath() p.moveTo(inch, 4.0 * inch) p.lineTo(3 * inch, 4.0 * inch) c.drawPath(p) c.drawString(4 * inch, 4 * inch, 'dash growing - setDash([1,2,3,4,5,6],0) setLineCap(0)') c.setLineCap(1) c.setLineJoin(1) c.setDash(32, 12) p = c.beginPath() p.moveTo(inch, 3.0 * inch) p.lineTo(2.5 * inch, 3.0 * inch) p.lineTo(inch, 2 * inch) c.drawPath(p) c.drawString(4 * inch, 3 * inch, 'dash pattern, join and cap style interacting - ') c.drawString(4 * inch, 3 * inch - 12, 'round join & miter results in sausages') c.showPage() ############################################################## # # higher level shapes # ############################################################### framePage(c, 'Shape Drawing Routines') t = c.beginText(inch, 10 * inch) t.textLines(""" Rather than making your own paths, you have access to a range of shape routines. These are built in pdfgen out of lines and bezier curves, but use the most compact set of operators possible. We can add any new ones that are of general use at no cost to performance.""") t.textLine() #line demo makesubsection(c, "lines", 10 * inch) c.line(inch, 8 * inch, 3 * inch, 8 * inch) t.setTextOrigin(4 * inch, 8 * inch) t.textLine('canvas.line(x1, y1, x2, y2)') #bezier demo - show control points makesubsection(c, "bezier curves", 7.5 * inch) (x1, y1, x2, y2, x3, y3, x4, y4) = (inch, 6.5 * inch, 1.2 * inch, 7.5 * inch, 3 * inch, 7.5 * inch, 3.5 * inch, 6.75 * inch) c.bezier(x1, y1, x2, y2, x3, y3, x4, y4) c.setDash(3, 3) c.line(x1, y1, x2, y2) c.line(x3, y3, x4, y4) c.setDash() t.setTextOrigin(4 * inch, 7 * inch) t.textLine('canvas.bezier(x1, y1, x2, y2, x3, y3, x4, y4)') #rectangle makesubsection(c, "rectangles", 7 * inch) c.rect(inch, 5.25 * inch, 2 * inch, 0.75 * inch) t.setTextOrigin(4 * inch, 5.5 * inch) t.textLine('canvas.rect(x, y, width, height) - x,y is lower left') #wedge makesubsection(c, "wedges", 5 * inch) c.wedge(inch, 5 * inch, 3 * inch, 4 * inch, 0, 315) t.setTextOrigin(4 * inch, 4.5 * inch) t.textLine('canvas.wedge(x1, y1, x2, y2, startDeg, extentDeg)') t.textLine('Note that this is an elliptical arc, not just circular!') #wedge the other way c.wedge(inch, 4 * inch, 3 * inch, 3 * inch, 0, -45) t.setTextOrigin(4 * inch, 3.5 * inch) t.textLine('Use a negative extent to go clockwise') #circle makesubsection(c, "circles", 3.5 * inch) c.circle(1.5 * inch, 2 * inch, 0.5 * inch) c.circle(3 * inch, 2 * inch, 0.5 * inch) t.setTextOrigin(4 * inch, 2 * inch) t.textLine('canvas.circle(x, y, radius)') c.drawText(t) c.showPage() ############################################################## # # Page 4 - fonts # ############################################################### framePage(c, "Font Control") c.drawString(inch, 10 * inch, 'Listing available fonts...') y = 9.5 * inch for fontname in c.getAvailableFonts(): c.setFont(fontname, 24) c.drawString(inch, y, 'This should be %s' % fontname) y = y - 28 makesubsection(c, "fonts and colors", 4 * inch) c.setFont('Times-Roman', 12) t = c.beginText(inch, 4 * inch) t.textLines("""Now we'll look at the color functions and how they interact with the text. In theory, a word is just a shape; so setFillColorRGB() determines most of what you see. If you specify other text rendering modes, an outline color could be defined by setStrokeColorRGB() too""") c.drawText(t) t = c.beginText(inch, 2.75 * inch) t.setFont('Times-Bold', 36) t.setFillColor(colors.green) #green t.textLine('Green fill, no stroke') #t.setStrokeColorRGB(1,0,0) #ou can do this in a text object, or the canvas. t.setStrokeColor( colors.red) #ou can do this in a text object, or the canvas. t.setTextRenderMode(2) # fill and stroke t.textLine('Green fill, red stroke - yuk!') t.setTextRenderMode(0) # back to default - fill only t.setFillColorRGB(0, 0, 0) #back to default t.setStrokeColorRGB(0, 0, 0) #ditto c.drawText(t) c.showPage() ######################################################################### # # Page 5 - coord transforms # ######################################################################### framePage(c, "Coordinate Transforms") c.setFont('Times-Roman', 12) t = c.beginText(inch, 10 * inch) t.textLines( """This shows coordinate transformations. We draw a set of axes, moving down the page and transforming space before each one. You can use saveState() and restoreState() to unroll transformations. Note that functions which track the text cursor give the cursor position in the current coordinate system; so if you set up a 6 inch high frame 2 inches down the page to draw text in, and move the origin to its top left, you should stop writing text after six inches and not eight.""") c.drawText(t) drawAxes(c, "0. at origin") c.addLiteral('%about to translate space') c.translate(2 * inch, 7 * inch) drawAxes(c, '1. translate near top of page') c.saveState() c.translate(1 * inch, -2 * inch) drawAxes(c, '2. down 2 inches, across 1') c.restoreState() c.saveState() c.translate(0, -3 * inch) c.scale(2, -1) drawAxes(c, '3. down 3 from top, scale (2, -1)') c.restoreState() c.saveState() c.translate(0, -5 * inch) c.rotate(-30) drawAxes(c, "4. down 5, rotate 30' anticlockwise") c.restoreState() c.saveState() c.translate(3 * inch, -5 * inch) c.skew(0, 30) drawAxes(c, "5. down 5, 3 across, skew beta 30") c.restoreState() c.showPage() ######################################################################### # # Page 6 - clipping # ######################################################################### framePage(c, "Clipping") c.setFont('Times-Roman', 12) t = c.beginText(inch, 10 * inch) t.textLines( """This shows clipping at work. We draw a chequerboard of rectangles into a path object, and clip it. This then forms a mask which limits the region of the page on which one can draw. This paragraph was drawn after setting the clipping path, and so you should only see part of the text.""") c.drawText(t) c.saveState() #c.setFillColorRGB(0,0,1) p = c.beginPath() #make a chesboard effect, 1 cm squares for i in range(14): x0 = (3 + i) * cm for j in range(7): y0 = (16 + j) * cm p.rect(x0, y0, 0.85 * cm, 0.85 * cm) c.addLiteral('%Begin clip path') c.clipPath(p) c.addLiteral('%End clip path') t = c.beginText(3 * cm, 22.5 * cm) t.textLines( """This shows clipping at work. We draw a chequerboard of rectangles into a path object, and clip it. This then forms a mask which limits the region of the page on which one can draw. This paragraph was drawn after setting the clipping path, and so you should only see part of the text. This shows clipping at work. We draw a chequerboard of rectangles into a path object, and clip it. This then forms a mask which limits the region of the page on which one can draw. This paragraph was drawn after setting the clipping path, and so you should only see part of the text. This shows clipping at work. We draw a chequerboard of rectangles into a path object, and clip it. This then forms a mask which limits the region of the page on which one can draw. This paragraph was drawn after setting the clipping path, and so you should only see part of the text.""") c.drawText(t) c.restoreState() t = c.beginText(inch, 5 * inch) t.textLines( """You can also use text as an outline for clipping with the text render mode. The API is not particularly clean on this and one has to follow the right sequence; this can be optimized shortly.""") c.drawText(t) #first the outline c.saveState() t = c.beginText(inch, 3.0 * inch) t.setFont('Helvetica-BoldOblique', 108) t.setTextRenderMode(5) #stroke and add to path t.textLine('Python!') t.setTextRenderMode(0) c.drawText(t) #this will make a clipping mask #now some small stuff which wil be drawn into the current clip mask t = c.beginText(inch, 4 * inch) t.setFont('Times-Roman', 6) t.textLines((('spam ' * 40) + '\n') * 15) c.drawText(t) #now reset canvas to get rid of the clipping mask c.restoreState() c.showPage() ######################################################################### # # Page 7 - images # ######################################################################### framePage(c, "Images") c.setFont('Times-Roman', 12) t = c.beginText(inch, 10 * inch) if not haveImages: c.drawString( inch, 11 * inch, "Python Imaging Library not found! Below you see rectangles instead of images." ) t.textLines( """PDFgen uses the Python Imaging Library to process a very wide variety of image formats. This page shows image capabilities. If I've done things right, the bitmap should have its bottom left corner aligned with the crosshairs. There are two methods for drawing images. The recommended use is to call drawImage. This produces the smallest PDFs and the fastest generation times as each image's binary data is only embedded once in the file. Also you can use advanced features like transparency masks. You can also use drawInlineImage, which puts images in the page stream directly. This is slightly faster for Acrobat to render or for very small images, but wastes space if you use images more than once.""") c.drawText(t) import tests from reportlab.lib.testutils import testsFolder gif = os.path.join(testsFolder, 'pythonpowered.gif') if haveImages and rl_isfile(gif): c.drawInlineImage(gif, 2 * inch, 7 * inch) else: c.rect(2 * inch, 7 * inch, 110, 44) c.line(1.5 * inch, 7 * inch, 4 * inch, 7 * inch) c.line(2 * inch, 6.5 * inch, 2 * inch, 8 * inch) c.drawString(4.5 * inch, 7.25 * inch, 'inline image drawn at natural size') if haveImages and rl_isfile(gif): c.drawInlineImage(gif, 2 * inch, 5 * inch, inch, inch) else: c.rect(2 * inch, 5 * inch, inch, inch) c.line(1.5 * inch, 5 * inch, 4 * inch, 5 * inch) c.line(2 * inch, 4.5 * inch, 2 * inch, 6 * inch) c.drawString(4.5 * inch, 5.25 * inch, 'inline image distorted to fit box') c.drawString( 1.5 * inch, 4 * inch, 'Image XObjects can be defined once in the file and drawn many times.') c.drawString(1.5 * inch, 3.75 * inch, 'This results in faster generation and much smaller files.') for i in range(5): if haveImages: (w, h) = c.drawImage(gif, (1.5 + i) * inch, 3 * inch) else: c.rect((1.5 + i) * inch, 3 * inch, 110, 44) myMask = [254, 255, 222, 223, 0, 1] c.drawString( 1.5 * inch, 2.5 * inch, "The optional 'mask' parameter lets you define transparent colors. We used a color picker" ) c.drawString( 1.5 * inch, 2.3 * inch, "to determine that the yellow in the image above is RGB=(225,223,0). We then define a mask" ) c.drawString( 1.5 * inch, 2.1 * inch, "spanning these RGB values: %s. The background vanishes!!" % myMask) c.drawString(2.5 * inch, 1.2 * inch, 'This would normally be obscured') if haveImages: c.drawImage(gif, 3 * inch, 1.2 * inch, w, h, mask=myMask) else: c.rect(3 * inch, 1.2 * inch, 110, 44) c.showPage() ######################################################################### # # Page 8 - Forms and simple links # ######################################################################### framePage(c, "Forms and Links") c.setFont('Times-Roman', 12) t = c.beginText(inch, 10 * inch) t.textLines("""Forms are sequences of text or graphics operations which are stored only once in a PDF file and used as many times as desired. The blue logo bar to the left is an example of a form in this document. See the function framePageForm in this demo script for an example of how to use canvas.beginForm(name, ...) ... canvas.endForm(). Documents can also contain cross references where (for example) a rectangle on a page may be bound to a position on another page. If the user clicks on the rectangle the PDF viewer moves to the bound position on the other page. There are many other types of annotations and links supported by PDF. For example, there is a bookmark to each page in this document and below is a browsable index that jumps to those pages. In addition we show two URL hyperlinks; for these, you specify a rectangle but must draw the contents or any surrounding rectangle yourself. """) c.drawText(t) nentries = len(titlelist) xmargin = 3 * inch xmax = 7 * inch ystart = 6.54 * inch ydelta = 0.4 * inch for i in range(nentries): yposition = ystart - i * ydelta title = titlelist[i] c.drawString(xmargin, yposition, title) c.linkAbsolute(title, title, (xmargin - ydelta / 4, yposition - ydelta / 4, xmax, yposition + ydelta / 2)) # test URLs r1 = (inch, 3 * inch, 5 * inch, 3.25 * inch) # this is x1,y1,x2,y2 c.linkURL('http://www.reportlab.com/', r1, thickness=1, color=colors.green) c.drawString(inch + 3, 3 * inch + 6, 'Hyperlink to www.reportlab.com, with green border') r1 = (inch, 2.5 * inch, 5 * inch, 2.75 * inch) # this is x1,y1,x2,y2 c.linkURL('mailto:[email protected]', r1) #, border=0) c.drawString(inch + 3, 2.5 * inch + 6, 'mailto: hyperlink, without border') r1 = (inch, 2 * inch, 5 * inch, 2.25 * inch) # this is x1,y1,x2,y2 c.linkURL('http://www.reportlab.com/', r1, thickness=2, dashArray=[2, 4], color=colors.magenta) c.drawString(inch + 3, 2 * inch + 6, 'Hyperlink with custom border style') ### now do stuff for the outline #for x in outlinenametree: print x #stop #c.setOutlineNames0(*outlinenametree) return c
def makeDocument(filename, pageCallBack=None): #the extra arg is a hack added later, so other #tests can get hold of the canvas just before it is #saved c = pycanvas.Canvas(filename) c.setPageCompression(0) c.setPageCallBack(pageCallBack) framePageForm(c) # define the frame form c.showOutline() framePage(c, 'PDFgen graphics API test script') makesubsection(c, "PDFgen and PIDDLE", 10*inch) t = c.beginText(inch, 10*inch) t.setFont('Times-Roman', 10) drawCrossHairs(c, t.getX(),t.getY()) t.textLines(""" The ReportLab library permits you to create PDF documents directly from your Python code. The "pdfgen" subpackage is the lowest level exposed to the user and lets you directly position test and graphics on the page, with access to almost the full range of PDF features. The API is intended to closely mirror the PDF / Postscript imaging model. There is an almost one to one correspondence between commands and PDF operators. However, where PDF provides several ways to do a job, we have generally only picked one. The test script attempts to use all of the methods exposed by the Canvas class, defined in reportlab/pdfgen/canvas.py First, let's look at text output. There are some basic commands to draw strings: - canvas.setFont(fontname, fontsize [, leading]) - canvas.drawString(x, y, text) - canvas.drawRightString(x, y, text) - canvas.drawCentredString(x, y, text) The coordinates are in points starting at the bottom left corner of the page. When setting a font, the leading (i.e. inter-line spacing) defaults to 1.2 * fontsize if the fontsize is not provided. For more sophisticated operations, you can create a Text Object, defined in reportlab/pdfgen/testobject.py. Text objects produce tighter PDF, run faster and have many methods for precise control of spacing and position. Basic usage goes as follows: - tx = canvas.beginText(x, y) - tx.textOut('Hello') # this moves the cursor to the right - tx.textLine('Hello again') # prints a line and moves down - y = tx.getY() # getX, getY and getCursor track position - canvas.drawText(tx) # all gets drawn at the end The green crosshairs below test whether the text cursor is working properly. They should appear at the bottom left of each relevant substring. """) t.setFillColorRGB(1,0,0) t.setTextOrigin(inch, 4*inch) drawCrossHairs(c, t.getX(),t.getY()) t.textOut('textOut moves across:') drawCrossHairs(c, t.getX(),t.getY()) t.textOut('textOut moves across:') drawCrossHairs(c, t.getX(),t.getY()) t.textOut('textOut moves across:') drawCrossHairs(c, t.getX(),t.getY()) t.textLine('') drawCrossHairs(c, t.getX(),t.getY()) t.textLine('textLine moves down') drawCrossHairs(c, t.getX(),t.getY()) t.textLine('textLine moves down') drawCrossHairs(c, t.getX(),t.getY()) t.textLine('textLine moves down') drawCrossHairs(c, t.getX(),t.getY()) t.setTextOrigin(4*inch,3.25*inch) drawCrossHairs(c, t.getX(),t.getY()) t.textLines('This is a multi-line\nstring with embedded newlines\ndrawn with textLines().\n') drawCrossHairs(c, t.getX(),t.getY()) t.textLines(['This is a list of strings', 'drawn with textLines().']) c.drawText(t) t = c.beginText(2*inch,2*inch) t.setFont('Times-Roman',10) drawCrossHairs(c, t.getX(),t.getY()) t.textOut('Small text.') drawCrossHairs(c, t.getX(),t.getY()) t.setFont('Courier',14) t.textOut('Bigger fixed width text.') drawCrossHairs(c, t.getX(),t.getY()) t.setFont('Times-Roman',10) t.textOut('Small text again.') drawCrossHairs(c, t.getX(),t.getY()) c.drawText(t) #mark the cursor where it stopped c.showPage() ############################################################## # # page 2 - line styles # ############################################################### #page 2 - lines and styles framePage(c, 'Line Drawing Styles') # three line ends, lines drawn the hard way #firt make some vertical end markers c.setDash(4,4) c.setLineWidth(0) c.line(inch,9.2*inch,inch, 7.8*inch) c.line(3*inch,9.2*inch,3*inch, 7.8*inch) c.setDash() #clears it c.setLineWidth(5) c.setLineCap(0) p = c.beginPath() p.moveTo(inch, 9*inch) p.lineTo(3*inch, 9*inch) c.drawPath(p) c.drawString(4*inch, 9*inch, 'the default - butt caps project half a width') makesubsection(c, "caps and joins", 8.5*inch) c.setLineCap(1) p = c.beginPath() p.moveTo(inch, 8.5*inch) p.lineTo(3*inch, 8.5*inch) c.drawPath(p) c.drawString(4*inch, 8.5*inch, 'round caps') c.setLineCap(2) p = c.beginPath() p.moveTo(inch, 8*inch) p.lineTo(3*inch, 8*inch) c.drawPath(p) c.drawString(4*inch, 8*inch, 'square caps') c.setLineCap(0) # three line joins c.setLineJoin(0) p = c.beginPath() p.moveTo(inch, 7*inch) p.lineTo(2*inch, 7*inch) p.lineTo(inch, 6.7*inch) c.drawPath(p) c.drawString(4*inch, 6.8*inch, 'Default - mitered join') c.setLineJoin(1) p = c.beginPath() p.moveTo(inch, 6.5*inch) p.lineTo(2*inch, 6.5*inch) p.lineTo(inch, 6.2*inch) c.drawPath(p) c.drawString(4*inch, 6.3*inch, 'round join') c.setLineJoin(2) p = c.beginPath() p.moveTo(inch, 6*inch) p.lineTo(2*inch, 6*inch) p.lineTo(inch, 5.7*inch) c.drawPath(p) c.drawString(4*inch, 5.8*inch, 'bevel join') c.setDash(6,6) p = c.beginPath() p.moveTo(inch, 5*inch) p.lineTo(3*inch, 5*inch) c.drawPath(p) c.drawString(4*inch, 5*inch, 'dash 6 points on, 6 off- setDash(6,6) setLineCap(0)') makesubsection(c, "dash patterns", 5*inch) c.setLineCap(1) p = c.beginPath() p.moveTo(inch, 4.5*inch) p.lineTo(3*inch, 4.5*inch) c.drawPath(p) c.drawString(4*inch, 4.5*inch, 'dash 6 points on, 6 off- setDash(6,6) setLineCap(1)') c.setLineCap(0) c.setDash([1,2,3,4,5,6],0) p = c.beginPath() p.moveTo(inch, 4.0*inch) p.lineTo(3*inch, 4.0*inch) c.drawPath(p) c.drawString(4*inch, 4*inch, 'dash growing - setDash([1,2,3,4,5,6],0) setLineCap(0)') c.setLineCap(1) c.setLineJoin(1) c.setDash(32,12) p = c.beginPath() p.moveTo(inch, 3.0*inch) p.lineTo(2.5*inch, 3.0*inch) p.lineTo(inch, 2*inch) c.drawPath(p) c.drawString(4*inch, 3*inch, 'dash pattern, join and cap style interacting - ') c.drawString(4*inch, 3*inch - 12, 'round join & miter results in sausages') c.showPage() ############################################################## # # higher level shapes # ############################################################### framePage(c, 'Shape Drawing Routines') t = c.beginText(inch, 10*inch) t.textLines(""" Rather than making your own paths, you have access to a range of shape routines. These are built in pdfgen out of lines and bezier curves, but use the most compact set of operators possible. We can add any new ones that are of general use at no cost to performance.""") t.textLine() #line demo makesubsection(c, "lines", 10*inch) c.line(inch, 8*inch, 3*inch, 8*inch) t.setTextOrigin(4*inch, 8*inch) t.textLine('canvas.line(x1, y1, x2, y2)') #bezier demo - show control points makesubsection(c, "bezier curves", 7.5*inch) (x1, y1, x2, y2, x3, y3, x4, y4) = ( inch, 6.5*inch, 1.2*inch, 7.5 * inch, 3*inch, 7.5 * inch, 3.5*inch, 6.75 * inch ) c.bezier(x1, y1, x2, y2, x3, y3, x4, y4) c.setDash(3,3) c.line(x1,y1,x2,y2) c.line(x3,y3,x4,y4) c.setDash() t.setTextOrigin(4*inch, 7 * inch) t.textLine('canvas.bezier(x1, y1, x2, y2, x3, y3, x4, y4)') #rectangle makesubsection(c, "rectangles", 7*inch) c.rect(inch, 5.25 * inch, 2 * inch, 0.75 * inch) t.setTextOrigin(4*inch, 5.5 * inch) t.textLine('canvas.rect(x, y, width, height) - x,y is lower left') #wedge makesubsection(c, "wedges", 5*inch) c.wedge(inch, 5*inch, 3*inch, 4*inch, 0, 315) t.setTextOrigin(4*inch, 4.5 * inch) t.textLine('canvas.wedge(x1, y1, x2, y2, startDeg, extentDeg)') t.textLine('Note that this is an elliptical arc, not just circular!') #wedge the other way c.wedge(inch, 4*inch, 3*inch, 3*inch, 0, -45) t.setTextOrigin(4*inch, 3.5 * inch) t.textLine('Use a negative extent to go clockwise') #circle makesubsection(c, "circles", 3.5*inch) c.circle(1.5*inch, 2*inch, 0.5 * inch) c.circle(3*inch, 2*inch, 0.5 * inch) t.setTextOrigin(4*inch, 2 * inch) t.textLine('canvas.circle(x, y, radius)') c.drawText(t) c.showPage() ############################################################## # # Page 4 - fonts # ############################################################### framePage(c, "Font Control") c.drawString(inch, 10*inch, 'Listing available fonts...') y = 9.5*inch for fontname in c.getAvailableFonts(): c.setFont(fontname,24) c.drawString(inch, y, 'This should be %s' % fontname) y = y - 28 makesubsection(c, "fonts and colors", 4*inch) c.setFont('Times-Roman', 12) t = c.beginText(inch, 4*inch) t.textLines("""Now we'll look at the color functions and how they interact with the text. In theory, a word is just a shape; so setFillColorRGB() determines most of what you see. If you specify other text rendering modes, an outline color could be defined by setStrokeColorRGB() too""") c.drawText(t) t = c.beginText(inch, 2.75 * inch) t.setFont('Times-Bold',36) t.setFillColor(colors.green) #green t.textLine('Green fill, no stroke') #t.setStrokeColorRGB(1,0,0) #ou can do this in a text object, or the canvas. t.setStrokeColor(colors.red) #ou can do this in a text object, or the canvas. t.setTextRenderMode(2) # fill and stroke t.textLine('Green fill, red stroke - yuk!') t.setTextRenderMode(0) # back to default - fill only t.setFillColorRGB(0,0,0) #back to default t.setStrokeColorRGB(0,0,0) #ditto c.drawText(t) c.showPage() ######################################################################### # # Page 5 - coord transforms # ######################################################################### framePage(c, "Coordinate Transforms") c.setFont('Times-Roman', 12) t = c.beginText(inch, 10 * inch) t.textLines("""This shows coordinate transformations. We draw a set of axes, moving down the page and transforming space before each one. You can use saveState() and restoreState() to unroll transformations. Note that functions which track the text cursor give the cursor position in the current coordinate system; so if you set up a 6 inch high frame 2 inches down the page to draw text in, and move the origin to its top left, you should stop writing text after six inches and not eight.""") c.drawText(t) drawAxes(c, "0. at origin") c.addLiteral('%about to translate space') c.translate(2*inch, 7 * inch) drawAxes(c, '1. translate near top of page') c.saveState() c.translate(1*inch, -2 * inch) drawAxes(c, '2. down 2 inches, across 1') c.restoreState() c.saveState() c.translate(0, -3 * inch) c.scale(2, -1) drawAxes(c, '3. down 3 from top, scale (2, -1)') c.restoreState() c.saveState() c.translate(0, -5 * inch) c.rotate(-30) drawAxes(c, "4. down 5, rotate 30' anticlockwise") c.restoreState() c.saveState() c.translate(3 * inch, -5 * inch) c.skew(0,30) drawAxes(c, "5. down 5, 3 across, skew beta 30") c.restoreState() c.showPage() ######################################################################### # # Page 6 - clipping # ######################################################################### framePage(c, "Clipping") c.setFont('Times-Roman', 12) t = c.beginText(inch, 10 * inch) t.textLines("""This shows clipping at work. We draw a chequerboard of rectangles into a path object, and clip it. This then forms a mask which limits the region of the page on which one can draw. This paragraph was drawn after setting the clipping path, and so you should only see part of the text.""") c.drawText(t) c.saveState() #c.setFillColorRGB(0,0,1) p = c.beginPath() #make a chesboard effect, 1 cm squares for i in range(14): x0 = (3 + i) * cm for j in range(7): y0 = (16 + j) * cm p.rect(x0, y0, 0.85*cm, 0.85*cm) c.addLiteral('%Begin clip path') c.clipPath(p) c.addLiteral('%End clip path') t = c.beginText(3 * cm, 22.5 * cm) t.textLines("""This shows clipping at work. We draw a chequerboard of rectangles into a path object, and clip it. This then forms a mask which limits the region of the page on which one can draw. This paragraph was drawn after setting the clipping path, and so you should only see part of the text. This shows clipping at work. We draw a chequerboard of rectangles into a path object, and clip it. This then forms a mask which limits the region of the page on which one can draw. This paragraph was drawn after setting the clipping path, and so you should only see part of the text. This shows clipping at work. We draw a chequerboard of rectangles into a path object, and clip it. This then forms a mask which limits the region of the page on which one can draw. This paragraph was drawn after setting the clipping path, and so you should only see part of the text.""") c.drawText(t) c.restoreState() t = c.beginText(inch, 5 * inch) t.textLines("""You can also use text as an outline for clipping with the text render mode. The API is not particularly clean on this and one has to follow the right sequence; this can be optimized shortly.""") c.drawText(t) #first the outline c.saveState() t = c.beginText(inch, 3.0 * inch) t.setFont('Helvetica-BoldOblique',108) t.setTextRenderMode(5) #stroke and add to path t.textLine('Python!') t.setTextRenderMode(0) c.drawText(t) #this will make a clipping mask #now some small stuff which wil be drawn into the current clip mask t = c.beginText(inch, 4 * inch) t.setFont('Times-Roman',6) t.textLines((('spam ' * 40) + '\n') * 15) c.drawText(t) #now reset canvas to get rid of the clipping mask c.restoreState() c.showPage() ######################################################################### # # Page 7 - images # ######################################################################### framePage(c, "Images") c.setFont('Times-Roman', 12) t = c.beginText(inch, 10 * inch) if not haveImages: c.drawString(inch, 11*inch, "Python Imaging Library not found! Below you see rectangles instead of images.") t.textLines("""PDFgen uses the Python Imaging Library to process a very wide variety of image formats. This page shows image capabilities. If I've done things right, the bitmap should have its bottom left corner aligned with the crosshairs. There are two methods for drawing images. The recommended use is to call drawImage. This produces the smallest PDFs and the fastest generation times as each image's binary data is only embedded once in the file. Also you can use advanced features like transparency masks. You can also use drawInlineImage, which puts images in the page stream directly. This is slightly faster for Acrobat to render or for very small images, but wastes space if you use images more than once.""") c.drawText(t) gif = os.path.join(_RL_DIR,'test','pythonpowered.gif') if haveImages and rl_isfile(gif): c.drawInlineImage(gif,2*inch, 7*inch) else: c.rect(2*inch, 7*inch, 110, 44) c.line(1.5*inch, 7*inch, 4*inch, 7*inch) c.line(2*inch, 6.5*inch, 2*inch, 8*inch) c.drawString(4.5 * inch, 7.25*inch, 'inline image drawn at natural size') if haveImages and rl_isfile(gif): c.drawInlineImage(gif,2*inch, 5*inch, inch, inch) else: c.rect(2*inch, 5*inch, inch, inch) c.line(1.5*inch, 5*inch, 4*inch, 5*inch) c.line(2*inch, 4.5*inch, 2*inch, 6*inch) c.drawString(4.5 * inch, 5.25*inch, 'inline image distorted to fit box') c.drawString(1.5 * inch, 4*inch, 'Image XObjects can be defined once in the file and drawn many times.') c.drawString(1.5 * inch, 3.75*inch, 'This results in faster generation and much smaller files.') for i in range(5): if haveImages: (w, h) = c.drawImage(gif, (1.5 + i)*inch, 3*inch) else: c.rect((1.5 + i)*inch, 3*inch, 110, 44) myMask = [254,255,222,223,0,1] c.drawString(1.5 * inch, 2.5*inch, "The optional 'mask' parameter lets you define transparent colors. We used a color picker") c.drawString(1.5 * inch, 2.3*inch, "to determine that the yellow in the image above is RGB=(225,223,0). We then define a mask") c.drawString(1.5 * inch, 2.1*inch, "spanning these RGB values: %s. The background vanishes!!" % myMask) c.drawString(2.5*inch, 1.2*inch, 'This would normally be obscured') if haveImages: c.drawImage(gif, 3*inch, 1.2*inch, w, h, mask=myMask) else: c.rect(3*inch, 1.2*inch, 110, 44) c.showPage() ######################################################################### # # Page 8 - Forms and simple links # ######################################################################### framePage(c, "Forms and Links") c.setFont('Times-Roman', 12) t = c.beginText(inch, 10 * inch) t.textLines("""Forms are sequences of text or graphics operations which are stored only once in a PDF file and used as many times as desired. The blue logo bar to the left is an example of a form in this document. See the function framePageForm in this demo script for an example of how to use canvas.beginForm(name, ...) ... canvas.endForm(). Documents can also contain cross references where (for example) a rectangle on a page may be bound to a position on another page. If the user clicks on the rectangle the PDF viewer moves to the bound position on the other page. There are many other types of annotations and links supported by PDF. For example, there is a bookmark to each page in this document and below is a browsable index that jumps to those pages. In addition we show two URL hyperlinks; for these, you specify a rectangle but must draw the contents or any surrounding rectangle yourself. """) c.drawText(t) nentries = len(titlelist) xmargin = 3*inch xmax = 7*inch ystart = 6.54*inch ydelta = 0.4*inch for i in range(nentries): yposition = ystart - i*ydelta title = titlelist[i] c.drawString(xmargin, yposition, title) c.linkAbsolute(title, title, (xmargin-ydelta/4, yposition-ydelta/4, xmax, yposition+ydelta/2)) # test URLs r1 = (inch, 3*inch, 5*inch, 3.25*inch) # this is x1,y1,x2,y2 c.linkURL('http://www.reportlab.com/', r1, thickness=1, color=colors.green) c.drawString(inch+3, 3*inch+6, 'Hyperlink to www.reportlab.com, with green border') r1 = (inch, 2.5*inch, 5*inch, 2.75*inch) # this is x1,y1,x2,y2 c.linkURL('mailto:[email protected]', r1) #, border=0) c.drawString(inch+3, 2.5*inch+6, 'mailto: hyperlink, without border') r1 = (inch, 2*inch, 5*inch, 2.25*inch) # this is x1,y1,x2,y2 c.linkURL('http://www.reportlab.com/', r1, thickness=2, dashArray=[2,4], color=colors.magenta) c.drawString(inch+3, 2*inch+6, 'Hyperlink with custom border style') ### now do stuff for the outline #for x in outlinenametree: print x #stop #apply(c.setOutlineNames0, tuple(outlinenametree)) return c
def search(self): started = time.clock() if not self._dirs: raise ValueError( "Font search path is empty! Please specify search directories using addDirectory or addDirectories" ) if self.useCache: cfn = self._getCacheFileName() if rl_isfile(cfn): try: self.load(cfn) #print "loaded cached file with %d fonts (%s)" % (len(self._fonts), cfn) return except: pass #pickle load failed. Ho hum, maybe it's an old pickle. Better rebuild it. from stat import ST_MTIME for dirName in self._dirs: fileNames = rl_listdir(dirName) for fileName in fileNames: root, ext = os.path.splitext(fileName) if ext.lower() in EXTENSIONS: #it's a font f = FontDescriptor() f.fileName = os.path.normpath( os.path.join(dirName, fileName)) f.timeModified = rl_getmtime(f.fileName) ext = ext.lower() if ext[0] == '.': ext = ext[1:] f.typeCode = ext #strip the dot #what to do depends on type. We only accept .pfb if we #have .afm to go with it, and don't handle .otf now. if ext in ('otf', 'pfa'): self._skippedFiles.append(fileName) elif ext in ('ttf', 'ttc'): #parsing should check it for us from reportlab.pdfbase.ttfonts import TTFontFile, TTFError try: font = TTFontFile(fileName, validate=self.validate) except TTFError: self._badFiles.append(fileName) continue f.name = font.name f.fullName = font.fullName f.styleName = font.styleName f.familyName = font.familyName f.isBold = (FF_FORCEBOLD == FF_FORCEBOLD & font.flags) f.isItalic = (FF_ITALIC == FF_ITALIC & font.flags) elif ext == 'pfb': # type 1; we need an AFM file or have to skip. if rl_isfile(os.path.join(dirName, root + '.afm')): f.metricsFileName = os.path.normpath( os.path.join(dirName, root + '.afm')) elif rl_isfile(os.path.join(dirName, root + '.AFM')): f.metricsFileName = os.path.normpath( os.path.join(dirName, root + '.AFM')) else: self._skippedFiles.append(fileName) continue from reportlab.pdfbase.pdfmetrics import parseAFMFile (info, glyphs) = parseAFMFile(f.metricsFileName) f.name = info['FontName'] f.fullName = info.get('FullName', f.name) f.familyName = info.get('FamilyName', None) f.isItalic = (float(info.get('ItalicAngle', 0)) > 0.0) #if the weight has the word bold, deem it bold f.isBold = ('bold' in info.get('Weight', '').lower()) self._fonts.append(f) if self.useCache: self.save(cfn) finished = time.clock()
def search(self): started = time.clock() if not self._dirs: raise ValueError("Font search path is empty! Please specify search directories using addDirectory or addDirectories") if self.useCache: cfn = self._getCacheFileName() if rl_isfile(cfn): try: self.load(cfn) #print "loaded cached file with %d fonts (%s)" % (len(self._fonts), cfn) return except: pass #pickle load failed. Ho hum, maybe it's an old pickle. Better rebuild it. from stat import ST_MTIME for dirName in self._dirs: fileNames = rl_listdir(dirName) for fileName in fileNames: root, ext = os.path.splitext(fileName) if ext.lower() in EXTENSIONS: #it's a font f = FontDescriptor() f.fileName = os.path.normpath(os.path.join(dirName, fileName)) f.timeModified = rl_getmtime(f.fileName) ext = ext.lower() if ext[0] == '.': ext = ext[1:] f.typeCode = ext #strip the dot #what to do depends on type. We only accept .pfb if we #have .afm to go with it, and don't handle .otf now. if ext in ('otf', 'pfa'): self._skippedFiles.append(fileName) elif ext in ('ttf','ttc'): #parsing should check it for us from reportlab.pdfbase.ttfonts import TTFontFile, TTFError try: font = TTFontFile(fileName,validate=self.validate) except TTFError: self._badFiles.append(fileName) continue f.name = font.name f.fullName = font.fullName f.styleName = font.styleName f.familyName = font.familyName f.isBold = (FF_FORCEBOLD == FF_FORCEBOLD & font.flags) f.isItalic = (FF_ITALIC == FF_ITALIC & font.flags) elif ext == 'pfb': # type 1; we need an AFM file or have to skip. if rl_isfile(os.path.join(dirName, root + '.afm')): f.metricsFileName = os.path.normpath(os.path.join(dirName, root + '.afm')) elif rl_isfile(os.path.join(dirName, root + '.AFM')): f.metricsFileName = os.path.normpath(os.path.join(dirName, root + '.AFM')) else: self._skippedFiles.append(fileName) continue from reportlab.pdfbase.pdfmetrics import parseAFMFile (info, glyphs) = parseAFMFile(f.metricsFileName) f.name = info['FontName'] f.fullName = info.get('FullName', f.name) f.familyName = info.get('FamilyName', None) f.isItalic = (float(info.get('ItalicAngle', 0)) > 0.0) #if the weight has the word bold, deem it bold f.isBold = ('bold' in info.get('Weight','').lower()) self._fonts.append(f) if self.useCache: self.save(cfn) finished = time.clock()
from reportlab.platypus import Paragraph, Preformatted from reportlab.lib.units import inch, cm from reportlab.lib.styles import PropertySet, getSampleStyleSheet, ParagraphStyle from reportlab.lib import colors from reportlab.rl_config import defaultPageSize # @UnresolvedImport from reportlab.lib.utils import haveImages, _RL_DIR, rl_isfile, open_for_read, fileName2FSEnc import unittest import reportlab.lib.testutils testsFolder = reportlab.lib.testutils._OUTDIR = os.path.dirname(__file__) or "" from wordaxe.rl.styles import getSampleStyleSheet, ParagraphStyle from wordaxe.rl.NewParagraph import Paragraph if haveImages: _GIF = os.path.join(testsFolder, 'pythonpowered.gif') if not rl_isfile(_GIF): _GIF = None else: _GIF = None if _GIF: _GIFFSEnc = fileName2FSEnc(_GIF) _JPG = os.path.join(testsFolder, 'lj8100.jpg') if not rl_isfile(_JPG): _JPG = None def getFurl(fn): furl = fn.replace(os.sep, '/') if sys.platform == 'win32' and furl[1] == ':': furl = furl[0] + '|' + furl[2:] if furl[0] != '/': furl = '/' + furl return 'file://' + furl
import string, copy, sys, os from reportlab.pdfgen import canvas from reportlab import platypus from reportlab.platypus import BaseDocTemplate, PageTemplate, Flowable, FrameBreak from reportlab.platypus import Paragraph, Preformatted from reportlab.lib.units import inch, cm from reportlab.lib.styles import PropertySet, getSampleStyleSheet, ParagraphStyle from reportlab.lib import colors from reportlab.rl_config import defaultPageSize from reportlab.lib.utils import haveImages, _RL_DIR, rl_isfile, open_for_read, fileName2Utf8 import unittest from reportlab.lib.testutils import testsFolder if haveImages: _GIF = os.path.join(testsFolder, "pythonpowered.gif") if not rl_isfile(_GIF): _GIF = None else: _GIF = None if _GIF: _GIFUTF8 = fileName2Utf8(_GIF) _JPG = os.path.join(testsFolder, "..", "docs", "images", "lj8100.jpg") if not rl_isfile(_JPG): _JPG = None def getFurl(fn): furl = fn.replace(os.sep, "/") if sys.platform == "win32" and furl[1] == ":": furl = furl[0] + "|" + furl[2:]
def test2(self): "try under a well known directory NOT on the path" D = os.path.join(os.path.dirname(reportlab.__file__), 'tools','pythonpoint') fn = os.path.join(D,'stdparser.py') if rl_isfile(fn) or rl_isfile(fn+'c') or rl_isfile(fn+'o'): m1 = recursiveImport('stdparser', baseDir=D)
from reportlab.test import unittest from reportlab.test.utils import makeSuiteForClasses, outputfile from reportlab.pdfgen import canvas from reportlab import platypus from reportlab.platypus import BaseDocTemplate, PageTemplate, Flowable, FrameBreak from reportlab.platypus import Paragraph, Preformatted from reportlab.lib.units import inch, cm from reportlab.lib.styles import PropertySet, getSampleStyleSheet, ParagraphStyle from reportlab.lib import colors from reportlab.rl_config import defaultPageSize from reportlab.lib.utils import haveImages, _RL_DIR, rl_isfile, open_for_read if haveImages: _GIF = os.path.join(_RL_DIR,'test','pythonpowered.gif') if not rl_isfile(_GIF): _GIF = None else: _GIF = None _JPG = os.path.join(_RL_DIR,'docs','images','lj8100.jpg') if not rl_isfile(_JPG): _JPG = None def getFurl(fn): furl = fn.replace(os.sep,'/') if sys.platform=='win32' and furl[1]==':': furl = furl[0]+'|'+furl[2:] if furl[0]!='/': furl = '/'+furl return 'file://'+furl PAGE_HEIGHT = defaultPageSize[1] ################################################################# #
def run(): from reportlab.platypus import BaseDocTemplate, PageTemplate, Image, Frame, PageTemplate, \ ShowBoundaryValue, SimpleDocTemplate, FrameBG, Paragraph, \ FrameBreak from reportlab.lib.colors import toColor from reportlab.lib.utils import haveImages, _RL_DIR, rl_isfile, open_for_read, fileName2FSEnc, asNative from reportlab.lib.styles import getSampleStyleSheet styleSheet = getSampleStyleSheet() if haveImages: _GIF = os.path.join(testsFolder, 'pythonpowered.gif') if not rl_isfile(_GIF): _GIF = None _GAPNG = os.path.join(testsFolder, 'gray-alpha.png') if not rl_isfile(_GAPNG): _GAPNG = None else: _GIF = None if _GIF: _GIFFSEnc = fileName2FSEnc(_GIF) if _GAPNG: _GAPNGFSEnc = fileName2FSEnc(_GAPNG) _JPG = os.path.join(testsFolder, '..', 'docs', 'images', 'lj8100.jpg') if not rl_isfile(_JPG): _JPG = None doc = SimpleDocTemplate(outputfile('test_platypus_images.pdf')) story = [ FrameBG(color=toColor('lightblue'), start='frame-permanent'), ] if _GIF: story.append( Paragraph( "Here is an Image flowable obtained from a string GIF filename.", styleSheet['Italic'])) story.append(Image(_GIF)) story.append( Paragraph( "Here is an Image flowable obtained from a utf8 GIF filename.", styleSheet['Italic'])) #story.append(Image(fileName2FSEnc(_GIF))) story.append( Paragraph( "Here is an Image flowable obtained from a string GIF file url.", styleSheet['Italic'])) story.append(Image(getFurl(_GIF))) story.append( Paragraph( "Here is an Image flowable obtained from an open GIF file.", styleSheet['Italic'])) story.append(Image(open_for_read(_GIF, 'b'))) story.append(FrameBreak()) img = Image('http://www.reportlab.com/rsrc/encryption.gif') story.append( Paragraph( "Here is an Image flowable obtained from a string GIF http url.", styleSheet['Italic'])) story.append(img) story.append(FrameBreak()) if _GAPNG: story.append( Paragraph( "Here is an Image flowable obtained from a string PNGA filename.", styleSheet['Italic'])) story.append(Image('rltw-icon-tr.png')) story.append( Paragraph( "Here is an Image flowable obtained from a string PNG filename.", styleSheet['Italic'])) story.append(Image(_GAPNG)) story.append( Paragraph( "Here is an Image flowable obtained from a utf8 PNG filename.", styleSheet['Italic'])) #story.append(Image(fileName2FSEnc(_GAPNG))) story.append( Paragraph( "Here is an Image flowable obtained from a string file PNG url.", styleSheet['Italic'])) story.append(Image(getFurl(_GAPNG))) story.append( Paragraph( "Here is an Image flowable obtained from an open PNG file.", styleSheet['Italic'])) story.append(Image(open_for_read(_GAPNG, 'b'))) story.append(FrameBreak()) if _JPG: img = Image(_JPG) story.append( Paragraph( "Here is an JPEG Image flowable obtained from a JPEG filename.", styleSheet['Italic'])) story.append(img) story.append( Paragraph( "Here is an JPEG Image flowable obtained from an open JPEG file.", styleSheet['Italic'])) img = Image(open_for_read(_JPG, 'b')) story.append(img) story.append(FrameBreak()) doc.build(story)