1#Copyright ReportLab Europe Ltd. 2000-2017
2#see license.txt for license details
3#history https://hg.reportlab.com/hg-public/reportlab/log/tip/tools/docco/examples.py
4testannotations="""
5def annotations(canvas):
6    from reportlab.lib.units import inch
7    canvas.drawString(inch, 2.5*inch,
8       "setAuthor, setTitle, setSubject have no visible effect")
9    canvas.drawString(inch, inch, "But if you are viewing this document dynamically")
10    canvas.drawString(inch, 0.5*inch, "please look at File/Document Info")
11    canvas.setAuthor("the ReportLab Team")
12    canvas.setTitle("ReportLab PDF Generation User Guide")
13    canvas.setSubject("How to Generate PDF files using the ReportLab modules")
14"""
15
16# magic function making module
17
18test1 = """
19def f(a,b):
20    print("it worked", a, b)
21    return a+b
22"""
23
24test2 = """
25def g(n):
26    if n==0: return 1
27    else: return n*g(n-1)
28"""
29
30testhello = """
31def hello(c):
32    from reportlab.lib.units import inch
33    # move the origin up and to the left
34    c.translate(inch,inch)
35    # define a large font
36    c.setFont("Helvetica", 14)
37    # choose some colors
38    c.setStrokeColorRGB(0.2,0.5,0.3)
39    c.setFillColorRGB(1,0,1)
40    # draw some lines
41    c.line(0,0,0,1.7*inch)
42    c.line(0,0,1*inch,0)
43    # draw a rectangle
44    c.rect(0.2*inch,0.2*inch,1*inch,1.5*inch, fill=1)
45    # make text go straight up
46    c.rotate(90)
47    # change color
48    c.setFillColorRGB(0,0,0.77)
49    # say hello (note after rotate the y coord needs to be negative!)
50    c.drawString(0.3*inch, -inch, "Hello World")
51"""
52
53testcoords = """
54def coords(canvas):
55    from reportlab.lib.units import inch
56    from reportlab.lib.colors import pink, black, red, blue, green
57    c = canvas
58    c.setStrokeColor(pink)
59    c.grid([inch, 2*inch, 3*inch, 4*inch], [0.5*inch, inch, 1.5*inch, 2*inch, 2.5*inch])
60    c.setStrokeColor(black)
61    c.setFont("Times-Roman", 20)
62    c.drawString(0,0, "(0,0) the Origin")
63    c.drawString(2.5*inch, inch, "(2.5,1) in inches")
64    c.drawString(4*inch, 2.5*inch, "(4, 2.5)")
65    c.setFillColor(red)
66    c.rect(0,2*inch,0.2*inch,0.3*inch, fill=1)
67    c.setFillColor(green)
68    c.circle(4.5*inch, 0.4*inch, 0.2*inch, fill=1)
69"""
70
71testtranslate = """
72def translate(canvas):
73    from reportlab.lib.units import cm
74    canvas.translate(2.3*cm, 0.3*cm)
75    coords(canvas)
76    """
77
78testscale = """
79def scale(canvas):
80    canvas.scale(0.75, 0.5)
81    coords(canvas)
82"""
83
84testscaletranslate = """
85def scaletranslate(canvas):
86    from reportlab.lib.units import inch
87    canvas.setFont("Courier-BoldOblique", 12)
88    # save the state
89    canvas.saveState()
90    # scale then translate
91    canvas.scale(0.3, 0.5)
92    canvas.translate(2.4*inch, 1.5*inch)
93    canvas.drawString(0, 2.7*inch, "Scale then translate")
94    coords(canvas)
95    # forget the scale and translate...
96    canvas.restoreState()
97    # translate then scale
98    canvas.translate(2.4*inch, 1.5*inch)
99    canvas.scale(0.3, 0.5)
100    canvas.drawString(0, 2.7*inch, "Translate then scale")
101    coords(canvas)
102"""
103
104testmirror = """
105def mirror(canvas):
106    from reportlab.lib.units import inch
107    canvas.translate(5.5*inch, 0)
108    canvas.scale(-1.0, 1.0)
109    coords(canvas)
110"""
111
112testRGBcolors = """
113def colorsRGB(canvas):
114    from reportlab.lib import colors
115    from reportlab.lib.units import inch
116    black = colors.black
117    y = x = 0; dy=inch*3/4.0; dx=inch*5.5/5; w=h=dy/2; rdx=(dx-w)/2
118    rdy=h/5.0; texty=h+2*rdy
119    canvas.setFont("Helvetica",10)
120    for [namedcolor, name] in (
121           [colors.lavenderblush, "lavenderblush"],
122           [colors.lawngreen, "lawngreen"],
123           [colors.lemonchiffon, "lemonchiffon"],
124           [colors.lightblue, "lightblue"],
125           [colors.lightcoral, "lightcoral"]):
126        canvas.setFillColor(namedcolor)
127        canvas.rect(x+rdx, y+rdy, w, h, fill=1)
128        canvas.setFillColor(black)
129        canvas.drawCentredString(x+dx/2, y+texty, name)
130        x = x+dx
131    y = y + dy; x = 0
132    for rgb in [(1,0,0), (0,1,0), (0,0,1), (0.5,0.3,0.1), (0.4,0.5,0.3)]:
133        r,g,b = rgb
134        canvas.setFillColorRGB(r,g,b)
135        canvas.rect(x+rdx, y+rdy, w, h, fill=1)
136        canvas.setFillColor(black)
137        canvas.drawCentredString(x+dx/2, y+texty, "r%s g%s b%s"%rgb)
138        x = x+dx
139    y = y + dy; x = 0
140    for gray in (0.0, 0.25, 0.50, 0.75, 1.0):
141        canvas.setFillGray(gray)
142        canvas.rect(x+rdx, y+rdy, w, h, fill=1)
143        canvas.setFillColor(black)
144        canvas.drawCentredString(x+dx/2, y+texty, "gray: %s"%gray)
145        x = x+dx
146"""
147
148testCMYKcolors = """
149def colorsCMYK(canvas):
150    from reportlab.lib.colors import CMYKColor, PCMYKColor
151    from reportlab.lib.units import inch
152    # creates a black CMYK ; CMYKColor use real values
153    black = CMYKColor(0,0,0,1)
154    # creates a cyan CMYK ; PCMYKColor use integer values
155    cyan = PCMYKColor(100,0,0,0)
156    y = x = 0; dy=inch*3/4.0; dx=inch*5.5/5; w=h=dy/2; rdx=(dx-w)/2
157    rdy=h/5.0; texty=h+2*rdy
158    canvas.setFont("Helvetica",10)
159    y = y + dy; x = 0
160    for cmyk in [(1,0,0,0), (0,1,0,0), (0,0,1,0), (0,0,0,1), (0,0,0,0)]:
161        c,m,y1,k = cmyk
162        canvas.setFillColorCMYK(c,m,y1,k)
163        canvas.rect(x+rdx, y+rdy, w, h, fill=1)
164        canvas.setFillColor(black)
165        canvas.drawCentredString(x+dx/2, y+texty, "c%s m%s y%s k%s"%cmyk)
166        x = x+dx
167"""
168
169testspumoni = """
170def spumoni(canvas):
171    from reportlab.lib.units import inch
172    from reportlab.lib.colors import pink, green, brown, white
173    x = 0; dx = 0.4*inch
174    for i in range(4):
175        for color in (pink, green, brown):
176            canvas.setFillColor(color)
177            canvas.rect(x,0,dx,3*inch,stroke=0,fill=1)
178            x = x+dx
179    canvas.setFillColor(white)
180    canvas.setStrokeColor(white)
181    canvas.setFont("Helvetica-Bold", 85)
182    canvas.drawCentredString(2.75*inch, 1.3*inch, "SPUMONI")
183"""
184
185testspumoni2 = """
186def spumoni2(canvas):
187    from reportlab.lib.units import inch
188    from reportlab.lib.colors import pink, green, brown, white, black
189    # draw the previous drawing
190    spumoni(canvas)
191    # now put an ice cream cone on top of it:
192    # first draw a triangle (ice cream cone)
193    p = canvas.beginPath()
194    xcenter = 2.75*inch
195    radius = 0.45*inch
196    p.moveTo(xcenter-radius, 1.5*inch)
197    p.lineTo(xcenter+radius, 1.5*inch)
198    p.lineTo(xcenter, 0)
199    canvas.setFillColor(brown)
200    canvas.setStrokeColor(black)
201    canvas.drawPath(p, fill=1)
202    # draw some circles (scoops)
203    y = 1.5*inch
204    for color in (pink, green, brown):
205        canvas.setFillColor(color)
206        canvas.circle(xcenter, y, radius, fill=1)
207        y = y+radius
208"""
209
210testalpha = """
211def alpha(canvas):
212    from reportlab.graphics.shapes import Rect
213    from reportlab.lib.colors import Color, black, blue, red
214    red50transparent = Color( 100, 0, 0, alpha=0.5)
215    c = canvas
216    c.setFillColor(black)
217    c.setFont('Helvetica', 10)
218    c.drawString(25,180, 'solid')
219    c.setFillColor(blue)
220    c.rect(25,25,100,100, fill=True, stroke=False)
221    c.setFillColor(red)
222    c.rect(100,75,100,100, fill=True, stroke=False)
223    c.setFillColor(black)
224    c.drawString(225,180, 'transparent')
225    c.setFillColor(blue)
226    c.rect(225,25,100,100, fill=True, stroke=False)
227    c.setFillColor(red50transparent)
228    c.rect(300,75,100,100, fill=True, stroke=False)
229"""
230
231testoverprint = """
232def overPrint(canvas):
233    from reportlab.graphics.shapes import Rect
234    from reportlab.lib.colors import PCMYKColor, PCMYKColorSep
235    black = PCMYKColorSep(0, 0, 0, 100, spotName='black',density=100)
236    blue  = PCMYKColorSep(91.0,  43.0,  0.0, 0.0, spotName='PANTONE 285 CV',density=100)
237    red   = PCMYKColorSep( 0.0, 100.0, 91.0, 0.0, spotName='PANTONE 485 CV',density=100)
238    c = canvas
239    c.setFillColor(black)
240    c.setFont('Helvetica', 10)
241    c.drawString(25,180, 'overprint')
242    c.setFillOverprint(True)
243    c.setFillColor(blue)
244    c.rect(25,25,100,100, fill=True, stroke=False)
245    c.setFillColor(red)
246    c.rect(100,75,100,100, fill=True, stroke=False)
247    c.setFillColor(black)
248    c.drawString(225,180, 'knockout')
249    c.setFillOverprint(False)
250    c.setFillColor(blue)
251    c.rect(225,25,100,100, fill=True, stroke=False)
252    c.setFillColor(red)
253    c.rect(300,75,100,100, fill=True, stroke=False)
254"""
255
256testbezier = """
257def bezier(canvas):
258    from reportlab.lib.colors import yellow, green, red, black
259    from reportlab.lib.units import inch
260    i = inch
261    d = i/4
262    # define the bezier curve control points
263    x1,y1, x2,y2, x3,y3, x4,y4 = d,1.5*i, 1.5*i,d, 3*i,d, 5.5*i-d,3*i-d
264    # draw a figure enclosing the control points
265    canvas.setFillColor(yellow)
266    p = canvas.beginPath()
267    p.moveTo(x1,y1)
268    for (x,y) in [(x2,y2), (x3,y3), (x4,y4)]:
269        p.lineTo(x,y)
270    canvas.drawPath(p, fill=1, stroke=0)
271    # draw the tangent lines
272    canvas.setLineWidth(inch*0.1)
273    canvas.setStrokeColor(green)
274    canvas.line(x1,y1,x2,y2)
275    canvas.setStrokeColor(red)
276    canvas.line(x3,y3,x4,y4)
277    # finally draw the curve
278    canvas.setStrokeColor(black)
279    canvas.bezier(x1,y1, x2,y2, x3,y3, x4,y4)
280"""
281
282testbezier2 = """
283def bezier2(canvas):
284    from reportlab.lib.colors import yellow, green, red, black
285    from reportlab.lib.units import inch
286    # make a sequence of control points
287    xd,yd = 5.5*inch/2, 3*inch/2
288    xc,yc = xd,yd
289    dxdy = [(0,0.33), (0.33,0.33), (0.75,1), (0.875,0.875),
290            (0.875,0.875), (1,0.75), (0.33,0.33), (0.33,0)]
291    pointlist = []
292    for xoffset in (1,-1):
293        yoffset = xoffset
294        for (dx,dy) in dxdy:
295            px = xc + xd*xoffset*dx
296            py = yc + yd*yoffset*dy
297            pointlist.append((px,py))
298        yoffset = -xoffset
299        for (dy,dx) in dxdy:
300            px = xc + xd*xoffset*dx
301            py = yc + yd*yoffset*dy
302            pointlist.append((px,py))
303    # draw tangent lines and curves
304    canvas.setLineWidth(inch*0.1)
305    while pointlist:
306        [(x1,y1),(x2,y2),(x3,y3),(x4,y4)] = pointlist[:4]
307        del pointlist[:4]
308        canvas.setLineWidth(inch*0.1)
309        canvas.setStrokeColor(green)
310        canvas.line(x1,y1,x2,y2)
311        canvas.setStrokeColor(red)
312        canvas.line(x3,y3,x4,y4)
313        # finally draw the curve
314        canvas.setStrokeColor(black)
315        canvas.bezier(x1,y1, x2,y2, x3,y3, x4,y4)
316"""
317
318testpencil = """
319def pencil(canvas, text="No.2"):
320    from reportlab.lib.colors import yellow, red, black,white
321    from reportlab.lib.units import inch
322    u = inch/10.0
323    canvas.setStrokeColor(black)
324    canvas.setLineWidth(4)
325    # draw erasor
326    canvas.setFillColor(red)
327    canvas.circle(30*u, 5*u, 5*u, stroke=1, fill=1)
328    # draw all else but the tip (mainly rectangles with different fills)
329    canvas.setFillColor(yellow)
330    canvas.rect(10*u,0,20*u,10*u, stroke=1, fill=1)
331    canvas.setFillColor(black)
332    canvas.rect(23*u,0,8*u,10*u,fill=1)
333    canvas.roundRect(14*u, 3.5*u, 8*u, 3*u, 1.5*u, stroke=1, fill=1)
334    canvas.setFillColor(white)
335    canvas.rect(25*u,u,1.2*u,8*u, fill=1,stroke=0)
336    canvas.rect(27.5*u,u,1.2*u,8*u, fill=1, stroke=0)
337    canvas.setFont("Times-Roman", 3*u)
338    canvas.drawCentredString(18*u, 4*u, text)
339    # now draw the tip
340    penciltip(canvas,debug=0)
341    # draw broken lines across the body.
342    canvas.setDash([10,5,16,10],0)
343    canvas.line(11*u,2.5*u,22*u,2.5*u)
344    canvas.line(22*u,7.5*u,12*u,7.5*u)
345    """
346
347testpenciltip = """
348def penciltip(canvas, debug=1):
349    from reportlab.lib.colors import tan, black, green
350    from reportlab.lib.units import inch
351    u = inch/10.0
352    canvas.setLineWidth(4)
353    if debug:
354        canvas.scale(2.8,2.8) # make it big
355        canvas.setLineWidth(1) # small lines
356    canvas.setStrokeColor(black)
357    canvas.setFillColor(tan)
358    p = canvas.beginPath()
359    p.moveTo(10*u,0)
360    p.lineTo(0,5*u)
361    p.lineTo(10*u,10*u)
362    p.curveTo(11.5*u,10*u, 11.5*u,7.5*u, 10*u,7.5*u)
363    p.curveTo(12*u,7.5*u, 11*u,2.5*u, 9.7*u,2.5*u)
364    p.curveTo(10.5*u,2.5*u, 11*u,0, 10*u,0)
365    canvas.drawPath(p, stroke=1, fill=1)
366    canvas.setFillColor(black)
367    p = canvas.beginPath()
368    p.moveTo(0,5*u)
369    p.lineTo(4*u,3*u)
370    p.lineTo(5*u,4.5*u)
371    p.lineTo(3*u,6.5*u)
372    canvas.drawPath(p, stroke=1, fill=1)
373    if debug:
374        canvas.setStrokeColor(green) # put in a frame of reference
375        canvas.grid([0,5*u,10*u,15*u], [0,5*u,10*u])
376"""
377
378testnoteannotation = """
379from reportlab.platypus.flowables import Flowable
380class NoteAnnotation(Flowable):
381    '''put a pencil in the margin.'''
382    def wrap(self, *args):
383        return (1,10) # I take up very little space! (?)
384    def draw(self):
385        canvas = self.canv
386        canvas.translate(-10,-10)
387        canvas.rotate(180)
388        canvas.scale(0.2,0.2)
389        pencil(canvas, text="NOTE")
390"""
391
392testhandannotation = """
393from reportlab.platypus.flowables import Flowable
394from reportlab.lib.colors import tan, green
395class HandAnnotation(Flowable):
396    '''A hand flowable.'''
397    def __init__(self, xoffset=0, size=None, fillcolor=tan, strokecolor=green):
398        from reportlab.lib.units import inch
399        if size is None: size=4*inch
400        self.fillcolor, self.strokecolor = fillcolor, strokecolor
401        self.xoffset = xoffset
402        self.size = size
403        # normal size is 4 inches
404        self.scale = size/(4.0*inch)
405    def wrap(self, *args):
406        return (self.xoffset, self.size)
407    def draw(self):
408        canvas = self.canv
409        canvas.setLineWidth(6)
410        canvas.setFillColor(self.fillcolor)
411        canvas.setStrokeColor(self.strokecolor)
412        canvas.translate(self.xoffset+self.size,0)
413        canvas.rotate(90)
414        canvas.scale(self.scale, self.scale)
415        hand(canvas, debug=0, fill=1)
416"""
417
418lyrics = '''\
419well she hit Net Solutions
420and she registered her own .com site now
421and filled it up with yahoo profile pics
422she snarfed in one night now
423and she made 50 million when Hugh Hefner
424bought up the rights now
425and she'll have fun fun fun
426til her Daddy takes the keyboard away'''
427
428lyrics = lyrics.split("\n")
429testtextsize = """
430def textsize(canvas):
431    from reportlab.lib.units import inch
432    from reportlab.lib.colors import magenta, red
433    canvas.setFont("Times-Roman", 20)
434    canvas.setFillColor(red)
435    canvas.drawCentredString(2.75*inch, 2.5*inch, "Font size examples")
436    canvas.setFillColor(magenta)
437    size = 7
438    y = 2.3*inch
439    x = 1.3*inch
440    for line in lyrics:
441        canvas.setFont("Helvetica", size)
442        canvas.drawRightString(x,y,"%s points: " % size)
443        canvas.drawString(x,y, line)
444        y = y-size*1.2
445        size = size+1.5
446"""
447
448teststar = """
449def star(canvas, title="Title Here", aka="Comment here.",
450         xcenter=None, ycenter=None, nvertices=5):
451    from math import pi
452    from reportlab.lib.units import inch
453    radius=inch/3.0
454    if xcenter is None: xcenter=2.75*inch
455    if ycenter is None: ycenter=1.5*inch
456    canvas.drawCentredString(xcenter, ycenter+1.3*radius, title)
457    canvas.drawCentredString(xcenter, ycenter-1.4*radius, aka)
458    p = canvas.beginPath()
459    p.moveTo(xcenter,ycenter+radius)
460    from math import pi, cos, sin
461    angle = (2*pi)*2/5.0
462    startangle = pi/2.0
463    for vertex in range(nvertices-1):
464        nextangle = angle*(vertex+1)+startangle
465        x = xcenter + radius*cos(nextangle)
466        y = ycenter + radius*sin(nextangle)
467        p.lineTo(x,y)
468    if nvertices==5:
469       p.close()
470    canvas.drawPath(p)
471"""
472
473testjoins = """
474def joins(canvas):
475    from reportlab.lib.units import inch
476    # make lines big
477    canvas.setLineWidth(5)
478    star(canvas, "Default: mitered join", "0: pointed", xcenter = 1*inch)
479    canvas.setLineJoin(1)
480    star(canvas, "Round join", "1: rounded")
481    canvas.setLineJoin(2)
482    star(canvas, "Bevelled join", "2: square", xcenter=4.5*inch)
483"""
484
485testcaps = """
486def caps(canvas):
487    from reportlab.lib.units import inch
488    # make lines big
489    canvas.setLineWidth(5)
490    star(canvas, "Default", "no projection",xcenter = 1*inch,
491         nvertices=4)
492    canvas.setLineCap(1)
493    star(canvas, "Round cap", "1: ends in half circle", nvertices=4)
494    canvas.setLineCap(2)
495    star(canvas, "Square cap", "2: projects out half a width", xcenter=4.5*inch,
496       nvertices=4)
497"""
498
499testdashes = """
500def dashes(canvas):
501    from reportlab.lib.units import inch
502    # make lines big
503    canvas.setDash(6,3)
504    star(canvas, "Simple dashes", "6 points on, 3 off", xcenter = 1*inch)
505    canvas.setDash(1,2)
506    star(canvas, "Dots", "One on, two off")
507    canvas.setDash([1,1,3,3,1,4,4,1], 0)
508    star(canvas, "Complex Pattern", "[1,1,3,3,1,4,4,1]", xcenter=4.5*inch)
509"""
510
511testcustomfont1 = """
512def customfont1(canvas):
513    # we know some glyphs are missing, suppress warnings
514    import reportlab.rl_config
515    reportlab.rl_config.warnOnMissingFontGlyphs = 0
516
517    from . import rl_doc_utils
518    from reportlab.pdfbase import pdfmetrics
519    afmFile, pfbFile = rl_doc_utils.getJustFontPaths()
520    justFace = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile)
521    faceName = 'DarkGardenMK' # pulled from AFM file
522    pdfmetrics.registerTypeFace(justFace)
523    justFont = pdfmetrics.Font('DarkGardenMK',
524                               faceName,
525                               'WinAnsiEncoding')
526    pdfmetrics.registerFont(justFont)
527
528    canvas.setFont('DarkGardenMK', 32)
529    canvas.drawString(10, 150, 'This should be in')
530    canvas.drawString(10, 100, 'DarkGardenMK')
531"""
532
533testttffont1 = """
534def ttffont1(canvas):
535    # we know some glyphs are missing, suppress warnings
536    import reportlab.rl_config
537    reportlab.rl_config.warnOnMissingFontGlyphs = 0
538    from reportlab.pdfbase import pdfmetrics
539    from reportlab.pdfbase.ttfonts import TTFont
540    pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf'))
541    from reportlab.pdfgen.canvas import Canvas
542
543    canvas.setFont('Vera', 32)
544    canvas.drawString(10, 150, "Some UTF-8 text encoded")
545    canvas.drawString(10, 100, "in the Vera TT Font!")
546"""
547
548testcursormoves1 = """
549def cursormoves1(canvas):
550    from reportlab.lib.units import inch
551    textobject = canvas.beginText()
552    textobject.setTextOrigin(inch, 2.5*inch)
553    textobject.setFont("Helvetica-Oblique", 14)
554    for line in lyrics:
555        textobject.textLine(line)
556    textobject.setFillGray(0.4)
557    textobject.textLines('''
558    With many apologies to the Beach Boys
559    and anyone else who finds this objectionable
560    ''')
561    canvas.drawText(textobject)
562"""
563
564testcursormoves2 = """
565def cursormoves2(canvas):
566    from reportlab.lib.units import inch
567    textobject = canvas.beginText()
568    textobject.setTextOrigin(2, 2.5*inch)
569    textobject.setFont("Helvetica-Oblique", 14)
570    for line in lyrics:
571        textobject.textOut(line)
572        textobject.moveCursor(14,14) # POSITIVE Y moves down!!!
573    textobject.setFillColorRGB(0.4,0,1)
574    textobject.textLines('''
575    With many apologies to the Beach Boys
576    and anyone else who finds this objectionable
577    ''')
578    canvas.drawText(textobject)
579"""
580
581testcharspace = """
582def charspace(canvas):
583    from reportlab.lib.units import inch
584    textobject = canvas.beginText()
585    textobject.setTextOrigin(3, 2.5*inch)
586    textobject.setFont("Helvetica-Oblique", 10)
587    charspace = 0
588    for line in lyrics:
589        textobject.setCharSpace(charspace)
590        textobject.textLine("%s: %s" %(charspace,line))
591        charspace = charspace+0.5
592    textobject.setFillGray(0.4)
593    textobject.textLines('''
594    With many apologies to the Beach Boys
595    and anyone else who finds this objectionable
596    ''')
597    canvas.drawText(textobject)
598"""
599
600testwordspace = """
601def wordspace(canvas):
602    from reportlab.lib.units import inch
603    textobject = canvas.beginText()
604    textobject.setTextOrigin(3, 2.5*inch)
605    textobject.setFont("Helvetica-Oblique", 12)
606    wordspace = 0
607    for line in lyrics:
608        textobject.setWordSpace(wordspace)
609        textobject.textLine("%s: %s" %(wordspace,line))
610        wordspace = wordspace+2.5
611    textobject.setFillColorCMYK(0.4,0,0.4,0.2)
612    textobject.textLines('''
613    With many apologies to the Beach Boys
614    and anyone else who finds this objectionable
615    ''')
616    canvas.drawText(textobject)
617"""
618testhorizontalscale = """
619def horizontalscale(canvas):
620    from reportlab.lib.units import inch
621    textobject = canvas.beginText()
622    textobject.setTextOrigin(3, 2.5*inch)
623    textobject.setFont("Helvetica-Oblique", 12)
624    horizontalscale = 80 # 100 is default
625    for line in lyrics:
626        textobject.setHorizScale(horizontalscale)
627        textobject.textLine("%s: %s" %(horizontalscale,line))
628        horizontalscale = horizontalscale+10
629    textobject.setFillColorCMYK(0.0,0.4,0.4,0.2)
630    textobject.textLines('''
631    With many apologies to the Beach Boys
632    and anyone else who finds this objectionable
633    ''')
634    canvas.drawText(textobject)
635"""
636testleading = """
637def leading(canvas):
638    from reportlab.lib.units import inch
639    textobject = canvas.beginText()
640    textobject.setTextOrigin(3, 2.5*inch)
641    textobject.setFont("Helvetica-Oblique", 14)
642    leading = 8
643    for line in lyrics:
644        textobject.setLeading(leading)
645        textobject.textLine("%s: %s" %(leading,line))
646        leading = leading+2.5
647    textobject.setFillColorCMYK(0.8,0,0,0.3)
648    textobject.textLines('''
649    With many apologies to the Beach Boys
650    and anyone else who finds this objectionable
651    ''')
652    canvas.drawText(textobject)
653"""
654
655testhand = """
656def hand(canvas, debug=1, fill=0):
657    (startx, starty) = (0,0)
658    curves = [
659      ( 0, 2), ( 0, 4), ( 0, 8), # back of hand
660      ( 5, 8), ( 7,10), ( 7,14),
661      (10,14), (10,13), ( 7.5, 8), # thumb
662      (13, 8), (14, 8), (17, 8),
663      (19, 8), (19, 6), (17, 6),
664      (15, 6), (13, 6), (11, 6), # index, pointing
665      (12, 6), (13, 6), (14, 6),
666      (16, 6), (16, 4), (14, 4),
667      (13, 4), (12, 4), (11, 4), # middle
668      (11.5, 4), (12, 4), (13, 4),
669      (15, 4), (15, 2), (13, 2),
670      (12.5, 2), (11.5, 2), (11, 2), # ring
671      (11.5, 2), (12, 2), (12.5, 2),
672      (14, 2), (14, 0), (12.5, 0),
673      (10, 0), (8, 0), (6, 0), # pinky, then close
674      ]
675    from reportlab.lib.units import inch
676    if debug: canvas.setLineWidth(6)
677    u = inch*0.2
678    p = canvas.beginPath()
679    p.moveTo(startx, starty)
680    ccopy = list(curves)
681    while ccopy:
682        [(x1,y1), (x2,y2), (x3,y3)] = ccopy[:3]
683        del ccopy[:3]
684        p.curveTo(x1*u,y1*u,x2*u,y2*u,x3*u,y3*u)
685    p.close()
686    canvas.drawPath(p, fill=fill)
687    if debug:
688        from reportlab.lib.colors import red, green
689        (lastx, lasty) = (startx, starty)
690        ccopy = list(curves)
691        while ccopy:
692            [(x1,y1), (x2,y2), (x3,y3)] = ccopy[:3]
693            del ccopy[:3]
694            canvas.setStrokeColor(red)
695            canvas.line(lastx*u,lasty*u, x1*u,y1*u)
696            canvas.setStrokeColor(green)
697            canvas.line(x2*u,y2*u, x3*u,y3*u)
698            (lastx,lasty) = (x3,y3)
699"""
700
701testhand2 = """
702def hand2(canvas):
703    canvas.translate(20,10)
704    canvas.setLineWidth(3)
705    canvas.setFillColorRGB(0.1, 0.3, 0.9)
706    canvas.setStrokeGray(0.5)
707    hand(canvas, debug=0, fill=1)
708"""
709
710testfonts = """
711def fonts(canvas):
712    from reportlab.lib.units import inch
713    text = "Now is the time for all good men to..."
714    x = 1.8*inch
715    y = 2.7*inch
716    for font in canvas.getAvailableFonts():
717        canvas.setFont(font, 10)
718        canvas.drawString(x,y,text)
719        canvas.setFont("Helvetica", 10)
720        canvas.drawRightString(x-10,y, font+":")
721        y = y-13
722"""
723
724testarcs = """
725def arcs(canvas):
726    from reportlab.lib.units import inch
727    canvas.setLineWidth(4)
728    canvas.setStrokeColorRGB(0.8, 1, 0.6)
729    # draw rectangles enclosing the arcs
730    canvas.rect(inch, inch, 1.5*inch, inch)
731    canvas.rect(3*inch, inch, inch, 1.5*inch)
732    canvas.setStrokeColorRGB(0, 0.2, 0.4)
733    canvas.setFillColorRGB(1, 0.6, 0.8)
734    p = canvas.beginPath()
735    p.moveTo(0.2*inch, 0.2*inch)
736    p.arcTo(inch, inch, 2.5*inch,2*inch, startAng=-30, extent=135)
737    p.arc(3*inch, inch, 4*inch, 2.5*inch, startAng=-45, extent=270)
738    canvas.drawPath(p, fill=1, stroke=1)
739"""
740testvariousshapes = """
741def variousshapes(canvas):
742    from reportlab.lib.units import inch
743    inch = int(inch)
744    canvas.setStrokeGray(0.5)
745    canvas.grid(range(0,int(11*inch/2),int(inch/2)), range(0,int(7*inch/2),int(inch/2)))
746    canvas.setLineWidth(4)
747    canvas.setStrokeColorRGB(0, 0.2, 0.7)
748    canvas.setFillColorRGB(1, 0.6, 0.8)
749    p = canvas.beginPath()
750    p.rect(0.5*inch, 0.5*inch, 0.5*inch, 2*inch)
751    p.circle(2.75*inch, 1.5*inch, 0.3*inch)
752    p.ellipse(3.5*inch, 0.5*inch, 1.2*inch, 2*inch)
753    canvas.drawPath(p, fill=1, stroke=1)
754"""
755
756testclosingfigures = """
757def closingfigures(canvas):
758    from reportlab.lib.units import inch
759    h = inch/3.0; k = inch/2.0
760    canvas.setStrokeColorRGB(0.2,0.3,0.5)
761    canvas.setFillColorRGB(0.8,0.6,0.2)
762    canvas.setLineWidth(4)
763    p = canvas.beginPath()
764    for i in (1,2,3,4):
765        for j in (1,2):
766            xc,yc = inch*i, inch*j
767            p.moveTo(xc,yc)
768            p.arcTo(xc-h, yc-k, xc+h, yc+k, startAng=0, extent=60*i)
769            # close only the first one, not the second one
770            if j==1:
771                p.close()
772    canvas.drawPath(p, fill=1, stroke=1)
773"""
774
775testforms = """
776def forms(canvas):
777    #first create a form...
778    canvas.beginForm("SpumoniForm")
779    #re-use some drawing functions from earlier
780    spumoni(canvas)
781    canvas.endForm()
782
783    #then draw it
784    canvas.doForm("SpumoniForm")
785"""
786
787def doctemplateillustration(canvas):
788    from reportlab.lib.units import inch
789    canvas.setFont("Helvetica", 10)
790    canvas.drawString(inch/4.0, 2.75*inch, "DocTemplate")
791    W = 4/3.0*inch
792    H = 2*inch
793    Wd = x = inch/4.0
794    Hd =y = inch/2.0
795    for name in ("two column", "chapter page", "title page"):
796        canvas.setFillColorRGB(0.5,1.0,1.0)
797        canvas.rect(x,y,W,H, fill=1)
798        canvas.setFillColorRGB(0,0,0)
799        canvas.drawString(x+inch/8, y+H-Wd, "PageTemplate")
800        canvas.drawCentredString(x+W/2.0, y-Wd, name)
801        x = x+W+Wd
802    canvas.saveState()
803    d = inch/16
804    dW = (W-3*d)/2.0
805    hD = H -2*d-Wd
806    canvas.translate(Wd+d, Hd+d)
807    for name in ("left Frame", "right Frame"):
808        canvas.setFillColorRGB(1.0,0.5,1.0)
809        canvas.rect(0,0, dW,hD, fill=1)
810        canvas.setFillGray(0.7)
811        dd= d/2.0
812        ddH = (hD-6*dd)/5.0
813        ddW = dW-2*dd
814        yy = dd
815        xx = dd
816        for i in range(5):
817            canvas.rect(xx,yy,ddW,ddH, fill=1, stroke=0)
818            yy = yy+ddH+dd
819        canvas.setFillColorRGB(0,0,0)
820        canvas.saveState()
821        canvas.rotate(90)
822        canvas.drawString(d,-dW/2, name)
823        canvas.restoreState()
824        canvas.translate(dW+d,0)
825    canvas.restoreState()
826    canvas.setFillColorRGB(1.0, 0.5, 1.0)
827    mx = Wd+W+Wd+d
828    my = Hd+d
829    mW = W-2*d
830    mH = H-d-Hd
831    canvas.rect(mx, my, mW, mH, fill=1)
832    canvas.rect(Wd+2*(W+Wd)+d, Hd+3*d, W-2*d, H/2.0, fill=1)
833    canvas.setFillGray(0.7)
834    canvas.rect(Wd+2*(W+Wd)+d+dd, Hd+5*d, W-2*d-2*dd, H/2.0-2*d-dd, fill=1)
835    xx = mx+dd
836    yy = my+mH/5.0
837    ddH = (mH-6*dd-mH/5.0)/3.0
838    ddW = mW - 2*dd
839    for i in range(3):
840        canvas.setFillGray(0.7)
841        canvas.rect(xx,yy,ddW,ddH, fill=1, stroke=1)
842        canvas.setFillGray(0)
843        canvas.drawString(xx+dd/2.0,yy+dd/2.0, "flowable %s" %(157-i))
844        yy = yy+ddH+dd
845    canvas.drawCentredString(3*Wd+2*W+W/2, Hd+H/2.0, "First Flowable")
846    canvas.setFont("Times-BoldItalic", 8)
847    canvas.setFillGray(0)
848    canvas.drawCentredString(mx+mW/2.0, my+mH+3*dd, "Chapter 6: Lubricants")
849    canvas.setFont("Times-BoldItalic", 10)
850    canvas.drawCentredString(3*Wd+2*W+W/2, Hd+H-H/4, "College Life")
851
852# D = dir()
853TESTS=[(a,b) for a, b in globals().items() if a.startswith('test')]
854for a,b in TESTS:
855    if isinstance(b,str):
856        b = b.strip()
857        exec(b+'\n')
858
859platypussetup = """
860from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
861from reportlab.lib.styles import getSampleStyleSheet
862from reportlab.rl_config import defaultPageSize
863from reportlab.lib.units import inch
864PAGE_HEIGHT=defaultPageSize[1]; PAGE_WIDTH=defaultPageSize[0]
865styles = getSampleStyleSheet()
866"""
867platypusfirstpage = """
868Title = "Hello world"
869pageinfo = "platypus example"
870def myFirstPage(canvas, doc):
871    canvas.saveState()
872    canvas.setFont('Times-Bold',16)
873    canvas.drawCentredString(PAGE_WIDTH/2.0, PAGE_HEIGHT-108, Title)
874    canvas.setFont('Times-Roman',9)
875    canvas.drawString(inch, 0.75 * inch, "First Page / %s" % pageinfo)
876    canvas.restoreState()
877"""
878platypusnextpage = """
879def myLaterPages(canvas, doc):
880    canvas.saveState()
881    canvas.setFont('Times-Roman',9)
882    canvas.drawString(inch, 0.75 * inch, "Page %d %s" % (doc.page, pageinfo))
883    canvas.restoreState()
884"""
885platypusgo = """
886def go():
887    doc = SimpleDocTemplate("phello.pdf")
888    Story = [Spacer(1,2*inch)]
889    style = styles["Normal"]
890    for i in range(100):
891        bogustext = ("This is Paragraph number %s.  " % i) *20
892        p = Paragraph(bogustext, style)
893        Story.append(p)
894        Story.append(Spacer(1,0.2*inch))
895    doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
896"""
897
898if __name__=="__main__":
899    # then do the platypus hello world
900    for b in platypussetup, platypusfirstpage, platypusnextpage, platypusgo:
901        b = b.strip()
902        exec(b+'\n')
903    go()
904