API Reference
reportlab
The Reportlab PDF generation library.
- reportlab.cmp(a, b)
reportlab.rl_config
module that aggregates config information
- reportlab.rl_config.register_reset(func)
register a function to be called by rl_config._reset
reportlab.rl_settings
default settings for reportlab
to override these drop a module rl_local_settings.py parallel to this file or anywhere on the path.
reportlab.graphics
Framework for reusable object graphics, in PDF or bitmap form
reportlab.graphics.renderPDF
Render Drawing objects within others PDFs or standalone
Usage:
import renderpdf
renderpdf.draw(drawing, canvas, x, y)
Execute the script to see some test drawings. changed
- class reportlab.graphics.renderPDF.GraphicsFlowable(drawing)
Flowable wrapper around a Pingo drawing
- draw()
- reportlab.graphics.renderPDF.draw(drawing, canvas, x, y, showBoundary=<reportlab.rl_config._unset_ object>)
As it says
- reportlab.graphics.renderPDF.drawToFile(d, fn, msg='', showBoundary=<reportlab.rl_config._unset_ object>, autoSize=1, **kwds)
Makes a one-page PDF with just the drawing.
If autoSize=1, the PDF will be the same size as the drawing; if 0, it will place the drawing on an A4 page with a title above it - possibly overflowing if too big.
- reportlab.graphics.renderPDF.drawToString(d, msg='', showBoundary=<reportlab.rl_config._unset_ object>, autoSize=1, **kwds)
Returns a PDF as a string in memory, without touching the disk
- reportlab.graphics.renderPDF.test(outDir='pdfout', shout=False)
reportlab.graphics.renderPM
Render drawing objects in common bitmap formats
Usage:
from reportlab.graphics import renderPM
renderPM.drawToFile(drawing,filename,fmt='GIF',configPIL={....})
Other functions let you create a PM drawing as string or into a PM buffer. Execute the script to see some test drawings.
- reportlab.graphics.renderPM.CairoColor(c)
c should be None or something convertible to Color rlPyCairo.GState can handle Color directly in either RGB24 or ARGB32
- reportlab.graphics.renderPM.Color2Hex(c)
- class reportlab.graphics.renderPM.PMCanvas(w, h, dpi=72, bg=16777215, configPIL=None, backend=None, backendFmt='RGB')
- addEllipsoidalArc(cx, cy, rx, ry, ang1, ang2)
adds an ellisesoidal arc segment to a path, with an ellipse centered on cx,cy and with radii (major & minor axes) rx and ry. The arc is drawn in the CCW direction. Requires: (ang2-ang1) > 0
- bezierArcCCW(cx, cy, rx, ry, theta0, theta1)
return a set of control points for Bezier approximation to an arc with angle increasing counter clockwise. No requirement on (theta1-theta0) <= 90 However, it must be true that theta1-theta0 > 0.
- circle(cx, cy, r)
add closed path circle with center cx,cy and axes r: counter-clockwise orientation
- drawCentredString(x, y, text, text_anchor='middle', direction=None, shaping=False)
- drawRightString(text, x, y, direction=None)
- drawString(x, y, text, _fontInfo=None, text_anchor='left', direction=None, shaping=False)
- ellipse(cx, cy, rx, ry)
add closed path ellipse with center cx,cy and axes rx,ry: counter-clockwise orientation (remember y-axis increases downward)
- fillstrokepath(stroke=1, fill=1)
- line(x1, y1, x2, y2)
- rect(x, y, width, height, stroke=1, fill=1)
- restoreState()
do nothing for compatibility
- roundRect(x, y, width, height, rx, ry)
rect(self, x, y, width, height, rx,ry): Draw a rectangle if rx or rx and ry are specified the corners are rounded with ellipsoidal arcs determined by rx and ry (drawn in the counter-clockwise direction)
- saveState()
do nothing for compatibility
- saveToFile(fn, fmt=None)
- saveToString(fmt='GIF')
- setFillColor(aColor)
- setFont(fontName, fontSize, leading=None)
- setLineCap(cap)
- setLineJoin(join)
- setLineWidth(width)
- setStrokeColor(aColor)
- stringWidth(text, fontName=None, fontSize=None)
- toPIL()
- reportlab.graphics.renderPM.draw(drawing, canvas, x, y, showBoundary=<reportlab.rl_config._unset_ object>, **kwds)
As it says
- reportlab.graphics.renderPM.drawToFile(d, fn, fmt='GIF', dpi=72, bg=16777215, configPIL=None, showBoundary=<reportlab.rl_config._unset_ object>, backend='rlPyCairo', backendFmt='RGB', **kwds)
create a pixmap and draw drawing, d to it then save as a file configPIL dict is passed to image save method
- reportlab.graphics.renderPM.drawToPIL(d, dpi=72, bg=16777215, configPIL=None, showBoundary=<reportlab.rl_config._unset_ object>, backend='rlPyCairo', backendFmt='RGB', **kwds)
- reportlab.graphics.renderPM.drawToPILP(d, dpi=72, bg=16777215, configPIL=None, showBoundary=<reportlab.rl_config._unset_ object>, backend='rlPyCairo', backendFmt='RGB', **kwds)
- reportlab.graphics.renderPM.drawToPMCanvas(d, dpi=72, bg=16777215, configPIL=None, showBoundary=<reportlab.rl_config._unset_ object>, backend='rlPyCairo', backendFmt='RGB', **kwds)
- reportlab.graphics.renderPM.drawToString(d, fmt='GIF', dpi=72, bg=16777215, configPIL=None, showBoundary=<reportlab.rl_config._unset_ object>, backend='rlPyCairo', backendFmt='RGB', **kwds)
- reportlab.graphics.renderPM.save(d, fn, fmt='GIF', dpi=72, bg=16777215, configPIL=None, showBoundary=<reportlab.rl_config._unset_ object>, backend='rlPyCairo', backendFmt='RGB', **kwds)
create a pixmap and draw drawing, d to it then save as a file configPIL dict is passed to image save method
- reportlab.graphics.renderPM.test(outDir='pmout', shout=False)
reportlab.graphics.renderPS
Render drawing objects in Postscript
- class reportlab.graphics.renderPS.PSCanvas(size=(300, 300), PostScriptLevel=2)
- circle(xc, yc, r)
- clear()
- closePath()
- comment(msg)
- curveTo(x1, y1, x2, y2, x3, y3)
- drawArc(x1, y1, x2, y2, startAng=0, extent=360, fromcenter=0)
Draw a partial ellipse inscribed within the rectangle x1,y1,x2,y2, starting at startAng degrees and covering extent degrees. Angles start with 0 to the right (+x) and increase counter-clockwise. These should have x1<x2 and y1<y2.
- drawCentredString(x, y, text, text_anchor='middle', textRenderMode=0)
- drawCurve(x1, y1, x2, y2, x3, y3, x4, y4, closed=0)
- drawFigure(partList, closed=0)
- drawImage(image, x1, y1, width=None, height=None)
- drawRightString(text, x, y, text_anchor='end', textRenderMode=0)
- drawString(x, y, s, angle=0, text_anchor='left', textRenderMode=0)
- ellipse(x1, y1, x2, y2)
Draw an orthogonal ellipse inscribed within the rectangle x1,y1,x2,y2. These should have x1<x2 and y1<y2.
- line(x1, y1, x2, y2)
- lineTo(x, y)
- lines(lineList, color=None, width=None)
- moveTo(x, y)
- polyLine(p)
- polygon(p, closed=0, stroke=1, fill=1)
- rect(x1, y1, x2, y2, stroke=1, fill=1)
Draw a rectangle between x1,y1, and x2,y2
- restoreState()
- roundRect(x1, y1, x2, y2, rx=8, ry=8)
Draw a rounded rectangle between x1,y1, and x2,y2, with corners inset as ellipses with x radius rx and y radius ry. These should have x1<x2, y1<y2, rx>0, and ry>0.
- save(f=None)
- saveState()
- scale(x, y)
- setColor(color)
- setDash(array=[], phase=0)
Two notations. pass two numbers, or an array and phase
- setFillColor(color)
- setFillMode(v)
- setFont(font, fontSize, leading=None)
- setLineCap(v)
- setLineJoin(v)
- setLineWidth(width)
- setStrokeColor(color)
- stringWidth(s, font=None, fontSize=None)
Return the logical width of the string if it were drawn in the current font (defaults to self.font).
- transform(a, b, c, d, e, f)
- translate(x, y)
- reportlab.graphics.renderPS.draw(drawing, canvas, x=0, y=0, showBoundary=0)
As it says
- reportlab.graphics.renderPS.drawToFile(d, fn, showBoundary=0, **kwd)
- reportlab.graphics.renderPS.drawToString(d, showBoundary=0)
Returns a PS as a string in memory, without touching the disk
- reportlab.graphics.renderPS.test(outDir='epsout', shout=False)
reportlab.graphics.renderSVG
An experimental SVG renderer for the ReportLab graphics framework.
This will create SVG code from the ReportLab Graphics API (RLG). To read existing SVG code and convert it into ReportLab graphics objects download the svglib module here:
- class reportlab.graphics.renderSVG.EncodedWriter(encoding, bom=False)
EncodedWriter(encoding) assumes .write will be called with either unicode or utf8 encoded bytes. it will accumulate unicode
- BOMS = {'utf-16': b'\xff\xfe', 'utf-16-be': b'\xfe\xff', 'utf-16-le': b'\xff\xfe', 'utf-32': b'\xff\xfe\x00\x00', 'utf-32-be': b'\x00\x00\xfe\xff', 'utf-32-le': b'\xff\xfe\x00\x00'}
- getvalue()
- write(u)
- class reportlab.graphics.renderSVG.SVGCanvas(size=(300, 300), encoding='utf-8', verbose=0, bom=False, **kwds)
- NOTUSED_stringWidth(s, font=None, fontSize=None)
Return the logical width of the string if it were drawn in the current font (defaults to self.font).
- circle(xc, yc, r, link_info=None)
- closePath()
- comment(data)
Add a comment.
- curveTo(x1, y1, x2, y2, x3, y3)
- drawArc(x1, y1, x2, y2, startAng=0, extent=360, fromcenter=0)
Draw a partial ellipse inscribed within the rectangle x1,y1,x2,y2.
Starting at startAng degrees and covering extent degrees. Angles start with 0 to the right (+x) and increase counter-clockwise. These should have x1<x2 and y1<y2.
- drawCentredString(s, x, y, angle=0, text_anchor='middle', link_info=None, textRenderMode=0, **_svgAttrs)
- drawCurve(x1, y1, x2, y2, x3, y3, x4, y4, closed=0)
- drawImage(image, x, y, width, height, embed=True)
- drawRightString(text, x, y, angle=0, text_anchor='end', link_info=None, textRenderMode=0, **_svgAttrs)
- drawString(s, x, y, angle=0, link_info=None, text_anchor='left', textRenderMode=0, **_svgAttrs)
- ellipse(x1, y1, x2, y2, link_info=None)
Draw an orthogonal ellipse inscribed within the rectangle x1,y1,x2,y2.
These should have x1<x2 and y1<y2.
- endGroup(currGroup)
- line(x1, y1, x2, y2)
- lineTo(x, y)
- lines(lineList, color=None, width=None)
- moveTo(x, y)
- polyLine(points)
- polygon(points, closed=0, link_info=None)
- rect(x1, y1, x2, y2, rx=8, ry=8, link_info=None, **_svgAttrs)
Draw a rectangle between x1,y1 and x2,y2.
- restoreState()
- roundRect(x1, y1, x2, y2, rx=8, ry=8, link_info=None, **_svgAttrs)
Draw a rounded rectangle between x1,y1 and x2,y2.
Corners inset as ellipses with x-radius rx and y-radius ry. These should have x1<x2, y1<y2, rx>0, and ry>0.
- save(fn=None)
- saveState()
- scale(sx, sy)
- setDash(array=[], phase=0)
Two notations. Pass two numbers, or an array and phase.
- setFillColor(color)
- setFillMode(v)
- setFont(font, fontSize)
- setLineCap(v)
- setLineJoin(v)
- setLineWidth(width)
- setStrokeColor(color)
- startGroup(attrDict={'transform': ''})
- transform(a, b, c, d, e, f)
- translate(x, y)
- reportlab.graphics.renderSVG.draw(drawing, canvas, x=0, y=0, showBoundary=0)
As it says.
- reportlab.graphics.renderSVG.drawToFile(d, fn, showBoundary=0, **kwds)
- reportlab.graphics.renderSVG.drawToString(d, showBoundary=0, **kwds)
Returns a SVG as a string in memory, without touching the disk
- reportlab.graphics.renderSVG.py_fp_str(*args)
- reportlab.graphics.renderSVG.test(outDir='out-svg')
- reportlab.graphics.renderSVG.transformNode(doc, newTag, node=None, **attrDict)
Transform a DOM node into new node and copy selected attributes.
Creates a new DOM node with tag name ‘newTag’ for document ‘doc’ and copies selected attributes from an existing ‘node’ as provided in ‘attrDict’. The source ‘node’ can be None. Attribute values will be converted to strings.
E.g.
n = transformNode(doc, “node1”, x=”0”, y=”1”) -> DOM node for <node1 x=”0” y=”1”/>
n = transformNode(doc, “node1”, x=0, y=1+1) -> DOM node for <node1 x=”0” y=”2”/>
n = transformNode(doc, “node1”, node0, x=”x0”, y=”x0”, zoo=bar()) -> DOM node for <node1 x=”[node0.x0]” y=”[node0.y0]” zoo=”[bar()]”/>
reportlab.graphics.renderbase
Superclass for renderers to factor out common functionality and default implementations.
- class reportlab.graphics.renderbase.Renderer
Virtual superclass for graphics renderers.
- applyStateChanges(delta, newState)
This takes a set of states, and outputs the operators needed to set those properties
- draw(drawing, canvas, x=0, y=0, showBoundary=<reportlab.rl_config._unset_ object>)
This is the top level function, which draws the drawing at the given location. The recursive part is handled by drawNode.
- drawCircle(circle)
- drawEllipse(ellipse)
- drawGroup(group)
- drawImage(*args, **kwds)
- drawLine(line)
- drawNode(node)
This is the recursive method called for each node in the tree
- drawNodeDispatcher(anode)
dispatch on the node’s (super) class: shared code
- drawPath(path)
- drawPolyLine(p)
- drawPolygon(p)
- drawRect(rect)
- drawString(stringObj)
- drawWedge(wedge)
- fillDerivedValues(node)
Examine a node for any values which are Derived, and replace them with their calculated values. Generally things may look at the drawing or their parent.
- getStateValue(key)
Return current state parameter for given key
- initState(x, y)
- pop()
- undefined(operation)
- class reportlab.graphics.renderbase.StateTracker(defaults=None, defaultObj=None)
Keeps a stack of transforms and state properties. It can contain any properties you want, but the keys ‘transform’ and ‘ctm’ have special meanings. The getCTM() method returns the current transformation matrix at any point, without needing to invert matrixes when you pop.
- getCTM()
returns the current transformation matrix at this point
- getState()
returns the complete graphics state at this point
- pop()
steps back one, and returns a state dictionary with the deltas to reverse out of wherever you are. Depending on your back end, you may not need the return value, since you can get the complete state afterwards with getState()
- push(delta)
Take a new state dictionary of changes and push it onto the stack. After doing this, the combined state is accessible through getState()
- reportlab.graphics.renderbase.getStateDelta(shape)
Used to compute when we need to change the graphics state. For example, if we have two adjacent red shapes we don’t need to set the pen color to red in between. Returns the effect the given shape would have on the graphics state
- reportlab.graphics.renderbase.renderScaledDrawing(d)
- reportlab.graphics.renderbase.testStateTracker()
reportlab.graphics.shapes
Core of the graphics library - defines Drawing and Shapes
- class reportlab.graphics.shapes.ArcPath(points=None, operators=None, isClipPath=0, autoclose=None, fillMode=0, **kw)
Path with an addArc method
- addArc(centerx, centery, radius, startangledegrees, endangledegrees, yradius=None, degreedelta=None, moveTo=None, reverse=None)
- class reportlab.graphics.shapes.Circle(cx, cy, r, **kw)
- copy()
Return a clone of this shape.
- getBounds()
Returns bounding rectangle of object as (x1,y1,x2,y2)
- class reportlab.graphics.shapes.DirectDraw(keywords={})
try to draw directly on the canvas
- drawDirectly(canvas)
- class reportlab.graphics.shapes.Drawing(width=400, height=200, *nodes, **keywords)
Outermost container; the thing a renderer works on. This has no properties except a height, width and list of contents.
- asGroup(*args, **kw)
- asString(format, verbose=None, preview=0, **kw)
Converts to an 8 bit string in given format.
- copy()
Returns a copy
- draw(showBoundary=<reportlab.rl_config._unset_ object>)
This is used by the Platypus framework to let the document draw itself in a story. It is specific to PDF and should not be used directly.
- expandUserNodes()
Return a new drawing which only contains primitive shapes.
- resized(kind='fit', lpad=0, rpad=0, bpad=0, tpad=0)
return a base class drawing which ensures all the contents fits
- save(formats=None, verbose=None, fnRoot=None, outDir=None, title='', **kw)
Saves copies of self in desired location and formats. Multiple formats can be supported in one call
the extra keywords can be of the form _renderPM_dpi=96 (which passes dpi=96 to renderPM)
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.graphics.shapes.Ellipse(cx, cy, rx, ry, **kw)
- copy()
Return a clone of this shape.
- getBounds()
Returns bounding rectangle of object as (x1,y1,x2,y2)
- class reportlab.graphics.shapes.Group(*elements, **keywords)
Groups elements together. May apply a transform to its contents. Has a publicly accessible property ‘contents’ which may be used to iterate over contents. In addition, child nodes may be given a name in which case they are subsequently accessible as properties.
- add(node, name=None)
Appends non-None child node to the ‘contents’ attribute. In addition, if a name is provided, it is subsequently accessible by name
- asDrawing(width, height)
Convenience function to make a drawing from a group After calling this the instance will be a drawing!
- copy()
returns a copy
- expandUserNodes()
Return a new object which only contains primitive shapes.
- getBounds()
Returns bounding rectangle of object as (x1,y1,x2,y2)
- getContents()
Return the list of things to be rendered override to get more complicated behaviour
- insert(i, n, name=None)
Inserts sub-node n in contents at specified location
- rotate(theta, cx=0, cy=0)
Convenience to help you set transforms
- scale(sx, sy=1)
Convenience to help you set transforms
- shift(x, y=0)
Convenience function to set the origin arbitrarily
- skew(kx, ky=0)
Convenience to help you set transforms
- translate(dx, dy=0)
Convenience to help you set transforms
- class reportlab.graphics.shapes.Hatching(spacings=2, angles=45, xyLists=[], **kwds)
define a hatching of a set of polygons defined by lists of the form [x0,y0,x1,y1,….,xn,yn]
- class reportlab.graphics.shapes.Image(x, y, width, height, path, **kw)
Bitmap image.
- copy()
Return a clone of this shape.
- getBounds()
Returns bounding rectangle of object as (x1,y1,x2,y2)
- class reportlab.graphics.shapes.Line(x1, y1, x2, y2, **kw)
- getBounds()
Returns bounding rectangle of object as (x1,y1,x2,y2)
- class reportlab.graphics.shapes.LineShape(kw)
- class reportlab.graphics.shapes.Path(points=None, operators=None, isClipPath=0, autoclose=None, fillMode=0, **kw)
Path, made up of straight lines and bezier curves.
- closePath()
- copy()
Return a clone of this shape.
- curveTo(x1, y1, x2, y2, x3, y3)
- getBounds()
Returns bounding rectangle of object as (x1,y1,x2,y2)
- lineTo(x, y)
- moveTo(x, y)
- class reportlab.graphics.shapes.PolyLine(points=[], **kw)
Series of line segments. Does not define a closed shape; never filled even if apparently joined. Put the numbers in the list, not two-tuples.
- copy()
Return a clone of this shape.
- getBounds()
Returns bounding rectangle of object as (x1,y1,x2,y2)
- class reportlab.graphics.shapes.Polygon(points=[], **kw)
Defines a closed shape; Is implicitly joined back to the start for you.
- copy()
Return a clone of this shape.
- getBounds()
Returns bounding rectangle of object as (x1,y1,x2,y2)
- class reportlab.graphics.shapes.Rect(x, y, width, height, rx=0, ry=0, **kw)
Rectangle, possibly with rounded corners.
- copy()
Return a clone of this shape.
- getBounds()
Returns bounding rectangle of object as (x1,y1,x2,y2)
- class reportlab.graphics.shapes.Shape(keywords={})
Base class for all nodes in the tree. Nodes are simply packets of data to be created, stored, and ultimately rendered - they don’t do anything active. They provide convenience methods for verification but do not check attribiute assignments or use any clever setattr tricks this time.
- copy()
Return a clone of this shape.
- dumpProperties(prefix='')
Convenience. Lists them on standard output. You may provide a prefix - mostly helps to generate code samples for documentation.
- getBounds()
Returns bounding rectangle of object as (x1,y1,x2,y2)
- getProperties(recur=1)
Interface to make it easy to extract automatic documentation
- setProperties(props)
Supports the bulk setting if properties from, for example, a GUI application or a config file.
- verify()
If the programmer has provided the optional _attrMap attribute, this checks all expected attributes are present; no unwanted attributes are present; and (if a checking function is found) checks each attribute. Either succeeds or raises an informative exception.
- class reportlab.graphics.shapes.SolidShape(kw)
- class reportlab.graphics.shapes.String(x, y, text, **kw)
Not checked against the spec, just a way to make something work. Can be anchored left, middle or end.
- copy()
Return a clone of this shape.
- encoding = 'utf8'
- getBounds()
Returns bounding rectangle of object as (x1,y1,x2,y2)
- getEast()
- class reportlab.graphics.shapes.UserNode
A simple template for creating a new node. The user (Python programmer) may subclasses this. provideNode() must be defined to provide a Shape primitive when called by a renderer. It does NOT inherit from Shape, as the renderer always replaces it, and your own classes can safely inherit from it without getting lots of unintended behaviour.
- provideNode()
Override this to create your own node. This lets widgets be added to drawings; they must create a shape (typically a group) so that the renderer can draw the custom node.
- class reportlab.graphics.shapes.Wedge(centerx, centery, radius, startangledegrees, endangledegrees, yradius=None, annular=False, **kw)
A “slice of a pie” by default translates to a polygon moves anticlockwise from start angle to end angle
- asPolygon()
- copy()
Return a clone of this shape.
- degreedelta = 1
- getBounds()
Returns bounding rectangle of object as (x1,y1,x2,y2)
- reportlab.graphics.shapes.definePath(pathSegs=[], isClipPath=0, dx=0, dy=0, **kw)
- reportlab.graphics.shapes.getArcPoints(centerx, centery, radius, startangledegrees, endangledegrees, yradius=None, degreedelta=None, reverse=None)
- reportlab.graphics.shapes.getPathBounds(points)
- reportlab.graphics.shapes.getPointsBounds(pointList)
Helper function for list of points
- reportlab.graphics.shapes.getRectsBounds(rectList)
- reportlab.graphics.shapes.numericXShift(tA, text, w, fontName, fontSize, encoding=None, pivotCharacter='.')
- reportlab.graphics.shapes.test()
reportlab.graphics.svgpath
this code is derived from that used by svglib.
- class reportlab.graphics.svgpath.SvgPath(s, isClipPath=0, autoclose=None, fillMode=0, **kw)
Path, from an svg path string
- provideNode()
Override this to create your own node. This lets widgets be added to drawings; they must create a shape (typically a group) so that the renderer can draw the custom node.
reportlab.graphics.testdrawings
Defines some standard drawings to use as test cases
This contains a number of routines to generate test drawings for reportlab/graphics. For now they are contrived, but we will expand them to try and trip up any parser. Feel free to add more.
- reportlab.graphics.testdrawings.getDrawing1()
Hello World, on a rectangular background
- reportlab.graphics.testdrawings.getDrawing2()
This demonstrates the basic shapes. There are no groups or references. Each solid shape should have a purple fill.
reportlab.graphics.testshapes
Execute this script to see some test drawings.
This contains a number of routines to generate test drawings for reportlab/graphics. For now many of them are contrived, but we will expand them to try and trip up any parser. Feel free to add more.
- class reportlab.graphics.testshapes.ShapesTestCase(methodName='runTest')
Test generating all kinds of shapes.
- setUp()
Prepare some things before the tests start.
- tearDown()
Do what has to be done after the tests are over.
- testAllDrawings()
Make a list of drawings.
- reportlab.graphics.testshapes.getAllFunctionDrawingNames(doTTF=1)
Get a list of drawing function names from somewhere.
- reportlab.graphics.testshapes.getAllTestDrawings(doTTF=1)
- reportlab.graphics.testshapes.getDrawing01()
Hello World, on a rectangular background.
The rectangle’s fillColor is yellow. The string’s fillColor is red.
- reportlab.graphics.testshapes.getDrawing02()
Various Line shapes.
The lines are blue and their strokeWidth is 5 mm. One line has a strokeDashArray set to [5, 10, 15].
- reportlab.graphics.testshapes.getDrawing03()
Text strings in various sizes and different fonts.
Font size increases from 12 to 36 and from bottom left to upper right corner. The first ones should be in Times-Roman. Finally, a solitary Courier string at the top right corner.
- reportlab.graphics.testshapes.getDrawing04()
Text strings in various colours.
Colours are blue, yellow and red from bottom left to upper right.
- reportlab.graphics.testshapes.getDrawing05()
Text strings with various anchors (alignments).
Text alignment conforms to the anchors in the left column.
- reportlab.graphics.testshapes.getDrawing06()
This demonstrates all the basic shapes at once.
There are no groups or references. Each solid shape should have a green fill.
- reportlab.graphics.testshapes.getDrawing07()
This tests the ability to translate and rotate groups. The first set of axes should be near the bottom left of the drawing. The second should be rotated counterclockwise by 15 degrees. The third should be rotated by 30 degrees.
- reportlab.graphics.testshapes.getDrawing08()
This tests the ability to scale coordinates. The bottom left set of axes should be near the bottom left of the drawing. The bottom right should be stretched vertically by a factor of 2. The top left one should be stretched horizontally by a factor of 2. The top right should have the vertical axiss leaning over to the right by 30 degrees.
- reportlab.graphics.testshapes.getDrawing09()
This tests rotated strings
Some renderers will have a separate mechanism for font drawing. This test just makes sure strings get transformed the same way as regular graphics.
- reportlab.graphics.testshapes.getDrawing10()
This tests nested groups with multiple levels of coordinate transformation. Each box should be staggered up and to the right, moving by 25 points each time.
- reportlab.graphics.testshapes.getDrawing11()
test of anchoring
- reportlab.graphics.testshapes.getDrawing12()
Text strings in a non-standard font. All that is required is to place the .afm and .pfb files on the font path given in rl_config.py, for example in reportlab/fonts/.
- reportlab.graphics.testshapes.getDrawing13()
Test Various TTF Fonts
- reportlab.graphics.testshapes.getDrawing14()
test shapes.Image
- reportlab.graphics.testshapes.getFailedDrawing(funcName)
Generate a drawing in case something goes really wrong.
This will create a drawing to be displayed whenever some other drawing could not be executed, because the generating function does something terribly wrong! The box contains an attention triangle, plus some error message.
- reportlab.graphics.testshapes.makeSuite()
Make a test suite for unit testing.
- reportlab.graphics.testshapes.resetFonts()
- reportlab.graphics.testshapes.smallArrow()
create a small PIL image
- reportlab.graphics.testshapes.writePDF(drawings)
Create and save a PDF file containing some drawings.
reportlab.graphics.transform
functions for 2D affine transformations
- reportlab.graphics.transform.inverse(A)
For A affine 2D represented as 6vec return 6vec version of A**(-1)
- reportlab.graphics.transform.mmult(A, B)
A postmultiplied by B
- reportlab.graphics.transform.nullTransform()
- reportlab.graphics.transform.rotate(angle, cx=0, cy=0)
- reportlab.graphics.transform.scale(sx, sy=1)
- reportlab.graphics.transform.skewX(angle)
- reportlab.graphics.transform.skewY(angle)
- reportlab.graphics.transform.transformPoint(A, v)
Apply transformation a to vector v –> A*v
- reportlab.graphics.transform.transformPoints(matrix, V)
- reportlab.graphics.transform.translate(dx, dy=0)
- reportlab.graphics.transform.zTransformPoint(A, v)
Apply the homogenous part of atransformation a to vector v –> A*v
- reportlab.graphics.transform.zTransformPoints(matrix, V)
reportlab.graphics.utils
- exception reportlab.graphics.utils.RenderPMError
- reportlab.graphics.utils.pathNumTrunc(n)
- reportlab.graphics.utils.processGlyph(*args, **kwds)
- reportlab.graphics.utils.setFont(*args, **kwds)
- reportlab.graphics.utils.text2Path(text, x=0, y=0, fontName='Times-Roman', fontSize=1000, anchor='start', truncate=1, pathReverse=0, gs=None, **kwds)
- reportlab.graphics.utils.text2PathDescription(*args, **kwds)
reportlab.graphics.widgetbase
Base class for user-defined graphical widgets
- class reportlab.graphics.widgetbase.CandleStickProperties(**kwds)
- reportlab.graphics.widgetbase.CandleSticks(**kwds)
- class reportlab.graphics.widgetbase.Face
This draws a face with two eyes.
It exposes a couple of properties to configure itself and hides all other details.
- demo()
- draw()
- class reportlab.graphics.widgetbase.PropHolder
Base for property holders
- dumpProperties(prefix='')
Convenience. Lists them on standard output. You may provide a prefix - mostly helps to generate code samples for documentation.
- getProperties(recur=1)
Returns a list of all properties which can be edited and which are not marked as private. This may include ‘child widgets’ or ‘primitive shapes’. You are free to override this and provide alternative implementations; the default one simply returns everything without a leading underscore.
- setProperties(propDict)
Permits bulk setting of properties. These may include child objects e.g. “chart.legend.width = 200”.
All assignments will be validated by the object as if they were set individually in python code.
All properties of a top-level object are guaranteed to be set before any of the children, which may be helpful to widget designers.
- verify()
If the _attrMap attribute is not None, this checks all expected attributes are present; no unwanted attributes are present; and (if a checking function is found) checks each attribute has a valid value. Either succeeds or raises an informative exception.
- class reportlab.graphics.widgetbase.ScaleWidget(x=0, y=0, scale=1.0, contents=None)
Contents with a scale and offset
- draw()
- class reportlab.graphics.widgetbase.Sizer(*elements)
Container to show size of all enclosed objects
- add(node, name=None)
Appends non-None child node to the ‘contents’ attribute. In addition, if a name is provided, it is subsequently accessible by name
- draw()
- getBounds()
Return outer boundary as x1,y1,x2,y2. Can be overridden for efficiency
- class reportlab.graphics.widgetbase.StyleProperties(**kwargs)
A container class for attributes used in charts and legends.
Attributes contained can be those for any graphical element (shape?) in the ReportLab graphics package. The idea for this container class is to be useful in combination with legends and/or the individual appearance of data series in charts.
A legend could be as simple as a wrapper around a list of style properties, where the ‘desc’ attribute contains a descriptive string and the rest could be used by the legend e.g. to draw something like a color swatch. The graphical presentation of the legend would be its own business, though.
A chart could be inspecting a legend or, more directly, a list of style properties to pick individual attributes that it knows about in order to render a particular row of the data. A bar chart e.g. could simply use ‘strokeColor’ and ‘fillColor’ for drawing the bars while a line chart could also use additional ones like strokeWidth.
- class reportlab.graphics.widgetbase.TwoFaces
- demo()
The default case already looks good enough, no implementation needed here
- draw()
Just return a group
- class reportlab.graphics.widgetbase.TypedPropertyCollection(exampleClass, **kwds)
A container with properties for objects of the same kind.
This makes it easy to create lists of objects. You initialize it with a class of what it is to contain, and that is all you can add to it. You can assign properties to the collection as a whole, or to a numeric index within it; if so it creates a new child object to hold that data.
- So:
wedges = TypedPropertyCollection(WedgeProperties) wedges.strokeWidth = 2 # applies to all wedges.strokeColor = colors.red # applies to all wedges[3].strokeColor = colors.blue # only to one
The last line should be taken as a prescription of how to create wedge no. 3 if one is needed; no error is raised if there are only two data points.
- We try and make sensible use of tuple indices.
line[(3,x)] is backed by line[(3,)] == line[3] & line
- checkAttr(key, a, default=None)
- getProperties(recur=1)
Returns a list of all properties which can be edited and which are not marked as private. This may include ‘child widgets’ or ‘primitive shapes’. You are free to override this and provide alternative implementations; the default one simply returns everything without a leading underscore.
- setVector(**kw)
- wKlassFactory(Klass)
- class reportlab.graphics.widgetbase.Widget
Base for all user-defined widgets. Keep as simple as possible. Does not inherit from Shape so that we can rewrite shapes without breaking widgets and vice versa.
- demo()
- draw()
- getBounds()
Return outer boundary as x1,y1,x2,y2. Can be overridden for efficiency
- provideNode()
Override this to create your own node. This lets widgets be added to drawings; they must create a shape (typically a group) so that the renderer can draw the custom node.
- reportlab.graphics.widgetbase.isWKlass(obj)
- reportlab.graphics.widgetbase.test()
- reportlab.graphics.widgetbase.tpcGetItem(obj, x)
return obj if it’s not a TypedPropertyCollection else obj[x]
reportlab.graphics.barcode
Popular barcodes available as reusable widgets
- reportlab.graphics.barcode.createBarcodeDrawing(codeName, **options)
This creates and returns a drawing with a barcode.
- reportlab.graphics.barcode.createBarcodeImageInMemory(codeName, **options)
This creates and returns barcode as an image in memory. Takes same arguments as createBarcodeDrawing and also an optional format keyword which can be anything acceptable to Drawing.asString eg gif, pdf, tiff, py ……
- reportlab.graphics.barcode.getCodeNames()
Returns sorted list of supported bar code names
- reportlab.graphics.barcode.getCodes()
Returns a dict mapping code names to widgets
- reportlab.graphics.barcode.registerWidget(widget)
reportlab.graphics.barcode.code128
- class reportlab.graphics.barcode.code128.Code128(value='', **args)
Code 128 is a very compact symbology that can encode the entire 128 character ASCII set, plus 4 special control codes, (FNC1-FNC4, expressed in the input string as ñ to ô). Code 128 can also encode digits at double density (2 per byte) and has a mandatory checksum. Code 128 is well supported and commonly used – for example, by UPS for tracking labels.
Because of these qualities, Code 128 is probably the best choice for a linear symbology today (assuming you have a choice).
Options that may be passed to constructor:
- value (int, or numeric string. required.):
The value to encode.
- barWidth (float, default .0075):
X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils).
- barHeight (float, see default below):
Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol’s length.
- quiet (bool, default 1):
Wether to include quiet zones in the symbol.
- lquiet (float, see default below):
Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidth
- rquiet (float, defaults as above):
Quiet zone size to right left of code, if quiet is true.
Sources of Information on Code 128:
http://www.semiconductor.agilent.com/barcode/sg/Misc/code_128.html http://www.adams1.com/pub/russadam/128code.html http://www.barcodeman.com/c128.html
Official Spec, “ANSI/AIM BC4-1999, ISS” is available for US$45 from http://www.aimglobal.org/aimstore/
- barHeight = None
- barWidth = 0.54
- decompose()
- encode()
- lquiet = None
- quiet = 1
- rquiet = None
- validate()
- class reportlab.graphics.barcode.code128.Code128Auto(value='', **args)
contributed by https://bitbucket.org/kylemacfarlane/ see https://bitbucket.org/rptlab/reportlab/issues/69/implementations-of-code-128-auto-and-data
- encode()
reportlab.graphics.barcode.code39
- class reportlab.graphics.barcode.code39.Extended39(value='', **args)
Extended Code 39 is a convention for encoding additional characters not present in stanmdard Code 39 by using pairs of characters to represent the characters missing in Standard Code 39.
See Standard39 for arguments.
Sources of Information on Extended Code 39:
http://www.semiconductor.agilent.com/barcode/sg/Misc/xcode_39.html http://www.barcodeman.com/c39_ext.html
- encode()
- validate()
- class reportlab.graphics.barcode.code39.Standard39(value='', **args)
Options that may be passed to constructor:
- value (int, or numeric string required.):
The value to encode.
- barWidth (float, default .0075):
X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils).
- ratio (float, default 2.2):
The ratio of wide elements to narrow elements. Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the barWidth is greater than 20 mils (.02 inch))
- gap (float or None, default None):
width of intercharacter gap. None means “use barWidth”.
- barHeight (float, see default below):
Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol’s length.
- checksum (bool, default 1):
Wether to compute and include the check digit
- bearers (float, in units of barWidth. default 0):
Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers).
- quiet (bool, default 1):
Wether to include quiet zones in the symbol.
- lquiet (float, see default below):
Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or .15 times the symbol’s length.
- rquiet (float, defaults as above):
Quiet zone size to right left of code, if quiet is true.
- stop (bool, default 1):
Whether to include start/stop symbols.
Sources of Information on Code 39:
http://www.semiconductor.agilent.com/barcode/sg/Misc/code_39.html http://www.adams1.com/pub/russadam/39code.html http://www.barcodeman.com/c39_1.html
Official Spec, “ANSI/AIM BC1-1995, USS” is available for US$45 from http://www.aimglobal.org/aimstore/
- encode()
- validate()
reportlab.graphics.barcode.code93
- class reportlab.graphics.barcode.code93.Extended93(value='', **args)
Extended Code 93 is a convention for encoding the entire 128 character set using pairs of characters to represent the characters missing in Standard Code 93. It is very much like Extended Code 39 in that way.
See Standard93 for arguments.
- encode()
- validate()
- class reportlab.graphics.barcode.code93.Standard93(value='', **args)
Code 93 is a Uppercase alphanumeric symbology with some punctuation. See Extended Code 93 for a variant that can represent the entire 128 characrter ASCII set.
Options that may be passed to constructor:
- value (int, or numeric string. required.):
The value to encode.
- barWidth (float, default .0075):
X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils).
- barHeight (float, see default below):
Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol’s length.
- quiet (bool, default 1):
Wether to include quiet zones in the symbol.
- lquiet (float, see default below):
Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidth
- rquiet (float, defaults as above):
Quiet zone size to right left of code, if quiet is true.
- stop (bool, default 1):
Whether to include start/stop symbols.
Sources of Information on Code 93:
http://www.semiconductor.agilent.com/barcode/sg/Misc/code_93.html
Official Spec, “NSI/AIM BC5-1995, USS” is available for US$45 from http://www.aimglobal.org/aimstore/
- encode()
- validate()
reportlab.graphics.barcode.common
- class reportlab.graphics.barcode.common.Barcode(value='', **kwd)
Abstract Base for barcodes. Includes implementations of some methods suitable for the more primitive barcode types
- annotate(x, y, text, fontName, fontSize, anchor='middle')
- computeSize(*args)
- decompose()
- draw()
- drawHumanReadable()
- encode()
- fontName = 'Courier'
- fontSize = 12
- property height
- humanReadable = 0
- rect(x, y, w, h)
- validate()
- property width
- class reportlab.graphics.barcode.common.Codabar(value='', **args)
Codabar is a numeric plus some puntuation (“-$:/.+”) barcode with four start/stop characters (A, B, C, and D).
Options that may be passed to constructor:
- value (string required.):
The value to encode.
- barWidth (float, default .0065):
X-Dimension, or width of the smallest element minimum is 6.5 mils (.0065 inch)
- ratio (float, default 2.0):
The ratio of wide elements to narrow elements.
- gap (float or None, default None):
width of intercharacter gap. None means “use barWidth”.
- barHeight (float, see default below):
Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol’s length.
- checksum (bool, default 0):
Whether to compute and include the check digit
- bearers (float, in units of barWidth. default 0):
Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers).
- quiet (bool, default 1):
Whether to include quiet zones in the symbol.
- stop (bool, default 1):
Whether to include start/stop symbols.
- lquiet (float, see default below):
Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidth
- rquiet (float, defaults as above):
Quiet zone size to right left of code, if quiet is true.
Sources of Information on Codabar
http://www.semiconductor.agilent.com/barcode/sg/Misc/codabar.html http://www.barcodeman.com/codabar.html
Official Spec, “ANSI/AIM BC3-1995, USS” is available for US$45 from http://www.aimglobal.org/aimstore/
- barHeight = None
- barWidth = 0.46799999999999997
- bearers = 0.0
- chars = '0123456789-$:/.+'
- checksum = 0
- decompose()
- encode()
- lquiet = None
- patterns = {'$': 'bsBSbsb', '+': 'bsBsBsB', '-': 'bsbSBsb', '.': 'BsBsBsb', '/': 'BsBsbsB', '0': 'bsbsbSB', '1': 'bsbsBSb', '2': 'bsbSbsB', '3': 'BSbsbsb', '4': 'bsBsbSb', '5': 'BsbsbSb', '6': 'bSbsbsB', '7': 'bSbsBsb', '8': 'bSBsbsb', '9': 'BsbSbsb', ':': 'BsbsBsB', 'A': 'bsBSbSb', 'B': 'bSbSbsB', 'C': 'bsbSbSB', 'D': 'bsbSBSb'}
- quiet = 1
- ratio = 2.0
- rquiet = None
- stop = 1
- validate()
- values = {'$': 11, '+': 15, '-': 10, '.': 14, '/': 13, '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, ':': 12, 'A': 16, 'B': 17, 'C': 18, 'D': 19}
- class reportlab.graphics.barcode.common.Code11(value='', **args)
Code 11 is an almost-numeric barcode. It encodes the digits 0-9 plus dash (“-“). 11 characters total, hence the name.
- value (int or string required.):
The value to encode.
- barWidth (float, default .0075):
X-Dimension, or width of the smallest element
- ratio (float, default 2.2):
The ratio of wide elements to narrow elements.
- gap (float or None, default None):
width of intercharacter gap. None means “use barWidth”.
- barHeight (float, see default below):
Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol’s length.
- checksum (0 none, 1 1-digit, 2 2-digit, -1 auto, default -1):
How many checksum digits to include. -1 (“auto”) means 1 if the number of digits is 10 or less, else 2.
- bearers (float, in units of barWidth. default 0):
Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers).
- quiet (bool, default 1):
Wether to include quiet zones in the symbol.
- lquiet (float, see default below):
Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidth
- rquiet (float, defaults as above):
Quiet zone size to right left of code, if quiet is true.
Sources of Information on Code 11:
http://www.cwi.nl/people/dik/english/codes/barcodes.html
- barHeight = None
- barWidth = 0.54
- bearers = 0.0
- chars = '0123456789-'
- checksum = -1
- decompose()
- encode()
- lquiet = None
- patterns = {'-': 'bsBsb', '0': 'bsbsB', '1': 'BsbsB', '2': 'bSbsB', '3': 'BSbsb', '4': 'bsBsB', '5': 'BsBsb', '6': 'bSBsb', '7': 'bsbSB', '8': 'BsbSb', '9': 'Bsbsb', 'S': 'bsBSb'}
- quiet = 1
- ratio = 2.2
- rquiet = None
- stop = 1
- validate()
- values = {'-': 10, '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
- class reportlab.graphics.barcode.common.I2of5(value='', **args)
Interleaved 2 of 5 is a numeric-only barcode. It encodes an even number of digits; if an odd number is given, a 0 is prepended.
Options that may be passed to constructor:
- value (int, or numeric string required.):
The value to encode.
- barWidth (float, default .0075):
X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils).
- ratio (float, default 2.2):
The ratio of wide elements to narrow elements. Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the barWidth is greater than 20 mils (.02 inch))
- gap (float or None, default None):
width of intercharacter gap. None means “use barWidth”.
- barHeight (float, see default below):
Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol’s length.
- checksum (bool, default 1):
Whether to compute and include the check digit
- bearers (float, in units of barWidth. default 3.0):
Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 3 x-dimensions. Set to zero for no bearer bars. (Bearer bars help detect misscans, so it is suggested to leave them on).
- bearerBox (bool default False)
if true draw a true rectangle of width bearers around the barcode.
- quiet (bool, default 1):
Whether to include quiet zones in the symbol.
- lquiet (float, see default below):
Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or .15 times the symbol’s length.
- rquiet (float, defaults as above):
Quiet zone size to right left of code, if quiet is true.
- stop (bool, default 1):
Whether to include start/stop symbols.
Sources of Information on Interleaved 2 of 5:
http://www.semiconductor.agilent.com/barcode/sg/Misc/i_25.html http://www.adams1.com/pub/russadam/i25code.html
Official Spec, “ANSI/AIM BC2-1995, USS” is available for US$45 from http://www.aimglobal.org/aimstore/
- barHeight = None
- barWidth = 0.54
- bearerBox = False
- bearers = 3.0
- checksum = 1
- decompose()
- encode()
- lquiet = None
- patterns = {'B0': 'bbBBb', 'B1': 'BbbbB', 'B2': 'bBbbB', 'B3': 'BBbbb', 'B4': 'bbBbB', 'B5': 'BbBbb', 'B6': 'bBBbb', 'B7': 'bbbBB', 'B8': 'BbbBb', 'B9': 'bBbBb', 'S0': 'ssSSs', 'S1': 'SsssS', 'S2': 'sSssS', 'S3': 'SSsss', 'S4': 'ssSsS', 'S5': 'SsSss', 'S6': 'sSSss', 'S7': 'sssSS', 'S8': 'SssSs', 'S9': 'sSsSs', 'start': 'bsbs', 'stop': 'Bsb'}
- quiet = 1
- ratio = 2.2
- rquiet = None
- stop = 1
- validate()
- class reportlab.graphics.barcode.common.MSI(value='', **args)
MSI is a numeric-only barcode.
Options that may be passed to constructor:
- value (int, or numeric string required.):
The value to encode.
- barWidth (float, default .0075):
X-Dimension, or width of the smallest element
- ratio (float, default 2.2):
The ratio of wide elements to narrow elements.
- gap (float or None, default None):
width of intercharacter gap. None means “use barWidth”.
- barHeight (float, see default below):
Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol’s length.
- checksum (bool, default 1):
Wether to compute and include the check digit
- bearers (float, in units of barWidth. default 0):
Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers).
- lquiet (float, see default below):
Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidths.
- rquiet (float, defaults as above):
Quiet zone size to right left of code, if quiet is true.
- stop (bool, default 1):
Whether to include start/stop symbols.
Sources of Information on MSI Bar Code:
http://www.semiconductor.agilent.com/barcode/sg/Misc/msi_code.html http://www.adams1.com/pub/russadam/plessy.html
- barHeight = None
- barWidth = 0.54
- bearers = 0.0
- checksum = 1
- decompose()
- encode()
- lquiet = None
- patterns = {'0': 'bSbSbSbS', '1': 'bSbSbSBs', '2': 'bSbSBsbS', '3': 'bSbSBsBs', '4': 'bSBsbSbS', '5': 'bSBsbSBs', '6': 'bSBsBsbS', '7': 'bSBsBsBs', '8': 'BsbSbSbS', '9': 'BsbSbSBs', 'start': 'Bs', 'stop': 'bSb'}
- quiet = 1
- ratio = 2.2
- rquiet = None
- stop = 1
- validate()
reportlab.graphics.barcode.dmtx
reportlab.graphics.barcode.eanbc
- class reportlab.graphics.barcode.eanbc.Ean13BarcodeWidget(value='123456789012', **kw)
- barFillColor = Color(0,0,0,1)
- barHeight = 73.50236220472442
- barStrokeColor = None
- barStrokeWidth = 0
- barWidth = 0.9354330708661419
- codeName = 'EAN13'
- draw()
- fontName = 'Helvetica'
- fontSize = 8
- humanReadable = 1
- lquiet = None
- quiet = 1
- rquiet = None
- textColor = Color(0,0,0,1)
- property width
- wrap(aW, aH)
- x = 0
- y = 0
- class reportlab.graphics.barcode.eanbc.Ean5BarcodeWidget(value='123456789012', **kw)
- EAN-5 barcodes can print the human readable price, set:
price=True
- codeName = 'EAN5'
- draw()
- class reportlab.graphics.barcode.eanbc.Ean8BarcodeWidget(value='123456789012', **kw)
- codeName = 'EAN8'
- class reportlab.graphics.barcode.eanbc.ISBNBarcodeWidget(value='123456789012', **kw)
ISBN Barcodes optionally print the EAN-5 supplemental price barcode (with the price in dollars or pounds). Set price to a string that follows the EAN-5 for ISBN spec:
- leading digit 0, 1 = GBP
3 = AUD 4 = NZD 5 = USD 6 = CAD
next 4 digits = price between 00.00 and 99.98, i.e.:
price=’52499’ # $24.99 USD
- codeName = 'ISBN'
- draw()
reportlab.graphics.barcode.ecc200datamatrix
reportlab.graphics.barcode.fourstate
reportlab.graphics.barcode.lto
- class reportlab.graphics.barcode.lto.BaseLTOLabel(prefix='', number=None, subtype='1', border=None, checksum=False, availheight=None)
Base class for LTO labels.
Specification taken from “IBM LTO Ultrium Cartridge Label Specification, Revision 3” available on May 14th 2008 from : http://www-1.ibm.com/support/docview.wss?rs=543&context=STCVQ6R&q1=ssg1*&uid=ssg1S7000429&loc=en_US&cs=utf-8&lang=en+en
- CODEBARHEIGHT = 31.46456692913386
- CODEBARWIDTH = 1.2245669291338583
- CODEGAP = 1.2245669291338583
- CODELQUIET = 12.245669291338583
- CODENOMINALWIDTH = 210.01322834645669
- CODERATIO = 2.75
- CODERQUIET = 12.245669291338583
- LABELHEIGHT = 48.188976377952756
- LABELROUND = 4.251968503937007
- LABELWIDTH = 223.93700787401576
- drawOn(canvas, x, y)
Draws the LTO label onto the canvas.
- class reportlab.graphics.barcode.lto.VerticalLTOLabel(*args, **kwargs)
A class for LTO labels with rectangular blocks around the tape identifier.
- BLOCKHEIGHT = 12.755905511811024
- BLOCKWIDTH = 28.346456692913385
- COLORSCHEME = ('red', 'yellow', 'lightgreen', 'lightblue', 'grey', 'orangered', 'pink', 'darkgreen', 'orange', 'purple')
- LABELFONT = ('Helvetica-Bold', 14)
- LINEWIDTH = 0.0125
- NBBLOCKS = 7
- drawOn(canvas, x, y)
Draws some blocks around the identifier’s characters.
- reportlab.graphics.barcode.lto.test()
Test this.
reportlab.graphics.barcode.qr
- class reportlab.graphics.barcode.qr.QrCode(value=None, **kw)
- addData(value)
- draw()
- height = 90.70866141732284
- qrBorder = 4
- qrLevel = 'L'
- qrVersion = None
- rect(x, y, w, h)
- value = None
- width = 90.70866141732284
- class reportlab.graphics.barcode.qr.QrCodeWidget(value='Hello World', **kw)
- addData(value)
- barBorder = 4
- barFillColor = Color(0,0,0,1)
- barHeight = 90.70866141732284
- barLevel = 'L'
- barStrokeColor = None
- barStrokeWidth = 0
- barWidth = 90.70866141732284
- codeName = 'QR'
- draw()
- qrVersion = None
- value = None
- x = 0
- y = 0
- class reportlab.graphics.barcode.qr.SRect(x, y, width, height, fillColor=Color(0, 0, 0, 1))
reportlab.graphics.barcode.qrencoder
- class reportlab.graphics.barcode.qrencoder.QR(data)
- property bitlength
- bits = None
- getLength()
- getLengthBits(ver)
- group = 0
- valid = None
- write(buffer, version)
- write_header(buffer, version)
- class reportlab.graphics.barcode.qrencoder.QR8bitByte(data)
- bits = (8,)
- group = 1
- lengthbits = (8, 16, 16)
- mode = 4
- write(buffer, version)
- class reportlab.graphics.barcode.qrencoder.QRAlphaNum(data)
- bits = (6, 5)
- chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'
- group = 2
- lengthbits = (9, 11, 13)
- mode = 2
- valid(string, pos=0, endpos=9223372036854775807)
Matches zero or more characters at the beginning of the string.
- class reportlab.graphics.barcode.qrencoder.QRBitBuffer
- get(index)
- getLengthInBits()
- put(num, length)
- putBit(bit)
- class reportlab.graphics.barcode.qrencoder.QRCode(version, errorCorrectLevel)
- PAD0 = 236
- PAD1 = 17
- addData(data)
- calculate_version()
- static createBytes(buffer, rsBlocks)
- static createData(version, errorCorrectLevel, dataList)
- dataBitIterator(data)
- dataPosIterator()
- getBestMaskPattern()
- getModuleCount()
- isDark(row, col)
- make()
- makeImpl(test, maskPattern)
- mapData(data, maskPattern)
- setupPositionAdjustPattern()
- setupPositionProbePattern(row, col)
- setupTimingPattern()
- setupTypeInfo(test, maskPattern)
- setupTypeNumber(test)
- class reportlab.graphics.barcode.qrencoder.QRECI(data)
- lengthbits = (0, 0, 0)
- mode = 7
- write(buffer, version)
- class reportlab.graphics.barcode.qrencoder.QRFNC1First
- lengthbits = (0, 0, 0)
- mode = 5
- write(buffer, version)
- class reportlab.graphics.barcode.qrencoder.QRFNC1Second(data)
- lengthbits = (0, 0, 0)
- mode = 9
- valid(string, pos=0, endpos=9223372036854775807)
Matches zero or more characters at the beginning of the string.
- write(buffer, version)
- class reportlab.graphics.barcode.qrencoder.QRHanzi(data)
- bits = (13,)
- group = 1
- lengthbits = (8, 10, 12)
- mode = 13
- unicode_to_qrhanzi(data)
- write(buffer, version)
- write_header(buffer, version)
- class reportlab.graphics.barcode.qrencoder.QRKanji(data)
- bits = (13,)
- group = 1
- lengthbits = (8, 10, 12)
- mode = 8
- unicode_to_qrkanji(data)
- write(buffer, version)
- class reportlab.graphics.barcode.qrencoder.QRMaskPattern
- PATTERN000 = 0
- PATTERN001 = 1
- PATTERN010 = 2
- PATTERN011 = 3
- PATTERN100 = 4
- PATTERN101 = 5
- PATTERN110 = 6
- PATTERN111 = 7
- class reportlab.graphics.barcode.qrencoder.QRNumber(data)
- bits = (4, 3, 3)
- chars = '0123456789'
- group = 3
- lengthbits = (10, 12, 14)
- mode = 1
- valid(string, pos=0, endpos=9223372036854775807)
Matches zero or more characters at the beginning of the string.
- class reportlab.graphics.barcode.qrencoder.QRPolynomial(num, shift)
- get(index)
- getLength()
- mod(e)
- multiply(e)
- class reportlab.graphics.barcode.qrencoder.QRRSBlock(totalCount, dataCount)
- RS_BLOCK_TABLE = [[1, 26, 19], [1, 26, 16], [1, 26, 13], [1, 26, 9], [1, 44, 34], [1, 44, 28], [1, 44, 22], [1, 44, 16], [1, 70, 55], [1, 70, 44], [2, 35, 17], [2, 35, 13], [1, 100, 80], [2, 50, 32], [2, 50, 24], [4, 25, 9], [1, 134, 108], [2, 67, 43], [2, 33, 15, 2, 34, 16], [2, 33, 11, 2, 34, 12], [2, 86, 68], [4, 43, 27], [4, 43, 19], [4, 43, 15], [2, 98, 78], [4, 49, 31], [2, 32, 14, 4, 33, 15], [4, 39, 13, 1, 40, 14], [2, 121, 97], [2, 60, 38, 2, 61, 39], [4, 40, 18, 2, 41, 19], [4, 40, 14, 2, 41, 15], [2, 146, 116], [3, 58, 36, 2, 59, 37], [4, 36, 16, 4, 37, 17], [4, 36, 12, 4, 37, 13], [2, 86, 68, 2, 87, 69], [4, 69, 43, 1, 70, 44], [6, 43, 19, 2, 44, 20], [6, 43, 15, 2, 44, 16], [4, 101, 81], [1, 80, 50, 4, 81, 51], [4, 50, 22, 4, 51, 23], [3, 36, 12, 8, 37, 13], [2, 116, 92, 2, 117, 93], [6, 58, 36, 2, 59, 37], [4, 46, 20, 6, 47, 21], [7, 42, 14, 4, 43, 15], [4, 133, 107], [8, 59, 37, 1, 60, 38], [8, 44, 20, 4, 45, 21], [12, 33, 11, 4, 34, 12], [3, 145, 115, 1, 146, 116], [4, 64, 40, 5, 65, 41], [11, 36, 16, 5, 37, 17], [11, 36, 12, 5, 37, 13], [5, 109, 87, 1, 110, 88], [5, 65, 41, 5, 66, 42], [5, 54, 24, 7, 55, 25], [11, 36, 12], [5, 122, 98, 1, 123, 99], [7, 73, 45, 3, 74, 46], [15, 43, 19, 2, 44, 20], [3, 45, 15, 13, 46, 16], [1, 135, 107, 5, 136, 108], [10, 74, 46, 1, 75, 47], [1, 50, 22, 15, 51, 23], [2, 42, 14, 17, 43, 15], [5, 150, 120, 1, 151, 121], [9, 69, 43, 4, 70, 44], [17, 50, 22, 1, 51, 23], [2, 42, 14, 19, 43, 15], [3, 141, 113, 4, 142, 114], [3, 70, 44, 11, 71, 45], [17, 47, 21, 4, 48, 22], [9, 39, 13, 16, 40, 14], [3, 135, 107, 5, 136, 108], [3, 67, 41, 13, 68, 42], [15, 54, 24, 5, 55, 25], [15, 43, 15, 10, 44, 16], [4, 144, 116, 4, 145, 117], [17, 68, 42], [17, 50, 22, 6, 51, 23], [19, 46, 16, 6, 47, 17], [2, 139, 111, 7, 140, 112], [17, 74, 46], [7, 54, 24, 16, 55, 25], [34, 37, 13], [4, 151, 121, 5, 152, 122], [4, 75, 47, 14, 76, 48], [11, 54, 24, 14, 55, 25], [16, 45, 15, 14, 46, 16], [6, 147, 117, 4, 148, 118], [6, 73, 45, 14, 74, 46], [11, 54, 24, 16, 55, 25], [30, 46, 16, 2, 47, 17], [8, 132, 106, 4, 133, 107], [8, 75, 47, 13, 76, 48], [7, 54, 24, 22, 55, 25], [22, 45, 15, 13, 46, 16], [10, 142, 114, 2, 143, 115], [19, 74, 46, 4, 75, 47], [28, 50, 22, 6, 51, 23], [33, 46, 16, 4, 47, 17], [8, 152, 122, 4, 153, 123], [22, 73, 45, 3, 74, 46], [8, 53, 23, 26, 54, 24], [12, 45, 15, 28, 46, 16], [3, 147, 117, 10, 148, 118], [3, 73, 45, 23, 74, 46], [4, 54, 24, 31, 55, 25], [11, 45, 15, 31, 46, 16], [7, 146, 116, 7, 147, 117], [21, 73, 45, 7, 74, 46], [1, 53, 23, 37, 54, 24], [19, 45, 15, 26, 46, 16], [5, 145, 115, 10, 146, 116], [19, 75, 47, 10, 76, 48], [15, 54, 24, 25, 55, 25], [23, 45, 15, 25, 46, 16], [13, 145, 115, 3, 146, 116], [2, 74, 46, 29, 75, 47], [42, 54, 24, 1, 55, 25], [23, 45, 15, 28, 46, 16], [17, 145, 115], [10, 74, 46, 23, 75, 47], [10, 54, 24, 35, 55, 25], [19, 45, 15, 35, 46, 16], [17, 145, 115, 1, 146, 116], [14, 74, 46, 21, 75, 47], [29, 54, 24, 19, 55, 25], [11, 45, 15, 46, 46, 16], [13, 145, 115, 6, 146, 116], [14, 74, 46, 23, 75, 47], [44, 54, 24, 7, 55, 25], [59, 46, 16, 1, 47, 17], [12, 151, 121, 7, 152, 122], [12, 75, 47, 26, 76, 48], [39, 54, 24, 14, 55, 25], [22, 45, 15, 41, 46, 16], [6, 151, 121, 14, 152, 122], [6, 75, 47, 34, 76, 48], [46, 54, 24, 10, 55, 25], [2, 45, 15, 64, 46, 16], [17, 152, 122, 4, 153, 123], [29, 74, 46, 14, 75, 47], [49, 54, 24, 10, 55, 25], [24, 45, 15, 46, 46, 16], [4, 152, 122, 18, 153, 123], [13, 74, 46, 32, 75, 47], [48, 54, 24, 14, 55, 25], [42, 45, 15, 32, 46, 16], [20, 147, 117, 4, 148, 118], [40, 75, 47, 7, 76, 48], [43, 54, 24, 22, 55, 25], [10, 45, 15, 67, 46, 16], [19, 148, 118, 6, 149, 119], [18, 75, 47, 31, 76, 48], [34, 54, 24, 34, 55, 25], [20, 45, 15, 61, 46, 16]]
- static getRSBlocks(version, errorCorrectLevel)
- static getRsBlockTable(version, errorCorrectLevel)
- class reportlab.graphics.barcode.qrencoder.QRStructAppend(part, total, parity)
- lengthbits = (0, 0, 0)
- mode = 3
- write(buffer, version)
- class reportlab.graphics.barcode.qrencoder.QRUtil
- G15 = 1335
- G15_MASK = 21522
- G18 = 7973
- PATTERN_POSITION_TABLE = [[], [6, 18], [6, 22], [6, 26], [6, 30], [6, 34], [6, 22, 38], [6, 24, 42], [6, 26, 46], [6, 28, 50], [6, 30, 54], [6, 32, 58], [6, 34, 62], [6, 26, 46, 66], [6, 26, 48, 70], [6, 26, 50, 74], [6, 30, 54, 78], [6, 30, 56, 82], [6, 30, 58, 86], [6, 34, 62, 90], [6, 28, 50, 72, 94], [6, 26, 50, 74, 98], [6, 30, 54, 78, 102], [6, 28, 54, 80, 106], [6, 32, 58, 84, 110], [6, 30, 58, 86, 114], [6, 34, 62, 90, 118], [6, 26, 50, 74, 98, 122], [6, 30, 54, 78, 102, 126], [6, 26, 52, 78, 104, 130], [6, 30, 56, 82, 108, 134], [6, 34, 60, 86, 112, 138], [6, 30, 58, 86, 114, 142], [6, 34, 62, 90, 118, 146], [6, 30, 54, 78, 102, 126, 150], [6, 24, 50, 76, 102, 128, 154], [6, 28, 54, 80, 106, 132, 158], [6, 32, 58, 84, 110, 136, 162], [6, 26, 54, 82, 110, 138, 166], [6, 30, 58, 86, 114, 142, 170]]
- static getBCHDigit(data)
- static getBCHTypeInfo(data)
- static getBCHTypeNumber(data)
- static getErrorCorrectPolynomial(errorCorrectLength)
- classmethod getLostPoint(qrCode)
- classmethod getMask(maskPattern)
- static getPatternPosition(version)
- maskPattern = {0: <function QRUtil.<lambda>>, 1: <function QRUtil.<lambda>>, 2: <function QRUtil.<lambda>>, 3: <function QRUtil.<lambda>>, 4: <function QRUtil.<lambda>>, 5: <function QRUtil.<lambda>>, 6: <function QRUtil.<lambda>>, 7: <function QRUtil.<lambda>>}
- classmethod maskScoreRule1vert(modules)
- classmethod maskScoreRule2(modules)
- classmethod maskScoreRule3hor(modules, pattern=[True, False, True, True, True, False, True, False, False, False, False])
- classmethod maskScoreRule4(modules)
reportlab.graphics.barcode.test
- reportlab.graphics.barcode.test.fullTest(fileName='test_full.pdf')
Creates large-ish test document with a variety of parameters
- reportlab.graphics.barcode.test.run()
reportlab.graphics.barcode.usps
- class reportlab.graphics.barcode.usps.FIM(value='', **args)
FIM (Facing ID Marks) encode only one letter. There are currently four defined:
A Courtesy reply mail with pre-printed POSTNET B Business reply mail without pre-printed POSTNET C Business reply mail with pre-printed POSTNET D OCR Readable mail without pre-printed POSTNET
Options that may be passed to constructor:
- value (single character string from the set A - D. required.):
The value to encode.
- quiet (bool, default 0):
Whether to include quiet zones in the symbol.
The following may also be passed, but doing so will generate nonstandard symbols which should not be used. This is mainly documented here to show the defaults:
- barHeight (float, default 5/8 inch):
Height of the code. This might legitimately be overriden to make a taller symbol that will ‘bleed’ off the edge of the paper, leaving 5/8 inch remaining.
- lquiet (float, default 1/4 inch):
Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or .15 times the symbol’s length.
- rquiet (float, default 15/32 inch):
Quiet zone size to right left of code, if quiet is true.
Sources of information on FIM:
USPS Publication 25, A Guide to Business Mail Preparation http://new.usps.com/cpim/ftp/pubs/pub25.pdf
- barHeight = 45.0
- barWidth = 2.25
- computeSize()
- decompose()
- draw()
- lquiet = 33.75
- quiet = 0
- rquiet = 18.0
- spaceWidth = 4.5
- validate()
- class reportlab.graphics.barcode.usps.POSTNET(value='', **args)
POSTNET is used in the US to encode “zip codes” (postal codes) on mail. It can encode 5, 9, or 11 digit codes. I’ve read that it’s pointless to do 5 digits, since USPS will just have to re-print them with 9 or 11 digits.
Sources of information on POSTNET:
USPS Publication 25, A Guide to Business Mail Preparation http://new.usps.com/cpim/ftp/pubs/pub25.pdf
- barHeight = 9.0
- barWidth = 1.2959999999999998
- computeSize()
- decompose()
- draw()
- encode()
- quiet = 0
- shortHeight = 3.6
- spaceWidth = 1.98
- validate()
reportlab.graphics.barcode.usps4s
- class reportlab.graphics.barcode.usps4s.USPS_4State(value='01234567094987654321', routing='', **kwd)
USPS 4-State OneView (TM) barcode. All info from USPS-B-3200A
- annotate(x, y, text, fontName, fontSize, anchor='middle')
- property barHeight
- property barWidth
- property barcodes
Get 4 state bar codes for current routing and tracking >>> print(USPS_4State(‘01234567094987654321’,’01234567891’).barcodes) AADTFFDFTDADTAADAATFDTDDAAADDTDTTDAFADADDDTFFFDDTTTADFAAADFTDAADA
- property binary
convert the 4 state string values to binary >>> print(nhex(USPS_4State(‘01234567094987654321’,’’).binary)) 0x1122103b5c2004b1 >>> print(nhex(USPS_4State(‘01234567094987654321’,’01234’).binary)) 0xd138a87bab5cf3804b1 >>> print(nhex(USPS_4State(‘01234567094987654321’,’012345678’).binary)) 0x202bdc097711204d21804b1 >>> print(nhex(USPS_4State(‘01234567094987654321’,’01234567891’).binary)) 0x16907b2a24abc16a2e5c004b1
- bottoms = {'A': (-0.0195, -0.0285), 'D': (-0.0625, -0.0825), 'F': (-0.0625, -0.0825), 'T': (-0.0195, -0.0285)}
- property characters
convert own codewords to characters >>> print(’ ‘.join(hex(c)[2:] for c in USPS_4State(‘01234567094987654321’,’01234567891’).characters)) dcb 85c 8e4 b06 6dd 1740 17c6 1200 123f 1b2b
- property codewords
convert binary value into codewords >>> print(USPS_4State(‘01234567094987654321’,’01234567891’).codewords) (673, 787, 607, 1022, 861, 19, 816, 1294, 35, 602)
- computeSize()
- dimensions = {'hcz': (0.125, 0.125), 'pitch': (0.0416, 0.05), 'vcz': (0.028, 0.028), 'width': (0.015, 0.025)}
- draw()
- drawHumanReadable()
- property fontSize
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4
- property height
- property heightScale
- property heightSize
- property horizontalClearZone
- property humanReadable
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4
- property pitch
- property routing
- static scale(kind, D, s)
- property table1
- property table2
- table4 = ((7, 2, 4, 3), (1, 10, 0, 0), (9, 12, 2, 8), (5, 5, 6, 11), (8, 9, 3, 1), (0, 1, 5, 12), (2, 5, 1, 8), (4, 4, 9, 11), (6, 3, 8, 10), (3, 9, 7, 6), (5, 11, 1, 4), (8, 5, 2, 12), (9, 10, 0, 2), (7, 1, 6, 7), (3, 6, 4, 9), (0, 3, 8, 6), (6, 4, 2, 7), (1, 1, 9, 9), (7, 10, 5, 2), (4, 0, 3, 8), (6, 2, 0, 4), (8, 11, 1, 0), (9, 8, 3, 12), (2, 6, 7, 7), (5, 1, 4, 10), (1, 12, 6, 9), (7, 3, 8, 0), (5, 8, 9, 7), (4, 6, 2, 10), (3, 4, 0, 5), (8, 4, 5, 7), (7, 11, 1, 9), (6, 0, 9, 6), (0, 6, 4, 8), (2, 1, 3, 2), (5, 9, 8, 12), (4, 11, 6, 1), (9, 5, 7, 4), (3, 3, 1, 2), (0, 7, 2, 0), (1, 3, 4, 1), (6, 10, 3, 5), (8, 7, 9, 4), (2, 11, 5, 6), (0, 8, 7, 12), (4, 2, 8, 1), (5, 10, 3, 0), (9, 3, 0, 9), (6, 5, 2, 4), (7, 8, 1, 7), (5, 0, 4, 5), (2, 3, 0, 10), (6, 12, 9, 2), (3, 11, 1, 6), (8, 8, 7, 9), (5, 4, 0, 11), (1, 5, 2, 2), (9, 1, 4, 12), (8, 3, 6, 6), (7, 0, 3, 7), (4, 7, 7, 5), (0, 12, 1, 11), (2, 9, 9, 0), (6, 8, 5, 3), (3, 10, 8, 2))
- tops = {'A': (0.0625, 0.0825), 'D': (0.0195, 0.0285), 'F': (0.0625, 0.0825), 'T': (0.0195, 0.0285)}
- property tracking
- property value
- property verticalClearZone
- property width
- property widthScale
- property widthSize
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
reportlab.graphics.barcode.widgets
- class reportlab.graphics.barcode.widgets.BarcodeCodabar(**kw)
Used in blood banks, photo labs and FedEx labels. Encodes 0-9, -$:/.+, and four start/stop characters A-D.
- codeName = 'Codabar'
- class reportlab.graphics.barcode.widgets.BarcodeCode11(**kw)
Used mostly for labelling telecommunications equipment. It encodes numeric digits.
- codeName = 'Code11'
- class reportlab.graphics.barcode.widgets.BarcodeCode128(**kw)
Code 128 encodes any number of characters in the ASCII character set.
- codeName = 'Code128'
- class reportlab.graphics.barcode.widgets.BarcodeExtended39(**kw)
Extended 39 encodes the full ASCII character set by encoding characters as pairs of Code 39 characters; $, /, % and + are used as shift characters.
- codeName = 'Extended39'
- class reportlab.graphics.barcode.widgets.BarcodeExtended93(**kw)
This is a compressed form of Code 39, allowing the full ASCII charset
- codeName = 'Extended93'
- class reportlab.graphics.barcode.widgets.BarcodeFIM(**kw)
FIM was developed as part of the POSTNET barcoding system. FIM (Face Identification Marking) is used by the cancelling machines to sort mail according to whether or not they have bar code and their postage requirements. There are four types of FIM called FIM A, FIM B, FIM C, and FIM D.
- The four FIM types have the following meanings:
FIM A- Postage required pre-barcoded FIM B - Postage pre-paid, no bar code exists FIM C- Postage prepaid prebarcoded FIM D- Postage required, no bar code exists
- codeName = 'FIM'
- class reportlab.graphics.barcode.widgets.BarcodeI2of5(**kw)
Interleaved 2 of 5 is used in distribution and warehouse industries.
It encodes an even-numbered sequence of numeric digits. There is an optional module 10 check digit; if including this, the total length must be odd so that it becomes even after including the check digit. Otherwise the length must be even. Since the check digit is optional, our library does not check it.
- codeName = 'I2of5'
- class reportlab.graphics.barcode.widgets.BarcodeMSI(**kw)
MSI is used for inventory control in retail applications.
There are several methods for calculating check digits so we do not implement one.
- codeName = 'MSI'
- class reportlab.graphics.barcode.widgets.BarcodeStandard39(**kw)
Code39 is widely used in non-retail, especially US defence and health. Allowed characters are 0-9, A-Z (caps only), space, and -.$/+%*.
- codeName = 'Standard39'
reportlab.graphics.charts
Business charts
reportlab.graphics.charts.areas
This module defines a Area mixin classes
reportlab.graphics.charts.axes
Collection of axes for charts.
The current collection comprises axes for charts using cartesian coordinate systems. All axes might have tick marks and labels. There are two dichotomies for axes: one of X and Y flavours and another of category and value flavours.
Category axes have an ordering but no metric. They are divided into a number of equal-sized buckets. Their tick marks or labels, if available, go BETWEEN the buckets, and the labels are placed below to/left of the X/Y-axis, respectively.
Value axes have an ordering AND metric. They correspond to a nu- meric quantity. Value axis have a real number quantity associated with it. The chart tells it where to go. The most basic axis divides the number line into equal spaces and has tickmarks and labels associated with each; later we will add variants where you can specify the sampling interval.
The charts using axis tell them where the labels should be placed.
Axes of complementary X/Y flavours can be connected to each other in various ways, i.e. with a specific reference point, like an x/value axis to a y/value (or category) axis. In this case the connection can be either at the top or bottom of the former or at any absolute value (specified in points) or at some value of the former axes in its own coordinate system.
- class reportlab.graphics.charts.axes.AdjYValueAxis(**kw)
A Y-axis applying additional rules.
Depending on the data and some built-in rules, the axis may choose to adjust its range and origin.
- class reportlab.graphics.charts.axes.AxisBackgroundAnnotation(colors, **kwds)
Create a set of coloured bars on the background of a chart using axis ticks as the bar borders colors is a set of colors to use for the background bars. A colour of None is just a skip. Special effects if you pass a rect or Shaded rect instead.
- class reportlab.graphics.charts.axes.AxisLabelAnnotation(v, **kwds)
Create a grid like line using the given user value to draw the line v value to use kwds may contain scaleValue True/not given –> scale the value
otherwise use the absolute value
labelClass the label class to use default Label all Label keywords are acceptable (including say _text)
- class reportlab.graphics.charts.axes.AxisLineAnnotation(v, **kwds)
Create a grid like line using the given user value to draw the line kwds may contain startOffset if true v is offset from the default grid start position endOffset if true v is offset from the default grid end position scaleValue True/not given –> scale the value
otherwise use the absolute value
lo lowest coordinate to draw default 0 hi highest coordinate to draw at default = length drawAtLimit True draw line at appropriate limit if its coordinate exceeds the lo, hi range
False ignore if it’s outside the range
all Line keywords are acceptable
- class reportlab.graphics.charts.axes.CALabel(**kw)
- class reportlab.graphics.charts.axes.CategoryAxis
Abstract category axis, unusable in itself.
- configure(multiSeries, barWidth=None)
- midScale(idx)
Returns the bar mid position in drawing units
- scale(idx)
Returns the position and width in drawing units
- setPosition(x, y, length)
- class reportlab.graphics.charts.axes.LogAxisLabellingSetup
- class reportlab.graphics.charts.axes.LogAxisTickLabeller
- class reportlab.graphics.charts.axes.LogAxisTickLabellerS
simple log axis labeller tries to use integers and short forms else exponential format
- class reportlab.graphics.charts.axes.LogValueAxis(**kw)
- class reportlab.graphics.charts.axes.LogXValueAxis
- scale(value)
Converts a numeric value to a Y position.
The chart first configures the axis, then asks it to work out the x value for each point when plotting lines or bars. You could override this to do logarithmic axes.
- class reportlab.graphics.charts.axes.LogYValueAxis
- scale(value)
Converts a numeric value to a Y position.
The chart first configures the axis, then asks it to work out the x value for each point when plotting lines or bars. You could override this to do logarithmic axes.
- class reportlab.graphics.charts.axes.NormalDateXValueAxis(**kw)
An X axis applying additional rules.
Depending on the data and some built-in rules, the axis displays normalDate values as nicely formatted dates.
The client chart should have NormalDate X values.
- configure(data)
Let the axis configure its scale and range based on the data.
Called after setPosition. Let it look at a list of lists of numbers determine the tick mark intervals. If valueMin, valueMax and valueStep are configured then it will use them; if any of them are set to None it will look at the data and make some sensible decision. You may override this to build custom axes with irregular intervals. It creates an internal variable self._values, which is a list of numbers to use in plotting.
- class reportlab.graphics.charts.axes.TickLU(*T, **kwds)
lookup special cases for tick values
- class reportlab.graphics.charts.axes.TickLabeller
Abstract base class which may be used to indicate a change in the call signature for callable label formats
- class reportlab.graphics.charts.axes.ValueAxis(**kw)
Abstract value axis, unusable in itself.
- configure(dataSeries)
Let the axis configure its scale and range based on the data.
Called after setPosition. Let it look at a list of lists of numbers determine the tick mark intervals. If valueMin, valueMax and valueStep are configured then it will use them; if any of them are set to None it will look at the data and make some sensible decision. You may override this to build custom axes with irregular intervals. It creates an internal variable self._values, which is a list of numbers to use in plotting.
- makeTickLabels()
- scale(value)
Converts a numeric value to a plotarea position. The chart first configures the axis, then asks it to
- setPosition(x, y, length)
- class reportlab.graphics.charts.axes.XCategoryAxis
X/category axis
- demo()
- joinToAxis(yAxis, mode='bottom', pos=None)
Join with y-axis using some mode.
- loScale(idx)
returns the x position in drawing units
- makeAxis()
- makeTickLabels()
- class reportlab.graphics.charts.axes.XTimeValueAxis(*args, **kwds)
- class reportlab.graphics.charts.axes.XValueAxis(**kw)
X/value axis
- demo()
- joinToAxis(yAxis, mode='bottom', pos=None)
Join with y-axis using some mode.
- makeAxis()
- class reportlab.graphics.charts.axes.YCategoryAxis
Y/category axis
- demo()
- joinToAxis(xAxis, mode='left', pos=None)
Join with x-axis using some mode.
- loScale(idx)
Returns the y position in drawing units
- makeAxis()
- makeTickLabels()
- class reportlab.graphics.charts.axes.YValueAxis
Y/value axis
- demo()
- joinToAxis(xAxis, mode='left', pos=None)
Join with x-axis using some mode.
- makeAxis()
- reportlab.graphics.charts.axes.parseDayAndMonth(dmstr)
This accepts and validates strings like “31-Dec” i.e. dates of no particular year. 29 Feb is allowed. These can be used for recurring dates. It returns a (dd, mm) pair where mm is the month integer. If the text is not valid it raises an error.
reportlab.graphics.charts.barcharts
This module defines a variety of Bar Chart components.
The basic flavors are stacked and side-by-side, available in horizontal and vertical versions.
- class reportlab.graphics.charts.barcharts.BarChart
Abstract base class, unusable by itself.
- calcBarPositions()
Works out where they go. default vertical.
Sets an attribute _barPositions which is a list of lists of (x, y, width, height) matching the data.
- demo()
Shows basic use of a bar chart
- draw()
- getSeriesName(i, default=None)
return series name i or default
- getSeriesOrder()
- makeBars()
- makeSwatchSample(rowNo, x, y, width, height)
- class reportlab.graphics.charts.barcharts.BarChart3D
- calcBarPositions()
Works out where they go. default vertical.
Sets an attribute _barPositions which is a list of lists of (x, y, width, height) matching the data.
- makeBars()
- theta_x = 0.5
- theta_y = 0.5
- zDepth = None
- zSpace = None
- class reportlab.graphics.charts.barcharts.BarChartProperties
- class reportlab.graphics.charts.barcharts.HorizontalBarChart
Horizontal bar chart with multiple side-by-side bars.
- class reportlab.graphics.charts.barcharts.HorizontalBarChart3D
- class reportlab.graphics.charts.barcharts.SampleH5c4(width=400, height=200, *args, **kw)
Simple bar chart with absolute spacing.
- class reportlab.graphics.charts.barcharts.VerticalBarChart
Vertical bar chart with multiple side-by-side bars.
- class reportlab.graphics.charts.barcharts.VerticalBarChart3D
- reportlab.graphics.charts.barcharts.sampleH0a()
Make a slightly pathologic bar chart with only TWO data items.
- reportlab.graphics.charts.barcharts.sampleH0b()
Make a pathologic bar chart with only ONE data item.
- reportlab.graphics.charts.barcharts.sampleH0c()
Make a really pathologic bar chart with NO data items at all!
- reportlab.graphics.charts.barcharts.sampleH1()
Sample of multi-series bar chart.
- reportlab.graphics.charts.barcharts.sampleH2a()
Sample of multi-series bar chart.
- reportlab.graphics.charts.barcharts.sampleH2b()
Sample of multi-series bar chart.
- reportlab.graphics.charts.barcharts.sampleH2c()
Sample of multi-series bar chart.
- reportlab.graphics.charts.barcharts.sampleH3()
A really horizontal bar chart (compared to the equivalent faked one).
- reportlab.graphics.charts.barcharts.sampleH4a()
A bar chart showing value axis region starting at exactly zero.
- reportlab.graphics.charts.barcharts.sampleH4b()
A bar chart showing value axis region starting below zero.
- reportlab.graphics.charts.barcharts.sampleH4c()
A bar chart showing value axis region starting above zero.
- reportlab.graphics.charts.barcharts.sampleH4d()
A bar chart showing value axis region entirely below zero.
- reportlab.graphics.charts.barcharts.sampleH5a()
A simple bar chart with no expressed spacing attributes.
- reportlab.graphics.charts.barcharts.sampleH5b()
A simple bar chart with proportional spacing.
- reportlab.graphics.charts.barcharts.sampleH5c1()
A simple bar chart with absolute spacing.
- reportlab.graphics.charts.barcharts.sampleH5c2()
Simple bar chart with absolute spacing.
- reportlab.graphics.charts.barcharts.sampleH5c3()
Simple bar chart with absolute spacing.
- reportlab.graphics.charts.barcharts.sampleH5c4()
Simple bar chart with absolute spacing.
- reportlab.graphics.charts.barcharts.sampleStacked1()
Simple bar chart using symbol attribute.
- reportlab.graphics.charts.barcharts.sampleSymbol1()
Simple bar chart using symbol attribute.
- reportlab.graphics.charts.barcharts.sampleV0a()
A slightly pathologic bar chart with only TWO data items.
- reportlab.graphics.charts.barcharts.sampleV0b()
A pathologic bar chart with only ONE data item.
- reportlab.graphics.charts.barcharts.sampleV0c()
A really pathologic bar chart with NO data items at all!
- reportlab.graphics.charts.barcharts.sampleV1()
Sample of multi-series bar chart.
- reportlab.graphics.charts.barcharts.sampleV2a()
Sample of multi-series bar chart.
- reportlab.graphics.charts.barcharts.sampleV2b()
Sample of multi-series bar chart.
- reportlab.graphics.charts.barcharts.sampleV2c()
Sample of multi-series bar chart.
- reportlab.graphics.charts.barcharts.sampleV3()
Faked horizontal bar chart using a vertical real one (deprecated).
- reportlab.graphics.charts.barcharts.sampleV4a()
A bar chart showing value axis region starting at exactly zero.
- reportlab.graphics.charts.barcharts.sampleV4b()
A bar chart showing value axis region starting below zero.
- reportlab.graphics.charts.barcharts.sampleV4c()
A bar chart showing value axis region staring above zero.
- reportlab.graphics.charts.barcharts.sampleV4d()
A bar chart showing value axis region entirely below zero.
- reportlab.graphics.charts.barcharts.sampleV5a()
A simple bar chart with no expressed spacing attributes.
- reportlab.graphics.charts.barcharts.sampleV5b()
A simple bar chart with proportional spacing.
- reportlab.graphics.charts.barcharts.sampleV5c1()
Make sampe simple bar chart but with absolute spacing.
- reportlab.graphics.charts.barcharts.sampleV5c2()
Make sampe simple bar chart but with absolute spacing.
- reportlab.graphics.charts.barcharts.sampleV5c3()
Make sampe simple bar chart but with absolute spacing.
- reportlab.graphics.charts.barcharts.sampleV5c4()
Make sampe simple bar chart but with absolute spacing.
reportlab.graphics.charts.dotbox
reportlab.graphics.charts.doughnut
Doughnut chart
Produces a circular chart like the doughnut charts produced by Excel. Can handle multiple series (which produce concentric ‘rings’ in the chart).
- class reportlab.graphics.charts.doughnut.Doughnut
- demo()
- draw()
- makeSectors()
- normalizeData(data=None)
- class reportlab.graphics.charts.doughnut.SectorProperties
This holds descriptive information about the sectors in a doughnut chart.
It is not to be confused with the ‘sector itself’; this just holds a recipe for how to format one, and does not allow you to hack the angles. It can format a genuine Sector object for you with its format method.
- reportlab.graphics.charts.doughnut.sample1()
Make up something from the individual Sectors
- reportlab.graphics.charts.doughnut.sample2()
Make a simple demo
- reportlab.graphics.charts.doughnut.sample3()
Make a more complex demo
- reportlab.graphics.charts.doughnut.sample4()
Make a more complex demo with Label Overlap fixing
reportlab.graphics.charts.legends
This will be a collection of legends to be used with charts.
- class reportlab.graphics.charts.legends.Legend
A simple legend containing rectangular swatches and strings.
The swatches are filled rectangles whenever the respective color object in ‘colorNamePairs’ is a subclass of Color in reportlab.lib.colors. Otherwise the object passed instead is assumed to have ‘x’, ‘y’, ‘width’ and ‘height’ attributes. A legend then tries to set them or catches any error. This lets you plug-in any widget you like as a replacement for the default rectangular swatches.
Strings can be nicely aligned left or right to the swatches.
- demo()
Make sample legend.
- draw()
- class reportlab.graphics.charts.legends.LegendCallout
- class reportlab.graphics.charts.legends.LegendColEndCallout
- class reportlab.graphics.charts.legends.LegendSwatchCallout
- class reportlab.graphics.charts.legends.LineLegend
A subclass of Legend for drawing legends with lines as the swatches rather than rectangles. Useful for lineCharts and linePlots. Should be similar in all other ways the the standard Legend class.
- class reportlab.graphics.charts.legends.LineSwatch
basically a Line with properties added so it can be used in a LineLegend
- draw()
- class reportlab.graphics.charts.legends.TotalAnnotator(lText='Total', rText='0.0', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1), strokeWidth=0.5, strokeColor=Color(0, 0, 0, 1), strokeDashArray=None, dx=0, dy=0, dly=0, dlx=(0, 0))
reportlab.graphics.charts.linecharts
This modules defines a very preliminary Line Chart example.
- class reportlab.graphics.charts.linecharts.AbstractLineChart
- getSeriesName(i, default=None)
return series name i or default
- makeSwatchSample(rowNo, x, y, width, height)
- class reportlab.graphics.charts.linecharts.HorizontalLineChart
Line chart with multiple lines.
A line chart is assumed to have one category and one value axis. Despite its generic name this particular line chart class has a vertical value axis and a horizontal category one. It may evolve into individual horizontal and vertical variants (like with the existing bar charts).
Available attributes are:
x: x-position of lower-left chart origin y: y-position of lower-left chart origin width: chart width height: chart height
useAbsolute: disables auto-scaling of chart elements (?) lineLabelNudge: distance of data labels to data points lineLabels: labels associated with data values lineLabelFormat: format string or callback function groupSpacing: space between categories
joinedLines: enables drawing of lines
strokeColor: color of chart lines (?) fillColor: color for chart background (?) lines: style list, used cyclically for data series
valueAxis: value axis object categoryAxis: category axis object categoryNames: category names
data: chart data, a list of data series of equal length
- calcPositions()
Works out where they go.
Sets an attribute _positions which is a list of lists of (x, y) matching the data.
- demo()
Shows basic use of a line chart.
- draw()
Draws itself.
- drawLabel(G, rowNo, colNo, x, y)
Draw a label for a given item in the list. G must have an add method
- makeLines()
- class reportlab.graphics.charts.linecharts.HorizontalLineChart3D
- calcPositions()
Works out where they go.
Sets an attribute _positions which is a list of lists of (x, y) matching the data.
- makeLines()
- theta_x = 0.5
- theta_y = 0.5
- zDepth = 10
- zSpace = 3
- class reportlab.graphics.charts.linecharts.LineChart
- class reportlab.graphics.charts.linecharts.LineChartProperties
- class reportlab.graphics.charts.linecharts.SampleHorizontalLineChart
Sample class overwriting one method to draw additional horizontal lines.
- demo()
Shows basic use of a line chart.
- makeBackground()
- class reportlab.graphics.charts.linecharts.VerticalLineChart
- reportlab.graphics.charts.linecharts.sample1()
- reportlab.graphics.charts.linecharts.sample1a()
- reportlab.graphics.charts.linecharts.sample2()
- reportlab.graphics.charts.linecharts.sample3()
- reportlab.graphics.charts.linecharts.sampleCandleStick()
reportlab.graphics.charts.lineplots
This module defines a very preliminary Line Plot example.
- class reportlab.graphics.charts.lineplots.AreaLinePlot
we’re given data in the form [(X1,Y11,..Y1M)….(Xn,Yn1,…YnM)]
- draw()
- class reportlab.graphics.charts.lineplots.Filler(**kw)
mixin providing simple polygon fill
- fill(lp, g, rowNo, rowColor, points)
- class reportlab.graphics.charts.lineplots.GridLinePlot
A customized version of SimpleTimeSeriesSPlot. It uses NormalDateXValueAxis() and AdjYValueAxis() for the X and Y axes. The chart has a default grid background with thin horizontal lines aligned with the tickmarks (and labels). You can change the back- ground to be any Grid or ShadedRect, or scale the whole chart. If you do provide a background, you can specify the colours of the stripes with ‘background.stripeColors’.
- demo(drawing=None)
Shows basic use of a line chart.
- draw()
- class reportlab.graphics.charts.lineplots.InFillValue(v, yValue=None)
- class reportlab.graphics.charts.lineplots.LinePlot
Line plot with multiple lines.
Both x- and y-axis are value axis (so there are no seperate X and Y versions of this class).
- addCrossHair(name, xv, yv, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, beforeLines=True)
- calcPositions()
Works out where they go.
Sets an attribute _positions which is a list of lists of (x, y) matching the data.
- demo()
Shows basic use of a line chart.
- draw()
- drawLabel(G, rowNo, colNo, x, y)
Draw a label for a given item in the list. G must have an add method
- property joinedLines
- makeLines()
- class reportlab.graphics.charts.lineplots.LinePlot3D
- calcPositions()
Works out where they go.
Sets an attribute _positions which is a list of lists of (x, y) matching the data.
- makeLines()
- theta_x = 0.5
- theta_y = 0.5
- zDepth = 10
- zSpace = 3
- class reportlab.graphics.charts.lineplots.LinePlotProperties
- class reportlab.graphics.charts.lineplots.PolyFiller(**kw)
- class reportlab.graphics.charts.lineplots.ScatterPlot
A scatter plot widget
- demo(drawing=None)
Shows basic use of a line chart.
- draw()
- class reportlab.graphics.charts.lineplots.ShadedPolyFiller(**kw)
- class reportlab.graphics.charts.lineplots.SimpleTimeSeriesPlot
A customized version of LinePlot. It uses NormalDateXValueAxis() and AdjYValueAxis() for the X and Y axes.
- class reportlab.graphics.charts.lineplots.SplitLinePlot
- reportlab.graphics.charts.lineplots.preprocessData(series)
Convert date strings into seconds and multiply values by 100.
- reportlab.graphics.charts.lineplots.sample1a()
A line plot with non-equidistant points in x-axis.
- reportlab.graphics.charts.lineplots.sample1b()
A line plot with non-equidistant points in x-axis.
- reportlab.graphics.charts.lineplots.sample1c()
A line plot with non-equidistant points in x-axis.
- reportlab.graphics.charts.lineplots.sample2()
A line plot with non-equidistant points in x-axis.
- reportlab.graphics.charts.lineplots.sampleFillPairedData()
reportlab.graphics.charts.markers
This modules defines a collection of markers used in charts.
The make* functions return a simple shape or a widget as for the smiley.
- reportlab.graphics.charts.markers.makeEmptyCircle(x, y, size, color)
Make a hollow circle marker.
- reportlab.graphics.charts.markers.makeEmptySquare(x, y, size, color)
Make an empty square marker.
- reportlab.graphics.charts.markers.makeFilledCircle(x, y, size, color)
Make a hollow circle marker.
- reportlab.graphics.charts.markers.makeFilledDiamond(x, y, size, color)
Make a filled diamond marker.
- reportlab.graphics.charts.markers.makeFilledSquare(x, y, size, color)
Make a filled square marker.
- reportlab.graphics.charts.markers.makeSmiley(x, y, size, color)
Make a smiley marker.
reportlab.graphics.charts.piecharts
Basic Pie Chart class.
This permits you to customize and pop out individual wedges; supports elliptical and circular pies.
- class reportlab.graphics.charts.piecharts.AbstractPieChart
- getSeriesName(i, default=None)
return series name i or default
- makeSwatchSample(rowNo, x, y, width, height)
- class reportlab.graphics.charts.piecharts.AngleData(angle, data)
use this to carry the data along with the angle
- class reportlab.graphics.charts.piecharts.LegendedPie
Pie with a two part legend (one editable with swatches, one hidden without swatches).
- demo(drawing=None)
- draw()
- class reportlab.graphics.charts.piecharts.Pie(**kwd)
- demo()
- draw()
- makeAngles()
- makePointerLabels(angles, plMode)
- makeWedges()
- normalizeData(keepData=False)
- other_threshold = None
- class reportlab.graphics.charts.piecharts.Pie3d
- CX(i, d)
- CY(i, d)
- OX(i, o, d)
- OY(i, o, d)
- angle_3d = 180
- demo()
- depth_3d = 25
- draw()
- perspective = 70
- rad_dist(a)
- class reportlab.graphics.charts.piecharts.Wedge3dProperties
This holds descriptive information about the wedges in a pie chart.
It is not to be confused with the ‘wedge itself’; this just holds a recipe for how to format one, and does not allow you to hack the angles. It can format a genuine Wedge object for you with its format method.
- class reportlab.graphics.charts.piecharts.WedgeLabel(**kw)
- class reportlab.graphics.charts.piecharts.WedgeProperties
This holds descriptive information about the wedges in a pie chart.
It is not to be confused with the ‘wedge itself’; this just holds a recipe for how to format one, and does not allow you to hack the angles. It can format a genuine Wedge object for you with its format method.
- reportlab.graphics.charts.piecharts.boundsOverlap(P, Q)
- reportlab.graphics.charts.piecharts.findOverlapRun(B, wrap=1)
determine a set of overlaps in bounding boxes B or return None
- reportlab.graphics.charts.piecharts.fixLabelOverlaps(L, sideLabels=False, mult0=1.0)
- reportlab.graphics.charts.piecharts.intervalIntersection(A, B)
- reportlab.graphics.charts.piecharts.sample0a()
Make a degenerated pie chart with only one slice.
- reportlab.graphics.charts.piecharts.sample0b()
Make a degenerated pie chart with only one slice.
- reportlab.graphics.charts.piecharts.sample1()
Make a typical pie chart with with one slice treated in a special way.
- reportlab.graphics.charts.piecharts.sample2()
Make a pie chart with nine slices.
- reportlab.graphics.charts.piecharts.sample3()
Make a pie chart with a very slim slice.
- reportlab.graphics.charts.piecharts.sample4()
Make a pie chart with several very slim slices.
- reportlab.graphics.charts.piecharts.sample5()
Make a pie with side labels.
- reportlab.graphics.charts.piecharts.sample6()
Illustrates the pie moving to leave space for the left labels
- reportlab.graphics.charts.piecharts.sample7()
Case with overlapping pointers
- reportlab.graphics.charts.piecharts.sample8()
Case with overlapping labels
- reportlab.graphics.charts.piecharts.sample9()
Case with overlapping labels
- reportlab.graphics.charts.piecharts.theta0(data, direction)
reportlab.graphics.charts.slidebox
reportlab.graphics.charts.spider
Spider Chart
Normal use shows variation of 5-10 parameters against some ‘norm’ or target. When there is more than one series, place the series with the largest numbers first, as it will be overdrawn by each successive one.
- class reportlab.graphics.charts.spider.SpiderChart
- demo()
- draw()
- getSeriesName(i, default=None)
return series name i or default
- labelClass(kind)
- makeSwatchSample(rowNo, x, y, width, height)
- normalizeData(outer=0.0)
Turns data into normalized ones where each datum is < 1.0, and 1.0 = maximum radius. Adds 10% at outside edge by default
- class reportlab.graphics.charts.spider.SpokeLabel(**kw)
- class reportlab.graphics.charts.spider.SpokeProperty(**kw)
- class reportlab.graphics.charts.spider.StrandLabel(**kw)
- class reportlab.graphics.charts.spider.StrandProperty
- reportlab.graphics.charts.spider.sample1()
Make a simple spider chart
- reportlab.graphics.charts.spider.sample2()
Make a spider chart with markers, but no fill
reportlab.graphics.charts.textlabels
- class reportlab.graphics.charts.textlabels.BarChartLabel(**kwds)
An extended Label allowing for nudging, lines visibility etc
- class reportlab.graphics.charts.textlabels.Label(**kw)
A text label to attach to something else, such as a chart axis.
This allows you to specify an offset, angle and many anchor properties relative to the label’s origin. It allows, for example, angled multiline axis labels.
- computeSize()
- demo()
This shows a label positioned with its top right corner at the top centre of the drawing, and rotated 45 degrees.
- draw()
- setOrigin(x, y)
Set the origin. This would be the tick mark or bar top relative to which it is defined. Called by the containing chart or axis.
- setText(text)
Set the text property. May contain embedded newline characters. Called by the containing chart or axis.
- class reportlab.graphics.charts.textlabels.LabelOffset
- class reportlab.graphics.charts.textlabels.NA_Label
An extended Label allowing for nudging, lines visibility etc
- class reportlab.graphics.charts.textlabels.PMVLabel(**kwds)
- class reportlab.graphics.charts.textlabels.RedNegativeChanger(fillColor=Color(1, 0, 0, 1))
- class reportlab.graphics.charts.textlabels.XLabel(*args, **kwds)
like label but uses XPreFormatted/Paragraph to draw the _text
reportlab.graphics.charts.utils
Utilities used here and there.
- class reportlab.graphics.charts.utils.CustomDrawChanger
a class to simplify making changes at draw time
- class reportlab.graphics.charts.utils.DrawTimeCollector(formats=['gif'])
generic mechanism for collecting information about nodes at the time they are about to be drawn
- clear()
- property pmcanv
- record(func, node, *args, **kwds)
- static rectDrawTimeCallback(node, canvas, renderer, **kwds)
- save(fnroot)
save the current information known to this collector fnroot is the root name of a resource to name the saved info override this to get the right semantics for your collector
- static transformAndFlatten(A, p)
transform an flatten a list of points A transformation matrix p points [(x0,y0),….(xk,yk)…..]
- wedgeDrawTimeCallback(node, canvas, renderer, **kwds)
- class reportlab.graphics.charts.utils.FillPairedData(v, other=0)
- reportlab.graphics.charts.utils.findNones(data)
- reportlab.graphics.charts.utils.find_good_grid(lower, upper, n=(4, 5, 6, 7, 8, 9), grid=None)
- reportlab.graphics.charts.utils.find_interval(lo, hi, I=5)
determine tick parameters for range [lo, hi] using I intervals
- reportlab.graphics.charts.utils.lineSegmentIntersect(xxx_todo_changeme2, xxx_todo_changeme3, xxx_todo_changeme4, xxx_todo_changeme5)
- reportlab.graphics.charts.utils.makeCircularString(x, y, radius, angle, text, fontName, fontSize, inside=0, G=None, textAnchor='start')
make a group with circular text in it
- reportlab.graphics.charts.utils.maverage(data, n=6)
- reportlab.graphics.charts.utils.mkTimeTuple(timeString)
Convert a ‘dd/mm/yyyy’ formatted string to a tuple for use in the time module.
- reportlab.graphics.charts.utils.nextRoundNumber(x)
Return the first ‘nice round number’ greater than or equal to x
Used in selecting apropriate tick mark intervals; we say we want an interval which places ticks at least 10 points apart, work out what that is in chart space, and ask for the nextRoundNumber(). Tries the series 1,2,5,10,20,50,100.., going up or down as needed.
- reportlab.graphics.charts.utils.pairFixNones(pairs)
- reportlab.graphics.charts.utils.pairMaverage(data, n=6)
- reportlab.graphics.charts.utils.seconds2str(seconds)
Convert a date string into the number of seconds since the epoch.
- reportlab.graphics.charts.utils.str2seconds(timeString)
Convert a number of seconds since the epoch into a date string.
- reportlab.graphics.charts.utils.ticks(lower, upper, n=(4, 5, 6, 7, 8, 9), split=1, percent=0, grid=None, labelVOffset=0)
return tick positions and labels for range lower<=x<=upper n=number of intervals to try (can be a list or sequence) split=1 return ticks then labels else (tick,label) pairs
- reportlab.graphics.charts.utils.xyDist(xxx_todo_changeme, xxx_todo_changeme1)
return distance between two points
reportlab.graphics.charts.utils3d
- reportlab.graphics.charts.utils3d.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.
- reportlab.graphics.charts.utils3d.mod_2pi(radians)
reportlab.graphics.samples
Example drawings to review, used in autogenerated docs
reportlab.graphics.samples.bubble
- class reportlab.graphics.samples.bubble.Bubble(width=200, height=150, *args, **kw)
reportlab.graphics.samples.clustered_bar
- class reportlab.graphics.samples.clustered_bar.ClusteredBar(width=200, height=150, *args, **kw)
reportlab.graphics.samples.clustered_column
- class reportlab.graphics.samples.clustered_column.ClusteredColumn(width=200, height=150, *args, **kw)
reportlab.graphics.samples.excelcolors
reportlab.graphics.samples.exploded_pie
- class reportlab.graphics.samples.exploded_pie.ExplodedPie(width=200, height=150, *args, **kw)
reportlab.graphics.samples.filled_radar
- class reportlab.graphics.samples.filled_radar.FilledRadarChart(width=200, height=150, *args, **kw)
reportlab.graphics.samples.line_chart
- class reportlab.graphics.samples.line_chart.LineChart(width=200, height=150, *args, **kw)
reportlab.graphics.samples.linechart_with_markers
- class reportlab.graphics.samples.linechart_with_markers.LineChartWithMarkers(width=200, height=150, *args, **kw)
reportlab.graphics.samples.radar
- class reportlab.graphics.samples.radar.RadarChart(width=200, height=150, *args, **kw)
reportlab.graphics.samples.runall
- reportlab.graphics.samples.runall.getclass(f)
- reportlab.graphics.samples.runall.moduleClasses(mod)
- reportlab.graphics.samples.runall.run(format, VERBOSE=0)
reportlab.graphics.samples.scatter
- class reportlab.graphics.samples.scatter.Scatter(width=200, height=150, *args, **kw)
reportlab.graphics.samples.scatter_lines
- class reportlab.graphics.samples.scatter_lines.ScatterLines(width=200, height=150, *args, **kw)
reportlab.graphics.samples.scatter_lines_markers
- class reportlab.graphics.samples.scatter_lines_markers.ScatterLinesMarkers(width=200, height=150, *args, **kw)
reportlab.graphics.samples.simple_pie
- class reportlab.graphics.samples.simple_pie.SimplePie(width=200, height=150, *args, **kw)
reportlab.graphics.samples.stacked_bar
- class reportlab.graphics.samples.stacked_bar.StackedBar(width=200, height=150, *args, **kw)
reportlab.graphics.samples.stacked_column
- class reportlab.graphics.samples.stacked_column.StackedColumn(width=200, height=150, *args, **kw)
reportlab.graphics.widgets
Some non-chart widgets
reportlab.graphics.widgets.adjustableArrow
- class reportlab.graphics.widgets.adjustableArrow.AdjustableArrow(**kwds)
This widget draws an arrow (style one).
possible attributes: ‘x’, ‘y’, ‘size’, ‘fillColor’
- draw()
- class reportlab.graphics.widgets.adjustableArrow.AdjustableArrowDrawing(width=100, height=63, *args, **kw)
reportlab.graphics.widgets.eventcal
This file is a
- class reportlab.graphics.widgets.eventcal.EventCalendar
- computeSize()
Called at start of draw. Sets various column widths
- computeStartAndEndTimes()
Work out first and last times to display
- draw()
- getAllTracks()
- getRelevantTalks(talkList)
Scans for tracks actually used
- getTalkRect(startTime, duration, trackId, text)
Return shapes for a specific talk
- scaleTime(theTime)
Return y-value corresponding to times given
- reportlab.graphics.widgets.eventcal.test()
Make a conference event for day 1 of UP Python 2003
reportlab.graphics.widgets.flags
This file is a collection of flag graphics as widgets.
All flags are represented at the ratio of 1:2, even where the official ratio for the flag is something else (such as 3:5 for the German national flag). The only exceptions are for where this would look _very_ wrong, such as the Danish flag whose (ratio is 28:37), or the Swiss flag (which is square).
Unless otherwise stated, these flags are all the ‘national flags’ of the countries, rather than their state flags, naval flags, ensigns or any other variants. (National flags are the flag flown by civilians of a country and the ones usually used to represent a country abroad. State flags are the variants used by the government and by diplomatic missions overseas).
To check on how close these are to the ‘official’ representations of flags, check the World Flag Database at http://www.flags.ndirect.co.uk/
The flags this file contains are:
EU Members: United Kingdom, Austria, Belgium, Denmark, Finland, France, Germany, Greece, Ireland, Italy, Luxembourg, Holland (The Netherlands), Spain, Sweden
Others: USA, Czech Republic, European Union, Switzerland, Turkey, Brazil
(Brazilian flag contributed by Publio da Costa Melo [publio@planetarium.com.br]).
- class reportlab.graphics.widgets.flags.Flag(**kw)
This is a generic flag class that all the flags in this file use as a basis.
This class basically provides edges and a tidy-up routine to hide any bits of line that overlap the ‘outside’ of the flag
possible attributes: ‘x’, ‘y’, ‘size’, ‘fillColor’
- availableFlagNames()
return a list of the things we can display
- clone()
- demo()
- draw()
- class reportlab.graphics.widgets.flags.Star
This draws a 5-pointed star.
possible attributes: ‘x’, ‘y’, ‘size’, ‘fillColor’, ‘strokeColor’
- demo()
- draw()
- reportlab.graphics.widgets.flags.makeFlag(name)
- reportlab.graphics.widgets.flags.test()
This function produces three pdf files with examples of all the signs and symbols from this file.
reportlab.graphics.widgets.grids
- class reportlab.graphics.widgets.grids.DoubleGrid
This combines two ordinary Grid objects orthogonal to each other.
- demo()
- draw()
- class reportlab.graphics.widgets.grids.Grid
This makes a rectangular grid of equidistant stripes.
The grid contains an outer border rectangle, and stripes inside which can be drawn with lines and/or as solid tiles. The drawing order is: outer rectangle, then lines and tiles.
The stripes’ width is indicated as ‘delta’. The sequence of stripes can have an offset named ‘delta0’. Both values need to be positive!
- demo()
- draw()
- makeInnerLines()
- makeInnerTiles()
- makeLinePosList(start, isX=0)
Returns a list of positions where to place lines.
- makeOuterRect()
- class reportlab.graphics.widgets.grids.ShadedRect(**kw)
This makes a rectangle with shaded colors between two colors.
Colors are interpolated linearly between ‘fillColorStart’ and ‘fillColorEnd’, both of which appear at the margins. If ‘numShades’ is set to one, though, only ‘fillColorStart’ is used.
- demo()
- draw()
- reportlab.graphics.widgets.grids.centroid(P)
compute average point of a set of points
- reportlab.graphics.widgets.grids.colorRange(c0, c1, n)
Return a range of intermediate colors between c0 and c1
- reportlab.graphics.widgets.grids.frange(start, end=None, inc=None)
A range function, that does accept float increments…
- reportlab.graphics.widgets.grids.makeDistancesList(list)
Returns a list of distances between adjacent numbers in some input list.
E.g. [1, 1, 2, 3, 5, 7] -> [0, 1, 1, 2, 2]
- reportlab.graphics.widgets.grids.rotatedEnclosingRect(P, angle, rect)
given P a sequence P of x,y coordinate pairs and an angle in degrees find the centroid of P and the axis at angle theta through it find the extreme points of P wrt axis parallel distance and axis orthogonal distance. Then compute the least rectangle that will still enclose P when rotated by angle.
The class R
reportlab.graphics.widgets.markers
This modules defines a collection of markers used in charts.
- class reportlab.graphics.widgets.markers.Marker(*args, **kw)
A polymorphic class of markers
- clone(**kwds)
- draw()
- reportlab.graphics.widgets.markers.makeMarker(name, **kw)
- reportlab.graphics.widgets.markers.uSymbol2Symbol(uSymbol, x, y, color)
reportlab.graphics.widgets.signsandsymbols
This file is a collection of widgets to produce some common signs and symbols.
Widgets include:
ETriangle (an equilateral triangle),
RTriangle (a right angled triangle),
Octagon,
Crossbox,
Tickbox,
SmileyFace,
StopSign,
NoEntry,
NotAllowed (the red roundel from ‘no smoking’ signs),
NoSmoking,
DangerSign (a black exclamation point in a yellow triangle),
YesNo (returns a tickbox or a crossbox depending on a testvalue),
FloppyDisk,
ArrowOne, and
ArrowTwo
CrossHair
- class reportlab.graphics.widgets.signsandsymbols.ArrowOne
This widget draws an arrow (style one).
possible attributes: ‘x’, ‘y’, ‘size’, ‘fillColor’
- draw()
- class reportlab.graphics.widgets.signsandsymbols.ArrowTwo
This widget draws an arrow (style two).
possible attributes: ‘x’, ‘y’, ‘size’, ‘fillColor’
- draw()
- class reportlab.graphics.widgets.signsandsymbols.CrossHair
This draws an equilateral triangle.
- draw()
- class reportlab.graphics.widgets.signsandsymbols.Crossbox
This draws a black box with a red cross in it - a ‘checkbox’.
possible attributes: ‘x’, ‘y’, ‘size’, ‘crossColor’, ‘strokeColor’, ‘crosswidth’
- draw()
- class reportlab.graphics.widgets.signsandsymbols.DangerSign
This draws a ‘danger’ sign: a yellow box with a black exclamation point.
possible attributes: ‘x’, ‘y’, ‘size’, ‘strokeColor’, ‘fillColor’, ‘strokeWidth’
- draw()
- class reportlab.graphics.widgets.signsandsymbols.ETriangle
This draws an equilateral triangle.
- draw()
- class reportlab.graphics.widgets.signsandsymbols.FloppyDisk
This widget draws an icon of a floppy disk.
possible attributes: ‘x’, ‘y’, ‘size’, ‘diskcolor’
- draw()
- class reportlab.graphics.widgets.signsandsymbols.NoEntry
This draws a (British) No Entry sign - a red circle with a white line on it.
possible attributes: ‘x’, ‘y’, ‘size’
- draw()
- class reportlab.graphics.widgets.signsandsymbols.NoSmoking
This draws a no-smoking sign.
possible attributes: ‘x’, ‘y’, ‘size’
- draw()
- class reportlab.graphics.widgets.signsandsymbols.NotAllowed
This draws a ‘forbidden’ roundel (as used in the no-smoking sign).
possible attributes: ‘x’, ‘y’, ‘size’
- draw()
- class reportlab.graphics.widgets.signsandsymbols.Octagon
This widget draws an Octagon.
possible attributes: ‘x’, ‘y’, ‘size’, ‘fillColor’, ‘strokeColor’
- draw()
- class reportlab.graphics.widgets.signsandsymbols.RTriangle
This draws a right-angled triangle.
possible attributes: ‘x’, ‘y’, ‘size’, ‘fillColor’, ‘strokeColor’
- draw()
- class reportlab.graphics.widgets.signsandsymbols.SmileyFace
This draws a classic smiley face.
possible attributes: ‘x’, ‘y’, ‘size’, ‘fillColor’
- draw()
- class reportlab.graphics.widgets.signsandsymbols.StopSign
This draws a (British) stop sign.
possible attributes: ‘x’, ‘y’, ‘size’
- draw()
- class reportlab.graphics.widgets.signsandsymbols.Tickbox
This draws a black box with a red tick in it - another ‘checkbox’.
possible attributes: ‘x’, ‘y’, ‘size’, ‘tickColor’, ‘strokeColor’, ‘tickwidth’
- draw()
- class reportlab.graphics.widgets.signsandsymbols.YesNo
This widget draw a tickbox or crossbox depending on ‘testValue’.
If this widget is supplied with a ‘True’ or 1 as a value for testValue, it will use the tickbox widget. Otherwise, it will produce a crossbox.
possible attributes: ‘x’, ‘y’, ‘size’, ‘tickcolor’, ‘crosscolor’, ‘testValue’
- demo()
- draw()
- reportlab.graphics.widgets.signsandsymbols.test()
This function produces a pdf with examples of all the signs and symbols from this file.
reportlab.graphics.widgets.table
- class reportlab.graphics.widgets.table.TableWidget(x=10, y=10, **kw)
A two dimensions table of labels
- demo()
returns a sample of this widget with data
- draw()
returns a group of shapes
- preProcessData(data)
preprocess and return a new array with at least one row and column (use a None) if needed, and all rows the same length (adding Nones if needed)
reportlab.lib
reportlab.lib.PyFontify
Module to analyze Python source code; for syntax coloring tools.
Interface:
tags = fontify(pytext, searchfrom, searchto)
- The 'pytext' argument is a string containing Python source code.
- The (optional) arguments 'searchfrom' and 'searchto' may contain a slice in pytext.
- The returned value is a list of tuples, formatted like this::
[('keyword', 0, 6, None), ('keyword', 11, 17, None), ('comment', 23, 53, None), etc. ]
- The tuple contents are always like this::
(tag, startindex, endindex, sublist)
- tag is one of 'keyword', 'string', 'comment' or 'identifier'
- sublist is not used, hence always None.
- reportlab.lib.PyFontify.fontify(pytext, searchfrom=0, searchto=None)
- reportlab.lib.PyFontify.replace(src, sep, rep)
- reportlab.lib.PyFontify.test(path)
reportlab.lib.abag
Data structure to hold a collection of attributes, used by styles.
- class reportlab.lib.abag.ABag(**attr)
‘Attribute Bag’ - a trivial BAG class for holding attributes.
This predates modern Python. Doing this again, we’d use a subclass of dict.
You may initialize with keyword arguments. a = ABag(k0=v0,….,kx=vx,….) ==> getattr(a,’kx’)==vx
c = a.clone(ak0=av0,…..) copy with optional additional attributes.
- clone(**attr)
reportlab.lib.arciv
Arciv Stream ciphering
- class reportlab.lib.arciv.ArcIV(key)
performs ‘ArcIV’ Stream Encryption of S using key Based on what is widely thought to be RSA’s ArcIV algorithm. It produces output streams that are identical.
NB there is no separate decoder arciv(arciv(s,key),key) == s
- encode(S)
ArcIV encode string S
- reset()
restore the cipher to it’s start state
- reportlab.lib.arciv.decode(text, key)
One-line shortcut for decoding
- reportlab.lib.arciv.encode(text, key)
One-line shortcut for making an encoder object
reportlab.lib.attrmap
Framework for objects whose assignments are checked. Used by graphics.
We developed reportlab/graphics prior to Python 2 and metaclasses. For the graphics, we wanted to be able to declare the attributes of a class, check them on assignment, and convert from string arguments. Examples of attrmap-based objects can be found in reportlab/graphics/shapes. It lets us defined structures like the one below, which are seen more modern form in Django models and other frameworks.
We’ll probably replace this one day soon, hopefully with no impact on client code.
- class Rect(SolidShape):
“””Rectangle, possibly with rounded corners.”””
- _attrMap = AttrMap(BASE=SolidShape,
x = AttrMapValue(isNumber), y = AttrMapValue(isNumber), width = AttrMapValue(isNumber), height = AttrMapValue(isNumber), rx = AttrMapValue(isNumber), ry = AttrMapValue(isNumber), )
- class reportlab.lib.attrmap.AttrMap(BASE=None, UNWANTED=[], **kw)
- clone(UNWANTED=[], **kw)
- remove(unwanted)
- class reportlab.lib.attrmap.AttrMapValue(validate=None, desc=None, initial=None, advancedUsage=0, **kw)
Simple multi-value holder for attribute maps
- class reportlab.lib.attrmap.CallableValue(func, *args, **kw)
a class to allow callable initial values
- reportlab.lib.attrmap.addProxyAttribute(src, name, validate=None, desc=None, initial=None, dst=None)
Add a proxy attribute ‘name’ to src with targets dst
- reportlab.lib.attrmap.hook__setattr__(obj)
- reportlab.lib.attrmap.validateSetattr(obj, name, value)
validate setattr(obj,name,value)
reportlab.lib.boxstuff
Utility functions to position and resize boxes within boxes
- reportlab.lib.boxstuff.aspectRatioFix(preserve, anchor, x, y, width, height, imWidth, imHeight, anchorAtXY=False)
This function helps position an image within a box.
It first normalizes for two cases: - if the width is None, it assumes imWidth - ditto for height - if width or height is negative, it adjusts x or y and makes them positive
Given (a) the enclosing box (defined by x,y,width,height where x,y is the lower left corner) which you wish to position the image in, and (b) the image size (imWidth, imHeight), and (c) the ‘anchor point’ as a point of the compass - n,s,e,w,ne,se etc and c for centre,
this should return the position at which the image should be drawn, as well as a scale factor indicating what scaling has happened.
It returns the parameters which would be used to draw the image without any adjustments:
x,y, width, height, scale
used in canvas.drawImage and drawInlineImage
- reportlab.lib.boxstuff.rectCorner(x, y, width, height, anchor='sw', dims=False)
given rectangle controlled by x,y width and height return the corner corresponding to the anchor
reportlab.lib.codecharts
Routines to print code page (character set) drawings. Predates unicode.
To be sure we can accurately represent characters in various encodings and fonts, we need some routines to display all those characters. These are defined herein. The idea is to include flowable, drawable and graphic objects for single and multi-byte fonts.
- class reportlab.lib.codecharts.Big5CodeChart(row, faceName, encodingName)
Formats one ‘row’ of the 94x160 space used in Big 5
These deliberately resemble the code charts in Ken Lunde’s “Understanding CJKV Information Processing”, to enable manual checking.
- draw()
- makeRow(row)
Works out the character values for this Big5 row. Rows start at 0xA1
- class reportlab.lib.codecharts.CodeChartBase
Basic bits of drawing furniture used by single and multi-byte versions: ability to put letters into boxes.
- calcLayout()
Work out x and y positions for drawing
- drawChars(charList)
Fills boxes in order. None means skip a box. Empty boxes at end get filled with gray
- drawLabels(topLeft='')
Writes little labels in the top row and first column
- formatByte(byt)
- class reportlab.lib.codecharts.KutenRowCodeChart(row, faceName, encodingName)
Formats one ‘row’ of the 94x94 space used in many Asian encodings.aliases
These deliberately resemble the code charts in Ken Lunde’s “Understanding CJKV Information Processing”, to enable manual checking. Due to the large numbers of characters, we don’t try to make one graphic with 10,000 characters, but rather output a sequence of these.
- draw()
- makeRow(row)
Works out the character values for this kuten row
- class reportlab.lib.codecharts.SingleByteEncodingChart(faceName='Helvetica', encodingName='WinAnsiEncoding', charsPerRow=16, boxSize=14, hex=1)
- draw()
- reportlab.lib.codecharts.hBoxText(msg, canvas, x, y, fontName)
Helper for stringwidth tests on Asian fonts.
Registers font if needed. Then draws the string, and a box around it derived from the stringWidth function
- reportlab.lib.codecharts.test()
reportlab.lib.colors
Defines standard colour-handling classes and colour names.
We define standard classes to hold colours in two models: RGB and CMYK. rhese can be constructed from several popular formats. We also include
pre-built colour objects for the HTML standard colours
pre-built colours used in ReportLab’s branding
various conversion and construction functions
These tests are here because doctest cannot find them otherwise. >>> toColor(‘rgb(128,0,0)’)==toColor(‘rgb(50%,0%,0%)’) True >>> toColor(‘rgb(50%,0%,0%)’)!=Color(0.5,0,0,1) True >>> toColor(‘hsl(0,100%,50%)’)==toColor(‘rgb(255,0,0)’) True >>> toColor(‘hsl(-120,100%,50%)’)==toColor(‘rgb(0,0,255)’) True >>> toColor(‘hsl(120,100%,50%)’)==toColor(‘rgb(0,255,0)’) True >>> toColor(‘rgba( 255,0,0,0.5)’)==Color(1,0,0,0.5) True >>> toColor(‘cmyk(1,0,0,0 )’)==CMYKColor(1,0,0,0) True >>> toColor(‘pcmyk( 100 , 0 , 0 , 0 )’)==PCMYKColor(100,0,0,0) True >>> toColor(‘cmyka(1,0,0,0,0.5)’)==CMYKColor(1,0,0,0,alpha=0.5) True >>> toColor(‘pcmyka(100,0,0,0,0.5)’)==PCMYKColor(100,0,0,0,alpha=0.5) True >>> toColor(‘pcmyka(100,0,0,0)’) Traceback (most recent call last):
ValueError: css color ‘pcmyka(100,0,0,0)’ has wrong number of components
- reportlab.lib.colors.Blacker(c, f)
given a color combine with black as c*f+b*(1-f) 0<=f<=1
- class reportlab.lib.colors.CMYKColor(cyan=0, magenta=0, yellow=0, black=0, spotName=None, density=1, knockout=None, alpha=1)
This represents colors using the CMYK (cyan, magenta, yellow, black) model commonly used in professional printing. This is implemented as a derived class so that renderers which only know about RGB “see it” as an RGB color through its ‘red’,’green’ and ‘blue’ attributes, according to an approximate function.
The RGB approximation is worked out when the object in constructed, so the color attributes should not be changed afterwards.
Extra attributes may be attached to the class to support specific ink models, and renderers may look for these.
- cmyk()
Returns a tuple of four color components - syntactic sugar
- cmyka()
Returns a tuple of five color components - syntactic sugar
- fader(n, reverse=False)
return n colors based on density fade NB note this dosen’t reach density zero
- property normalizedAlpha
- class reportlab.lib.colors.CMYKColorSep(cyan=0, magenta=0, yellow=0, black=0, spotName=None, density=1, alpha=1)
special case color for making separating pdfs
- class reportlab.lib.colors.Color(red=0, green=0, blue=0, alpha=1)
This class is used to represent color. Components red, green, blue are in the range 0 (dark) to 1 (full intensity).
- bitmap_rgb()
- bitmap_rgba()
- property cKwds
- clone(**kwds)
copy then change values in kwds
- hexval()
- hexvala()
- int_argb()
- int_rgb()
- int_rgba()
- property normalizedAlpha
- rgb()
Returns a three-tuple of components
- rgba()
Returns a four-tuple of components
- reportlab.lib.colors.HexColor(val, htmlOnly=False, hasAlpha=False)
This function converts a hex string, or an actual integer number, into the corresponding color. E.g., in “#AABBCC” or 0xAABBCC, AA is the red, BB is the green, and CC is the blue (00-FF).
An alpha value can also be given in the form #AABBCCDD or 0xAABBCCDD where DD is the alpha value if hasAlpha is True.
For completeness I assume that #aabbcc or 0xaabbcc are hex numbers otherwise a pure integer is converted as decimal rgb. If htmlOnly is true, only the #aabbcc form is allowed.
>>> HexColor('#ffffff') Color(1,1,1,1) >>> HexColor('#FFFFFF') Color(1,1,1,1) >>> HexColor('0xffffff') Color(1,1,1,1) >>> HexColor('16777215') Color(1,1,1,1)
An ‘0x’ or ‘#’ prefix is required for hex (as opposed to decimal):
>>> HexColor('ffffff') Traceback (most recent call last): ValueError: invalid literal for int() with base 10: 'ffffff'
>>> HexColor('#FFFFFF', htmlOnly=True) Color(1,1,1,1) >>> HexColor('0xffffff', htmlOnly=True) Traceback (most recent call last): ValueError: not a hex string >>> HexColor('16777215', htmlOnly=True) Traceback (most recent call last): ValueError: not a hex string
- class reportlab.lib.colors.PCMYKColor(cyan, magenta, yellow, black, density=100, spotName=None, knockout=None, alpha=100)
100 based CMYKColor with density and a spotName; just like Rimas uses
- property cKwds
- class reportlab.lib.colors.PCMYKColorSep(cyan=0, magenta=0, yellow=0, black=0, spotName=None, density=100, alpha=100)
special case color for making separating pdfs
- reportlab.lib.colors.Whiter(c, f)
given a color combine with white as c*f w*(1-f) 0<=f<=1
- reportlab.lib.colors.cmyk2rgb(cmyk, density=1)
Convert from a CMYK color tuple to an RGB color tuple
- reportlab.lib.colors.cmykDistance(col1, col2)
Returns a number between 0 and root(4) stating how similar two colours are - distance in r,g,b, space. Only used to find names for things.
- reportlab.lib.colors.color2bw(colorRGB)
Transform an RGB color to a black and white equivalent.
- reportlab.lib.colors.colorDistance(col1, col2)
Returns a number between 0 and root(3) stating how similar two colours are - distance in r,g,b, space. Only used to find names for things.
- reportlab.lib.colors.describe(aColor, mode=0)
finds nearest colour match to aColor. mode=0 print a string desription mode=1 return a string description mode=2 return (distance, colorName)
- reportlab.lib.colors.fade(aSpotColor, percentages)
Waters down spot colors and returns a list of new ones
e.g fade(myColor, [100,80,60,40,20]) returns a list of five colors
- reportlab.lib.colors.getAllNamedColors()
- reportlab.lib.colors.hsl2rgb(h, s, l)
- reportlab.lib.colors.hue2rgb(m1, m2, h)
- reportlab.lib.colors.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’.
- reportlab.lib.colors.obj_R_G_B(c)
attempt to convert an object to (red,green,blue)
- reportlab.lib.colors.opaqueColor(c)
utility to check we have a color that’s not fully transparent
- reportlab.lib.colors.rgb2cmyk(r, g, b)
one way to get cmyk from rgb
- reportlab.lib.colors.setColors(**kw)
- reportlab.lib.colors.toColorOrNone(arg, default=None)
as above but allows None as a legal value
reportlab.lib.corp
Generate ReportLab logo in a variety of sizes and formats.
- This module includes some reusable routines for ReportLab’s
‘Corporate Image’ - the logo, standard page backdrops and so on - you are advised to do the same for your own company!
- class reportlab.lib.corp.RL_BusinessCard
Widget that creates a single business card. Uses RL_CorpLogo for the logo.
For a black border around your card, set self.border to 1. To change the details on the card, over-ride the following properties: self.name, self.position, self.telephone, self.mobile, self.fax, self.email, self.web The office locations are set in self.rh_blurb_top (“London office” etc), and self.rh_blurb_bottom (“New York office” etc).
- demo()
- draw()
- class reportlab.lib.corp.RL_CorpLogo
Dinu’s fat letter logo as hacked into decent paths by Robin
- static applyPrec(P, prec)
- demo()
- draw()
- class reportlab.lib.corp.RL_CorpLogoReversed
- class reportlab.lib.corp.RL_CorpLogoThin
The ReportLab Logo.
New version created by John Precedo on 7-8 August 2001. Based on bitmapped imaged from E-Id. Improved by Robin Becker.
- demo()
- draw()
- class reportlab.lib.corp.ReportLabLogo(atx=0, aty=0, width=180.0, height=108.0, powered_by=0)
vector reportlab logo centered in a 250x by 150y rectangle
- draw(canvas)
- reportlab.lib.corp.test(formats=['pdf', 'eps', 'jpg', 'gif', 'svg'])
This function produces a pdf with examples.
reportlab.lib.enums
Container for constants. Hardly used!
reportlab.lib.extformat
Apparently not used anywhere, purpose unknown!
- reportlab.lib.extformat.dictformat(_format, L={}, G={})
- reportlab.lib.extformat.magicformat(format)
Evaluate and substitute the appropriate parts of the string.
reportlab.lib.fontfinder
This provides some general-purpose tools for finding fonts.
The FontFinder object can search for font files. It aims to build a catalogue of fonts which our framework can work with. It may be useful if you are building GUIs or design-time interfaces and want to present users with a choice of fonts.
There are 3 steps to using it 1. create FontFinder and set options and directories 2. search 3. query
>>> import fontfinder
>>> ff = fontfinder.FontFinder()
>>> ff.addDirectories([dir1, dir2, dir3])
>>> ff.search()
>>> ff.getFamilyNames() #or whichever queries you want...
Because the disk search takes some time to find and parse hundreds of fonts, it can use a cache to store a file with all fonts found. The cache file name
For each font found, it creates a structure with - the short font name - the long font name - the principal file (.pfb for type 1 fonts), and the metrics file if appropriate - the time modified (unix time stamp) - a type code (‘ttf’) - the family name - bold and italic attributes
One common use is to display families in a dialog for end users; then select regular, bold and italic variants of the font. To get the initial list, use getFamilyNames; these will be in alpha order.
>>> ff.getFamilyNames()
['Bitstream Vera Sans', 'Century Schoolbook L', 'Dingbats', 'LettErrorRobot',
'MS Gothic', 'MS Mincho', 'Nimbus Mono L', 'Nimbus Roman No9 L',
'Nimbus Sans L', 'Vera', 'Standard Symbols L',
'URW Bookman L', 'URW Chancery L', 'URW Gothic L', 'URW Palladio L']
One can then obtain a specific font as follows
>>> f = ff.getFont('Bitstream Vera Sans', bold=False, italic=True)
>>> f.fullName
'Bitstream Vera Sans'
>>> f.fileName
'C:\code\reportlab\fonts\Vera.ttf'
>>>
It can also produce an XML report of fonts found by family, for the benefit of non-Python applications.
Future plans might include using this to auto-register fonts; and making it update itself smartly on repeated instantiation.
- class reportlab.lib.fontfinder.FontDescriptor
This is a short descriptive record about a font.
typeCode should be a file extension e.g. [‘ttf’,’ttc’,’otf’,’pfb’,’pfa’]
- getTag()
Return an XML tag representation
- class reportlab.lib.fontfinder.FontFinder(dirs=[], useCache=True, validate=False, recur=False, fsEncoding=None, verbose=0)
- addDirectories(dirNames, recur=None)
- addDirectory(dirName, recur=None)
- getFamilyNames()
Returns a list of the distinct font families found
- getFamilyXmlReport()
Reports on all families found as XML.
- getFont(familyName, bold=False, italic=False)
Try to find a font matching the spec
- getFontsInFamily(familyName)
Return list of all font objects with this family name
- getFontsWithAttributes(**kwds)
This is a general lightweight search.
- load(fileName)
- save(fileName)
- search()
- reportlab.lib.fontfinder.asNative(s)
- reportlab.lib.fontfinder.test()
reportlab.lib.fonts
Utilities to associate bold and italic versions of fonts into families
Bold, italic and plain fonts are usually implemented in separate disk files; but non-trivial apps want <b>this</b> to do the right thing. We therefore need to keep ‘mappings’ between the font family name and the right group of up to 4 implementation fonts to use.
Most font-handling code lives in pdfbase, and this probably should too.
- reportlab.lib.fonts.addMapping(face, bold, italic, psname)
allow a custom font to be put in the mapping
- reportlab.lib.fonts.ps2tt(psfn)
ps fontname to family name, bold, italic
- reportlab.lib.fonts.tt2ps(fn, b, i)
family name + bold & italic to ps font name
reportlab.lib.formatters
These help format numbers and dates in a user friendly way. Used by the graphics framework.
reportlab.lib.geomutils
Utility functions for geometrical operations.
- reportlab.lib.geomutils.normalizeTRBL(p)
Useful for interpreting short descriptions of paddings, borders, margin, etc. Expects a single value or a tuple of length 2 to 4. Returns a tuple representing (clockwise) the value(s) applied to the 4 sides of a rectangle: If a single value is given, that value is applied to all four sides. If two or three values are given, the missing values are taken from the opposite side(s). If four values are given they are returned unchanged.
>>> normalizeTRBL(1) (1, 1, 1, 1) >>> normalizeTRBL((1, 1.2)) (1, 1.2, 1, 1.2) >>> normalizeTRBL((1, 1.2, 0)) (1, 1.2, 0, 1.2) >>> normalizeTRBL((1, 1.2, 0, 8)) (1, 1.2, 0, 8)
reportlab.lib.logger
Logging and warning framework, predating Python’s logging package
- class reportlab.lib.logger.Logger
An extended file type thing initially equivalent to sys.stderr You can add/remove file type things; it has a write method
- add(fp)
add the file/string fp to the destinations
- remove(fp)
remove the file/string fp from the destinations
- write(text)
write text to all the destinations
reportlab.lib.normalDate
Jeff Bauer’s lightweight date class, extended by us. Predates Python’s datetime module.
- class reportlab.lib.normalDate.BusinessDate(normalDate=None)
Specialised NormalDate
- add(days)
add days to date; use negative integers to subtract
- asNormalDate()
- daysBetweenDates(normalDate)
return value may be negative, since calculation is self.scalar() - arg
- normalize(i)
convert scalar to normalDate
- scalar()
days since baseline date: Jan 1, 1900
- setNormalDate(normalDate)
accepts date as scalar string/integer (yyyymmdd) or tuple (year, month, day, …)
- reportlab.lib.normalDate.FND(d)
convert to ND if required
- reportlab.lib.normalDate.ND
alias of
NormalDate
- class reportlab.lib.normalDate.NormalDate(normalDate=None)
NormalDate is a specialized class to handle dates without all the excess baggage (time zones, daylight savings, leap seconds, etc.) of other date structures. The minimalist strategy greatly simplifies its implementation and use.
Internally, NormalDate is stored as an integer with values in a discontinuous range of -99990101 to 99991231. The integer value is used principally for storage and to simplify the user interface. Internal calculations are performed by a scalar based on Jan 1, 1900.
Valid NormalDate ranges include (-9999,1,1) B.C.E. through (9999,12,31) C.E./A.D.
- 1.0
No changes, except the version number. After 3 years of use by various parties I think we can consider it stable.
- 0.8
- Added Prof. Stephen Walton’s suggestion for a range method
module author resisted the temptation to use lambda <0.5 wink>
- 0.7
Added Dan Winkler’s suggestions for __add__, __sub__ methods
- 0.6
- Modifications suggested by Kevin Digweed to fix:
dayOfWeek, dayOfWeekAbbrev, clone methods
Permit NormalDate to be a better behaved superclass
- 0.5
Minor tweaking
- 0.4
Added methods __cmp__, __hash__
Added Epoch variable, scoped to the module
Added setDay, setMonth, setYear methods
- 0.3
Minor touch-ups
- 0.2
Fixed bug for certain B.C.E leap years
Added Jim Fulton’s suggestions for short alias class name =ND and __getstate__, __setstate__ methods
Special thanks: Roedy Green
- add(days)
add days to date; use negative integers to subtract
- clone()
return a cloned instance of this normalDate
- day()
return the day as integer 1-31
- dayOfWeek()
return integer representing day of week, Mon=0, Tue=1, etc.
- dayOfWeekAbbrev()
return day of week abbreviation for current date: Mon, Tue, etc.
- dayOfWeekName()
return day of week name for current date: Monday, Tuesday, etc.
- dayOfYear()
day of year
- daysBetweenDates(normalDate)
return value may be negative, since calculation is self.scalar() - arg
- endOfMonth()
returns (cloned) last day of month
- equals(target)
- firstDayOfMonth()
returns (cloned) first day of month
- formatMS(fmt)
format like MS date using the notation {YY} –> 2 digit year {YYYY} –> 4 digit year {M} –> month as digit {MM} –> 2 digit month {MMM} –> abbreviated month name {MMMM} –> monthname {MMMMM} –> first character of monthname {D} –> day of month as digit {DD} –> 2 digit day of month {DDD} –> abrreviated weekday name {DDDD} –> weekday name
- formatUS()
return date as string in common US format: MM/DD/YY
- formatUSCentury()
return date as string in 4-digit year US format: MM/DD/YYYY
- isLeapYear()
determine if specified year is leap year, returning true (1) or false (0)
- lastDayOfMonth()
returns last day of the month as integer 28-31
- localeFormat()
override this method to use your preferred locale format
- month()
returns month as integer 1-12
- monthAbbrev()
returns month as a 3-character abbreviation, i.e. Jan, Feb, etc.
- monthName()
returns month name, i.e. January, February, etc.
- normalize(scalar)
convert scalar to normalDate
- range(days)
Return a range of normalDates as a list. Parameter may be an int or normalDate.
- scalar()
days since baseline date: Jan 1, 1900
- setDay(day)
set the day of the month
- setMonth(month)
set the month [1-12]
- setNormalDate(normalDate)
accepts date as scalar string/integer (yyyymmdd) or tuple (year, month, day, …)
- setYear(year)
- toTuple()
return date as (year, month, day) tuple
- year()
return year in yyyy format, negative values indicate B.C.
- exception reportlab.lib.normalDate.NormalDateException
Exception class for NormalDate
- reportlab.lib.normalDate.bigBang()
return lower boundary as a NormalDate
- reportlab.lib.normalDate.bigCrunch()
return upper boundary as a NormalDate
- reportlab.lib.normalDate.dayOfWeek(y, m, d)
return integer representing day of week, Mon=0, Tue=1, etc.
- reportlab.lib.normalDate.firstDayOfYear(year)
number of days to the first of the year, relative to Jan 1, 1900
- reportlab.lib.normalDate.getStdDayNames()
- reportlab.lib.normalDate.getStdMonthNames()
- reportlab.lib.normalDate.getStdShortDayNames()
- reportlab.lib.normalDate.getStdShortMonthNames()
- reportlab.lib.normalDate.isLeapYear(year)
determine if specified year is leap year, returns Python boolean
reportlab.lib.pagesizes
This module defines a few common page sizes in points (1/72 inch). To be expanded to include things like label sizes, envelope windows etc.
- reportlab.lib.pagesizes.landscape(pagesize)
Use this to get page orientation right
- reportlab.lib.pagesizes.portrait(pagesize)
Use this to get page orientation right
reportlab.lib.pdfencrypt
- class reportlab.lib.pdfencrypt.EncryptionFlowable(userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=None)
Drop this in your Platypus story and it will set up the encryption options.
If you do it multiple times, the last one before saving will win.
- draw()
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.lib.pdfencrypt.StandardEncryption(userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=None)
- encode(t)
encode a string, stream, text
- info()
- permissionBits()
- prepare(document, overrideID=None)
- prepared = 0
- register(objnum, version)
- setAllPermissions(value)
- class reportlab.lib.pdfencrypt.StandardEncryptionDictionary(O, OE, U, UE, P, Perms, revision)
- format(document)
- reportlab.lib.pdfencrypt.checkRevision(revision)
- reportlab.lib.pdfencrypt.checkU(encryptionkey, U)
- reportlab.lib.pdfencrypt.computeO(userPassword, ownerPassword, revision)
- reportlab.lib.pdfencrypt.computeU(encryptionkey, encodestring=b'(\xbfN^Nu\x8aAd\x00NV\xff\xfa\x01\x08..\x00\xb6\xd0h>\x80/\x0c\xa9\xfedSiz', revision=None, documentId=None)
- reportlab.lib.pdfencrypt.encodePDF(key, objectNumber, generationNumber, string, revision=None)
Encodes a string or stream
- reportlab.lib.pdfencrypt.encryptCanvas(canvas, userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=40)
Applies encryption to the document being generated
- reportlab.lib.pdfencrypt.encryptDocTemplate(dt, userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=40)
For use in Platypus. Call before build().
- reportlab.lib.pdfencrypt.encryptPdfInMemory(inputPDF, userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=40)
accepts a PDF file ‘as a byte array in memory’; return encrypted one.
This is a high level convenience and does not touch the hard disk in any way. If you are encrypting the same file over and over again, it’s better to use pageCatcher and cache the results.
- reportlab.lib.pdfencrypt.encryptPdfOnDisk(inputFileName, outputFileName, userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=40)
Creates encrypted file OUTPUTFILENAME. Returns size in bytes.
- reportlab.lib.pdfencrypt.encryptionkey(password, OwnerKey, Permissions, FileId1, revision=None)
- reportlab.lib.pdfencrypt.equalityCheck(observed, expected, label)
- reportlab.lib.pdfencrypt.hexText(text)
a legitimate way to show strings in PDF
- reportlab.lib.pdfencrypt.main()
- reportlab.lib.pdfencrypt.scriptInterp()
- reportlab.lib.pdfencrypt.test()
- reportlab.lib.pdfencrypt.unHexText(hexText)
- reportlab.lib.pdfencrypt.xorKey(num, key)
xor’s each byte of the key with the number, which is <256
reportlab.lib.pygments2xpre
Helps you output colourised code snippets in ReportLab documents.
Platypus has an ‘XPreformatted’ flowable for handling preformatted text, with variations in fonts and colors. If Pygments is installed, calling ‘pygments2xpre’ will return content suitable for display in an XPreformatted object. If it’s not installed, you won’t get colours.
For a list of available lexers see http://pygments.org/docs/
- reportlab.lib.pygments2xpre.pygments2xpre(s, language='python')
Return markup suitable for XPreformatted
reportlab.lib.randomtext
Like Lorem Ipsum, but more fun and extensible.
This module exposes a function randomText() which generates paragraphs. These can be used when testing out document templates and stylesheets. A number of ‘themes’ are provided - please contribute more! We need some real Greek text too.
- There are currently six themes provided:
STARTUP (words suitable for a business plan - or not as the case may be), COMPUTERS (names of programming languages and operating systems etc), BLAH (variations on the word ‘blah’), BUZZWORD (buzzword bingo), STARTREK (Star Trek), PRINTING (print-related terms) PYTHON (snippets and quotes from Monty Python) CHOMSKY (random lingusitic nonsense)
- EXAMPLE USAGE:
from reportlab.lib import randomtext print randomtext.randomText(randomtext.PYTHON, 10)
This prints a random number of random sentences (up to a limit of ten) using the theme ‘PYTHON’.
- reportlab.lib.randomtext.chomsky(times=1)
- reportlab.lib.randomtext.format_wisdom(text, line_length=72)
- reportlab.lib.randomtext.randomText(theme=['strategic', 'direction', 'proactive', 'venture capital', 'reengineering', 'forecast', 'resources', 'SWOT analysis', 'forward-thinking', 'profit', 'growth', 'doubletalk', 'B2B', 'B2C', 'venture capital', 'IPO', "NASDAQ meltdown - we're all doomed!"], sentences=5)
reportlab.lib.rl_accel
- reportlab.lib.rl_accel.add32(x, y)
Calculate (x + y) modulo 2**32
- reportlab.lib.rl_accel.asciiBase85Decode(input)
Decodes input using ASCII-Base85 coding.
This is not normally used - Acrobat Reader decodes for you - but a round trip is essential for testing.
- reportlab.lib.rl_accel.asciiBase85Encode(input)
Encodes input using ASCII-Base85 coding.
This is a compact encoding used for binary data within a PDF file. Four bytes of binary data become five bytes of ASCII. This is the default method used for encoding images.
- reportlab.lib.rl_accel.calcChecksum(data)
Calculates TTF-style checksums
- reportlab.lib.rl_accel.escapePDF(s)
- reportlab.lib.rl_accel.fp_str(*a)
convert separate arguments (or single sequence arg) into space separated numeric strings
- reportlab.lib.rl_accel.hex32(i)
- reportlab.lib.rl_accel.instanceStringWidthT1(self, text, size, encoding='utf8')
This is the “purist” approach to width
- reportlab.lib.rl_accel.instanceStringWidthTTF(self, text, size, encoding='utf8')
Calculate text width
- reportlab.lib.rl_accel.sameFrag(f, g, _cmp=('fontName', 'fontSize', 'textColor', 'rise', 'us_lines', 'link', 'backColor', 'nobr'))
- reportlab.lib.rl_accel.unicode2T1(utext, fonts)
return a list of (font,string) pairs representing the unicode text
reportlab.lib.rl_safe_eval
- exception reportlab.lib.rl_safe_eval.BadCode
- class reportlab.lib.rl_safe_eval.UntrustedAstTransformer(names_seen=None, nameIsAllowed=None)
- check_function_argument_names(node)
- check_import_names(node)
Check the names being imported.
This is a protection against rebinding dunder names like __rl_getitem__,__rl_set__ via imports.
=> ‘from _a import x’ is ok, because ‘_a’ is not added to the scope.
- error(node, msg)
- gen_attr_check(node, attr_name)
Check if ‘attr_name’ is allowed on the object in node.
It generates (_getattr_(node, attr_name) and node).
- gen_del_stmt(name_to_del)
- gen_lambda(args, body)
- gen_unpack_spec(tpl)
Generate a specification for ‘__rl_unpack_sequence__’.
This spec is used to protect sequence unpacking. The primary goal of this spec is to tell which elements in a sequence are sequences again. These ‘child’ sequences have to be protected again.
- For example there is a sequence like this:
(a, (b, c), (d, (e, f))) = g
- On a higher level the spec says:
There is a sequence of len 3
The element at index 1 is a sequence again with len 2
The element at index 2 is a sequence again with len 2 - The element at index 1 in this subsequence is a sequence again
with len 2
With this spec ‘__rl_unpack_sequence__’ does something like this for protection (len checks are omitted):
t = list(__rl_getiter__(g)) t[1] = list(__rl_getiter__(t[1])) t[2] = list(__rl_getiter__(t[2])) t[2][1] = list(__rl_getiter__(t[2][1])) return t
- The ‘real’ spec for the case above is then:
- spec = {
‘min_len’: 3, ‘childs’: (
(1, {‘min_len’: 2, ‘childs’: ()}), (2, {
‘min_len’: 2, ‘childs’: (
(1, {‘min_len’: 2, ‘childs’: ()})
)
}
)
)
}
- So finally the assignment above is converted into:
(a, (b, c), (d, (e, f))) = __rl_unpack_sequence__(g, spec)
- gen_unpack_wrapper(node, target, ctx='store')
Helper function to protect tuple unpacks.
node: used to copy the locations for the new nodes. target: is the tuple which must be protected. ctx: Defines the context of the returned temporary node.
It returns a tuple with two element.
- Element 1: Is a temporary name node which must be used to
replace the target. The context (store, param) is defined by the ‘ctx’ parameter..
- Element 2: Is a try .. finally where the body performs the
protected tuple unpack of the temporary variable into the original target.
- generic_visit(node)
Reject nodes which do not have a corresponding visit method.
- guard_iter(node)
- Converts:
for x in expr
- to
for x in __rl_getiter__(expr)
Also used for * list comprehensions * dict comprehensions * set comprehensions * generator expresions
- isAllowedName(node, name)
- is_starred(ob)
- not_allowed(node)
- protect_unpack_sequence(target, value)
- property tmpName
- transform_slice(slice_)
Transform slices into function parameters.
ast.Slice nodes are only allowed within a ast.Subscript node. To use a slice as an argument of ast.Call it has to be converted. Conversion is done by calling the ‘slice’ function from builtins
- visit_Add(node)
Visit the contents of a node.
- visit_And(node)
Visit the contents of a node.
- visit_Assert(node)
Visit the contents of a node.
- visit_Assign(node)
- visit_AsyncFor(node)
- visit_AsyncFunctionDef(node)
- visit_AsyncWith(node)
- visit_Attribute(node)
Checks and mutates attribute access/assignment.
‘a.b’ becomes ‘__rl_getattr__(a, “b”)’
- visit_AugAssign(node)
Forbid certain kinds of AugAssign
According to the language reference (and ast.c) the following nodes are are possible: Name, Attribute, Subscript
Note that although augmented assignment of attributes and subscripts is disallowed, augmented assignment of names (such as ‘n += 1’) is allowed. ‘n += 1’ becomes ‘n = __rl_augAssign__(“+=”, n, 1)’
- visit_Await(node)
- visit_BinOp(node)
- visit_BitAnd(node)
Visit the contents of a node.
- visit_BitOr(node)
Visit the contents of a node.
- visit_BitXor(node)
Visit the contents of a node.
- visit_BoolOp(node)
Visit the contents of a node.
- visit_Break(node)
Visit the contents of a node.
- visit_Bytes(node)
Visit the contents of a node.
- visit_Call(node)
Checks calls with ‘*args’ and ‘**kwargs’.
Note: The following happens only if ‘*args’ or ‘**kwargs’ is used.
Transfroms ‘foo(<all the possible ways of args>)’ into __rl_apply__(foo, <all the possible ways for args>)
The thing is that ‘__rl_apply__’ has only ‘*args’, ‘**kwargs’, so it gets Python to collapse all the myriad ways to call functions into one manageable from.
From there, ‘__rl_apply__()’ wraps args and kws in guarded accessors, then calls the function, returning the value.
- visit_ClassDef(node)
Check the name of a class definition.
- visit_Compare(node)
Visit the contents of a node.
- visit_Constant(node)
Visit the contents of a node.
- visit_Continue(node)
Visit the contents of a node.
- visit_Del(node)
Visit the contents of a node.
- visit_Delete(node)
Visit the contents of a node.
- visit_Dict(node)
Visit the contents of a node.
- visit_DictComp(node)
Visit the contents of a node.
- visit_Div(node)
Visit the contents of a node.
- visit_Ellipsis(node)
- visit_Eq(node)
Visit the contents of a node.
- visit_ExceptHandler(node)
Protect tuple unpacking on exception handlers.
- try:
- except Exception as (a, b):
becomes
- try:
- except Exception as tmp:
- try:
(a, b) = __rl_getiter__(tmp)
- finally:
del tmp
- visit_Exec(node)
- visit_Expr(node)
Visit the contents of a node.
- visit_Expression(node)
Visit the contents of a node.
- visit_ExtSlice(node)
Visit the contents of a node.
- visit_FloorDiv(node)
Visit the contents of a node.
- visit_For(node)
- Converts:
for x in expr
- to
for x in __rl_getiter__(expr)
Also used for * list comprehensions * dict comprehensions * set comprehensions * generator expresions
- visit_FormattedValue(node)
Visit the contents of a node.
- visit_FunctionDef(node)
Allow function definitions (def) with some restrictions.
- visit_GeneratorExp(node)
Visit the contents of a node.
- visit_Global(node)
Visit the contents of a node.
- visit_Gt(node)
Visit the contents of a node.
- visit_GtE(node)
Visit the contents of a node.
- visit_If(node)
Visit the contents of a node.
- visit_IfExp(node)
Visit the contents of a node.
- visit_Import(node)
- visit_ImportFrom(node)
- visit_In(node)
Visit the contents of a node.
- visit_Index(node)
Visit the contents of a node.
- visit_Invert(node)
Visit the contents of a node.
- visit_Is(node)
Visit the contents of a node.
- visit_IsNot(node)
Visit the contents of a node.
- visit_JoinedStr(node)
Visit the contents of a node.
- visit_LShift(node)
Visit the contents of a node.
- visit_Lambda(node)
Allow lambda with some restrictions.
- visit_List(node)
Visit the contents of a node.
- visit_ListComp(node)
Visit the contents of a node.
- visit_Load(node)
Visit the contents of a node.
- visit_Lt(node)
Visit the contents of a node.
- visit_LtE(node)
Visit the contents of a node.
- visit_MatMult(node)
- visit_Mod(node)
Visit the contents of a node.
- visit_Module(node)
Visit the contents of a node.
- visit_Mult(node)
Visit the contents of a node.
- visit_Name(node)
- visit_NameConstant(node)
Visit the contents of a node.
- visit_Nonlocal(node)
- visit_Not(node)
Visit the contents of a node.
- visit_NotEq(node)
Visit the contents of a node.
- visit_NotIn(node)
Visit the contents of a node.
- visit_Num(node)
Visit the contents of a node.
- visit_Or(node)
Visit the contents of a node.
- visit_Param(node)
Visit the contents of a node.
- visit_Pass(node)
Visit the contents of a node.
- visit_Pow(node)
Visit the contents of a node.
- visit_Print(node)
- visit_RShift(node)
Visit the contents of a node.
- visit_Raise(node)
Visit the contents of a node.
- visit_Return(node)
Visit the contents of a node.
- visit_Set(node)
Visit the contents of a node.
- visit_SetComp(node)
Visit the contents of a node.
- visit_Slice(node)
Visit the contents of a node.
- visit_Starred(node)
Visit the contents of a node.
- visit_Store(node)
Visit the contents of a node.
- visit_Str(node)
Visit the contents of a node.
- visit_Sub(node)
Visit the contents of a node.
- visit_Subscript(node)
Transforms all kinds of subscripts.
‘v[a]’ becomes ‘__rl_getitem__(foo, a)’ ‘v[:b]’ becomes ‘__rl_getitem__(foo, slice(None, b, None))’ ‘v[a:]’ becomes ‘__rl_getitem__(foo, slice(a, None, None))’ ‘v[a:b]’ becomes ‘__rl_getitem__(foo, slice(a, b, None))’ ‘v[a:b:c]’ becomes ‘__rl_getitem__(foo, slice(a, b, c))’ ‘v[a,b:c] becomes ‘__rl_getitem__(foo, (a, slice(b, c, None)))’ #’v[a] = c’ becomes ‘_rl_write__(v)[a] = c’ #’del v[a]’ becomes ‘del __rl_sd__(v)[a]’
- visit_Try(node)
Visit the contents of a node.
- visit_TryExcept(node)
Visit the contents of a node.
- visit_TryFinally(node)
Visit the contents of a node.
- visit_Tuple(node)
Visit the contents of a node.
- visit_UAdd(node)
Visit the contents of a node.
- visit_USub(node)
Visit the contents of a node.
- visit_UnaryOp(node)
Visit the contents of a node.
- visit_While()
- visit_With(node)
Protect tuple unpacking on with statements.
- visit_Yield(node)
Visit the contents of a node.
- visit_YieldFrom(node)
Visit the contents of a node.
- visit_alias(node)
Visit the contents of a node.
- visit_arg(node)
Visit the contents of a node.
- visit_arguments(node)
Visit the contents of a node.
- visit_children(node)
Visit the contents of a node.
- visit_comprehension(node)
- Converts:
for x in expr
- to
for x in __rl_getiter__(expr)
Also used for * list comprehensions * dict comprehensions * set comprehensions * generator expresions
- visit_keyword(node)
Visit the contents of a node.
- visit_withitem(node)
Visit the contents of a node.
- reportlab.lib.rl_safe_eval.astFormat(node)
- reportlab.lib.rl_safe_eval.copy_locations(new_node, old_node)
- reportlab.lib.rl_safe_eval.rl_extended_literal_eval(expr, safe_callables=None, safe_names=None)
- reportlab.lib.rl_safe_eval.rl_less_safe_eval(expr, NS)
eval with our so called safe globals
- reportlab.lib.rl_safe_eval.safer_globals(g=None)
reportlab.lib.rltempfile
Helper for the test suite - determines where to write output.
When our test suite runs as source, a script “test_foo.py” will typically create “test_foo.pdf” alongside it. But if you are testing a package of compiled code inside a zip archive, this won’t work. This determines where to write test suite output, creating a subdirectory of /tmp/ or whatever if needed.
- reportlab.lib.rltempfile.get_rl_tempdir(*subdirs)
reportlab.lib.rparsexml
Very simple and fast XML parser, used for intra-paragraph text.
Devised by Aaron Watters in the bad old days before Python had fast parsers available. Constructs the lightest possible in-memory representation; parses most files we have seen in pure python very quickly.
The output structure is the same as the one produced by pyRXP, our validating C-based parser, which was written later. It will use pyRXP if available.
This is used to parse intra-paragraph markup.
Example parse:
<this type="xml">text <b>in</b> xml</this>
( "this",
{"type": "xml"},
[ "text ",
("b", None, ["in"], None),
" xml"
]
None )
{ 0: "this"
"type": "xml"
1: ["text ",
{0: "b", 1:["in"]},
" xml"]
}
- Ie, xml tag translates to a tuple:
(name, dictofattributes, contentlist, miscellaneousinfo)
where miscellaneousinfo can be anything, (but defaults to None) (with the intention of adding, eg, line number information)
special cases: name of “” means “top level, no containing tag”. Top level parse always looks like this:
("", list, None, None)
contained text of None means <simple_tag/>
In order to support stuff like:
<this></this><one></one>
AT THE MOMENT & ETCETERA ARE IGNORED. THEY MUST BE PROCESSED IN A POST-PROCESSING STEP.
PROLOGUES ARE NOT UNDERSTOOD. OTHER STUFF IS PROBABLY MISSING.
- reportlab.lib.rparsexml.parseFile(filename)
- reportlab.lib.rparsexml.parsexml(xmltext, oneOutermostTag=0, eoCB=None, entityReplacer=<function unEscapeContentList>)
official interface: discard unused cursor info
- reportlab.lib.rparsexml.parsexml0(xmltext, startingat=0, toplevel=1, entityReplacer=<function unEscapeContentList>)
simple recursive descent xml parser… return (dictionary, endcharacter) special case: comment returns (None, endcharacter)
- reportlab.lib.rparsexml.parsexmlSimple(xmltext, oneOutermostTag=0, eoCB=None, entityReplacer=<function unEscapeContentList>)
official interface: discard unused cursor info
- reportlab.lib.rparsexml.pprettyprint(parsedxml)
pretty printer mainly for testing
- reportlab.lib.rparsexml.skip_prologue(text, cursor)
skip any prologue found after cursor, return index of rest of text
- reportlab.lib.rparsexml.test(dump=0)
- reportlab.lib.rparsexml.testparse(s, dump=0)
- reportlab.lib.rparsexml.unEscapeContentList(contentList)
reportlab.lib.sequencer
A Sequencer class counts things. It aids numbering and formatting lists.
- class reportlab.lib.sequencer.Sequencer
Something to make it easy to number paragraphs, sections, images and anything else. The features include registering new string formats for sequences, and ‘chains’ whereby some counters are reset when their parents. It keeps track of a number of ‘counters’, which are created on request: Usage:
>>> seq = layout.Sequencer() >>> seq.next('Bullets') 1 >>> seq.next('Bullets') 2 >>> seq.next('Bullets') 3 >>> seq.reset('Bullets') >>> seq.next('Bullets') 1 >>> seq.next('Figures') 1 >>>
- chain(parent, child)
- dump()
Write current state to stdout for diagnostics
- format(template)
The crowning jewels - formats multi-level lists.
- next(counter=None)
- nextf(counter=None)
Retrieves the numeric value for the given counter, then increments it by one. New counters start at one.
- registerFormat(format, func)
Registers a new formatting function. The funtion must take a number as argument and return a string; fmt is a short menmonic string used to access it.
- reset(counter=None, base=0)
- setDefaultCounter(default=None)
Changes the key used for the default
- setFormat(counter, format)
Specifies that the given counter should use the given format henceforth.
- thisf(counter=None)
- reportlab.lib.sequencer.getSequencer()
- reportlab.lib.sequencer.setSequencer(seq)
reportlab.lib.styles
Classes for ParagraphStyle and similar things.
A style is a collection of attributes, but with some extra features to allow ‘inheritance’ from a parent, and to ensure nobody makes changes after construction.
ParagraphStyle shows all the attributes available for formatting paragraphs.
getSampleStyleSheet() returns a stylesheet you can use for initial development, with a few basic heading and text styles.
- class reportlab.lib.styles.LineStyle(name, parent=None, **kw)
- defaults = {'color': Color(0,0,0,1), 'width': 1}
- prepareCanvas(canvas)
You can ask a LineStyle to set up the canvas for drawing the lines.
- class reportlab.lib.styles.ListStyle(name, parent=None, **kw)
- defaults = {'bulletAlign': 'left', 'bulletColor': Color(0,0,0,1), 'bulletDedent': 'auto', 'bulletDir': 'ltr', 'bulletFontName': 'Helvetica', 'bulletFontSize': 12, 'bulletFormat': None, 'bulletOffsetY': 0, 'bulletType': '1', 'leftIndent': 18, 'rightIndent': 0, 'start': None}
- class reportlab.lib.styles.ParagraphStyle(name, parent=None, **kw)
- defaults = {'alignment': 0, 'allowOrphans': 0, 'allowWidows': 1, 'backColor': None, 'borderColor': None, 'borderPadding': 0, 'borderRadius': None, 'borderWidth': 0, 'bulletAnchor': 'start', 'bulletFontName': 'Helvetica', 'bulletFontSize': 10, 'bulletIndent': 0, 'embeddedHyphenation': 0, 'endDots': None, 'firstLineIndent': 0, 'fontName': 'Helvetica', 'fontSize': 10, 'hyphenationLang': '', 'justifyBreaks': 0, 'justifyLastLine': 0, 'leading': 12, 'leftIndent': 0, 'linkUnderline': 0, 'rightIndent': 0, 'shaping': 0, 'spaceAfter': 0, 'spaceBefore': 0, 'spaceShrinkage': 0.05, 'splitLongWords': 1, 'strikeColor': None, 'strikeGap': '1', 'strikeOffset': '0.25*F', 'strikeWidth': '', 'textColor': Color(0,0,0,1), 'textTransform': None, 'underlineColor': None, 'underlineGap': '1', 'underlineOffset': '-0.125*F', 'underlineWidth': '', 'uriWasteReduce': 0, 'wordWrap': None}
- class reportlab.lib.styles.PropertySet(name, parent=None, **kw)
- clone(name, parent=None, **kwds)
- defaults = {}
- listAttrs(indent='')
- refresh()
re-fetches attributes from the parent on demand; use if you have been hacking the styles. This is used by __init__
- class reportlab.lib.styles.StyleSheet1
This may or may not be used. The idea is to:
slightly simplify construction of stylesheets;
enforce rules to validate styles when added (e.g. we may choose to disallow having both ‘heading1’ and ‘Heading1’ - actual rules are open to discussion);
allow aliases and alternate style lookup mechanisms
Have a place to hang style-manipulation methods (save, load, maybe support a GUI editor)
Access is via getitem, so they can be compatible with plain old dictionaries.
- add(style, alias=None)
- get(key, default=<object object>)
- has_key(key)
- list()
- reportlab.lib.styles.getSampleStyleSheet()
Returns a stylesheet object
- reportlab.lib.styles.str2alignment(v, __map__={'center': 1, 'centre': 1, 'justify': 4, 'left': 0, 'right': 2})
reportlab.lib.testutils
Provides support for the test suite.
The test suite as a whole, and individual tests, need to share certain support functions. We have to put these in here so they can always be imported, and so that individual tests need to import nothing more than “reportlab.whatever…”
- class reportlab.lib.testutils.CVSGlobDirectoryWalker(directory, pattern='*')
An directory tree iterator that checks for CVS data.
- filterFiles(folder, files)
Filters files not listed in CVS subfolder.
This will look in the CVS subfolder of ‘folder’ for a file named ‘Entries’ and filter all elements from the ‘files’ list that are not listed in ‘Entries’.
- class reportlab.lib.testutils.ExtConfigParser(defaults=None, dict_type=<class 'dict'>, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section='DEFAULT', interpolation=<object object>, converters=<object object>)
A slightly extended version to return lists of strings.
- getstringlist(section, option)
Coerce option to a list of strings or return unchanged if that fails.
- pat = re.compile('\\s*\\[.*\\]\\s*')
- class reportlab.lib.testutils.GlobDirectoryWalker(directory, pattern='*')
A forward iterator that traverses files in a directory tree.
- filterFiles(folder, files)
Filter hook, overwrite in subclasses as needed.
- class reportlab.lib.testutils.NearTestCase(methodName='runTest')
- static assertNear(a, b, accuracy=1e-05)
- class reportlab.lib.testutils.RestrictedGlobDirectoryWalker(directory, pattern='*', ignore=None)
An restricted directory tree iterator.
- filterFiles(folder, files)
Filters all items from files matching patterns to ignore.
- class reportlab.lib.testutils.ScriptThatMakesFileTest(scriptDir, scriptName, outFileName, verbose=0)
Runs a Python script at OS level, expecting it to produce a file.
It CDs to the working directory to run the script.
- runTest()
- setUp()
Hook method for setting up the test fixture before exercising it.
- tearDown()
Hook method for deconstructing the test fixture after testing it.
- class reportlab.lib.testutils.SecureTestCase(methodName='runTest')
Secure testing base class with additional pre- and postconditions.
We try to ensure that each test leaves the environment it has found unchanged after the test is performed, successful or not.
Currently we restore sys.path and the working directory, but more of this could be added easily, like removing temporary files or similar things.
Use this as a base class replacing unittest.TestCase and call these methods in subclassed versions before doing your own business!
- setUp()
Remember sys.path and current working directory.
- tearDown()
Restore previous sys.path and working directory.
- reportlab.lib.testutils.eqCheck(r, x)
- reportlab.lib.testutils.equalStrings(a, b, enc='utf8')
- reportlab.lib.testutils.getCVSEntries(folder, files=1, folders=0)
Returns a list of filenames as listed in the CVS/Entries file.
‘folder’ is the folder that should contain the CVS subfolder. If there is no such subfolder an empty list is returned. ‘files’ is a boolean; 1 and 0 means to return files or not. ‘folders’ is a boolean; 1 and 0 means to return folders or not.
- reportlab.lib.testutils.haveDejaVu()
- reportlab.lib.testutils.haveRenderPM()
- reportlab.lib.testutils.isWritable(D)
- reportlab.lib.testutils.makeSuiteForClasses(*classes, testMethodPrefix=None)
Return a test suite with tests loaded from provided classes.
- reportlab.lib.testutils.mockUrlRead(name)
- reportlab.lib.testutils.outputfile(fn)
This works out where to write test output. If running code in a locked down file system, this will be a temp directory; otherwise, the output of ‘test_foo.py’ will normally be a file called ‘test_foo.pdf’, next door.
- reportlab.lib.testutils.printLocation(depth=1)
- reportlab.lib.testutils.rlSkip(reason, __module__=None)
- reportlab.lib.testutils.rlSkipIf(cond, reason, __module__=None)
- reportlab.lib.testutils.rlSkipUnless(cond, reason, __module__=None)
- reportlab.lib.testutils.rlextraNeeded()
- reportlab.lib.testutils.setOutDir(name)
Is it a writable file system distro being invoked within test directory? If so, can write test output here. If not, it had better go in a temp directory. Only do this once per process
reportlab.lib.textsplit
Helpers for text wrapping, hyphenation, Asian text splitting and kinsoku shori.
How to split a ‘big word’ depends on the language and the writing system. This module works on a Unicode string. It ought to grow by allowing ore algoriths to be plugged in based on possible knowledge of the language and desirable ‘niceness’ of the algorithm.
- reportlab.lib.textsplit.cjkwrap(text, width, encoding='utf8')
- reportlab.lib.textsplit.dumbSplit(word, widths, maxWidths)
This function attempts to fit as many characters as possible into the available space, cutting “like a knife” between characters. This would do for Chinese. It returns a list of (text, extraSpace) items where text is a Unicode string, and extraSpace is the points of unused space available on the line. This is a structure which is fairly easy to display, and supports ‘backtracking’ approaches after the fact.
Test cases assume each character is ten points wide…
>>> dumbSplit(u'Hello', [10]*5, 60) [[10, u'Hello']] >>> dumbSplit(u'Hello', [10]*5, 50) [[0, u'Hello']] >>> dumbSplit(u'Hello', [10]*5, 40) [[0, u'Hell'], [30, u'o']]
- reportlab.lib.textsplit.getCharWidths(word, fontName, fontSize)
Returns a list of glyph widths.
>>> getCharWidths('Hello', 'Courier', 10) [6.0, 6.0, 6.0, 6.0, 6.0] >>> from reportlab.pdfbase.cidfonts import UnicodeCIDFont >>> from reportlab.pdfbase.pdfmetrics import registerFont >>> registerFont(UnicodeCIDFont('HeiseiMin-W3')) >>> getCharWidths(u'東京', 'HeiseiMin-W3', 10) #most kanji are 100 ems [10.0, 10.0]
- reportlab.lib.textsplit.is_multi_byte(ch)
Is this an Asian character?
- reportlab.lib.textsplit.kinsokuShoriSplit(word, widths, availWidth)
Split according to Japanese rules according to CJKV (Lunde).
Essentially look for “nice splits” so that we don’t end a line with an open bracket, or start one with a full stop, or stuff like that. There is no attempt to try to split compound words into constituent kanji. It currently uses wrap-down: packs as much on a line as possible, then backtracks if needed
This returns a number of words each of which should just about fit on a line. If you give it a whole paragraph at once, it will do all the splits.
It’s possible we might slightly step over the width limit if we do hanging punctuation marks in future (e.g. dangle a Japanese full stop in the right margin rather than using a whole character box.
- reportlab.lib.textsplit.wordSplit(word, maxWidths, fontName, fontSize, encoding='utf8')
Attempts to break a word which lacks spaces into two parts, the first of which fits in the remaining space. It is allowed to add hyphens or whatever it wishes.
This is intended as a wrapper for some language- and user-choice-specific splitting algorithms. It should only be called after line breaking on spaces, which covers western languages and is highly optimised already. It works on the ‘last unsplit word’.
Presumably with further study one could write a Unicode splitting algorithm for text fragments whick was much faster.
Courier characters should be 6 points wide. >>> wordSplit(‘HelloWorld’, 30, ‘Courier’, 10) [[0.0, ‘Hello’], [0.0, ‘World’]] >>> wordSplit(‘HelloWorld’, 31, ‘Courier’, 10) [[1.0, ‘Hello’], [1.0, ‘World’]]
reportlab.lib.units
Defines inch, cm, mm etc as multiples of a point
You can now in user-friendly units by doing:
from reportlab.lib.units import inch
r = Rect(0, 0, 3 * inch, 6 * inch)
- reportlab.lib.units.toLength(s)
convert a string to a length
reportlab.lib.utils
Gazillions of miscellaneous internal utility functions
- class reportlab.lib.utils.ArgvDictValue(value, func)
A type to allow clients of getArgvDict to specify a conversion function
- class reportlab.lib.utils.CIDict(*args, **kwds)
- get(k, dv=None)
Return the value for key if key is in the dictionary, else default.
- pop(k[, d]) v, remove specified key and return the corresponding value.
If the key is not found, return the default if given; otherwise, raise a KeyError.
- setdefault(k, *a)
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- update([E, ]**F) None. Update D from dict/iterable E and F.
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- class reportlab.lib.utils.DebugMemo(fn='rl_dbgmemo.dbg', mode='w', getScript=1, modules=(), capture_traceback=1, stdout=None, **kw)
Intended as a simple report back encapsulator
Typical usages:
To record error data:
dbg = DebugMemo(fn='dbgmemo.dbg',myVar=value) dbg.add(anotherPayload='aaaa',andagain='bbb') dbg.dump()
To show the recorded info:
dbg = DebugMemo(fn='dbgmemo.dbg',mode='r') dbg.load() dbg.show()
To re-use recorded information:
dbg = DebugMemo(fn='dbgmemo.dbg',mode='r') dbg.load() myTestFunc(dbg.payload('myVar'),dbg.payload('andagain'))
In addition to the payload variables the dump records many useful bits of information which are also printed in the show() method.
- add(**kw)
- dump()
- dumps()
- load()
- loads(s)
- payload(name)
- show()
- specials = {'__module_versions': <function DebugMemo._show_module_versions>, '__payload': <function DebugMemo._show_payload>, '__script': <function DebugMemo._show_file>, '__traceback': <function DebugMemo._show_lines>}
- class reportlab.lib.utils.FixedOffsetTZ(h, m, name)
Fixed offset in minutes east from UTC.
- dst(dt)
datetime -> DST offset as timedelta positive east of UTC.
- tzname(dt)
datetime -> string name of time zone.
- utcoffset(dt)
datetime -> timedelta showing offset from UTC, negative values indicating West of UTC
- class reportlab.lib.utils.FmtSelfDict
mixin to provide the _fmt method
- class reportlab.lib.utils.IdentStr(value)
useful for identifying things that get split
- class reportlab.lib.utils.ImageReader(fileName, ident=None)
Wraps up PIL to get data from bitmaps
- classmethod check_pil_image_size(im)
- getImageData()
- getRGBData()
Return byte array of RGB data as string
- getSize()
- getTransparent()
- identity()
try to return information that will identify the instance
- jpeg_fh()
- classmethod set_max_image_size(max_image_size=None)
- class reportlab.lib.utils.LazyImageReader(fileName, ident=None)
- class reportlab.lib.utils.RLString(v, **kwds)
allows specification of extra properties of a string using a dictionary of extra attributes eg fontName = RLString(‘proxima-nova-bold’,
svgAttrs=dict(family=‘“proxima-nova”’,weight=’bold’))
- reportlab.lib.utils.annotateException(msg, enc='utf8', postMsg='', sep=' ')
add msg to the args of an existing exception
- reportlab.lib.utils.asBytes(v, enc='utf8')
- reportlab.lib.utils.asNative(v, enc='utf8')
- reportlab.lib.utils.asUnicode(v, enc='utf8')
- reportlab.lib.utils.asUnicodeEx(v, enc='utf8')
- reportlab.lib.utils.bytestr(x, enc='utf8')
- reportlab.lib.utils.char2int(s)
- reportlab.lib.utils.commajoin(l)
Inverse of commasplit, except that whitespace around items is not conserved. Adds more whitespace than needed for simplicity and performance.
>>> commasplit(commajoin(['a', 'b', 'c'])) == [u'a', u'b', u'c'] True >>> commasplit((commajoin([u'a,', u' b ', u'c'])) == [u'a,', u'b', u'c'] True >>> commasplit((commajoin([u'a ', u',b', u'c'])) == [u'a', u',b', u'c']
- reportlab.lib.utils.commasplit(s)
Splits the string s at every unescaped comma and returns the result as a list. To escape a comma, double it. Individual items are stripped. To avoid the ambiguity of 3 successive commas to denote a comma at the beginning or end of an item, add a space between the item seperator and the escaped comma.
>>> commasplit(u'a,b,c') == [u'a', u'b', u'c'] True >>> commasplit('a,, , b , c ') == [u'a,', u'b', u'c'] True >>> commasplit(u'a, ,,b, c') == [u'a', u',b', u'c']
- reportlab.lib.utils.decode_label(label)
- reportlab.lib.utils.encode_label(args)
- reportlab.lib.utils.escapeOnce(data)
Ensure XML output is escaped just once, irrespective of input
>>> escapeOnce('A & B') 'A & B' >>> escapeOnce('C & D') 'C & D' >>> escapeOnce('E &amp; F') 'E & F'
- reportlab.lib.utils.escapeTextOnce(text)
Escapes once only
- reportlab.lib.utils.fileName2FSEnc(fn)
- reportlab.lib.utils.findInPaths(fn, paths, isfile=True, fail=False)
search for relative files in likely places
- reportlab.lib.utils.find_locals(func, depth=0)
apply func to the locals at each stack frame till func returns a non false value
- reportlab.lib.utils.flatten(L)
recursively flatten the list or tuple L
- reportlab.lib.utils.getArgvDict(**kw)
Builds a dictionary from its keyword arguments with overrides from sys.argv. Attempts to be smart about conversions, but the value can be an instance of ArgDictValue to allow specifying a conversion function.
- reportlab.lib.utils.getHyphenater(hDict=None)
- reportlab.lib.utils.getImageData(imageFileName)
Get width, height and RGB pixels from image file. Wraps PIL
- reportlab.lib.utils.instantiated(v)
- reportlab.lib.utils.int2Byte(i)
- reportlab.lib.utils.isBytes(v)
- reportlab.lib.utils.isClass(v)
- reportlab.lib.utils.isCompactDistro()
return truth if not a file system distribution
- reportlab.lib.utils.isFileSystemDistro()
return truth if a file system distribution
- reportlab.lib.utils.isFunction(v)
- reportlab.lib.utils.isMethod(v, mt=<class 'function'>)
- reportlab.lib.utils.isModule(v)
- reportlab.lib.utils.isNative(v)
- reportlab.lib.utils.isNonPrimitiveInstance(x)
- reportlab.lib.utils.isSeq(v, _st=(<class 'tuple'>, <class 'list'>))
- reportlab.lib.utils.isSourceDistro()
return truth if a source file system distribution
- reportlab.lib.utils.isStr(v)
- reportlab.lib.utils.isUnicode(v)
- reportlab.lib.utils.makeFileName(s)
force filename strings to unicode so python can handle encoding stuff
- reportlab.lib.utils.markfilename(filename, creatorcode=None, filetype=None)
- reportlab.lib.utils.normalize_path(p)
- reportlab.lib.utils.open_and_read(name, mode='b')
- reportlab.lib.utils.open_and_readlines(name, mode='t')
- reportlab.lib.utils.open_for_read(name, mode='b')
attempt to open a file or URL for reading
- reportlab.lib.utils.open_for_read_by_name(name, mode='b')
- reportlab.lib.utils.prev_this_next(items)
Loop over a collection with look-ahead and look-back.
From Thomas Guest, http://wordaligned.org/articles/zippy-triples-served-with-python
Seriously useful looping tool (Google “zippy triples”) lets you loop a collection and see the previous and next items, which get set to None at the ends.
To be used in layout algorithms where one wants a peek at the next item coming down the pipe.
- reportlab.lib.utils.rawBytes(s)
converts first 256 unicodes 1-1
- reportlab.lib.utils.rawUnicode(s)
converts first 256 unicodes 1-1
- reportlab.lib.utils.recursiveDelAttr(obj, name)
- reportlab.lib.utils.recursiveGetAttr(obj, name, g=None)
Can call down into e.g. object1.object2[4].attr
- reportlab.lib.utils.recursiveImport(modulename, baseDir=None, noCWD=0, debug=0)
Dynamically imports possible packagized module, or raises ImportError
- reportlab.lib.utils.recursiveSetAttr(obj, name, value)
Can call down into e.g. object1.object2[4].attr = value
- reportlab.lib.utils.rlUrlRead(name)
- reportlab.lib.utils.rl_add_builtins(**kwd)
- reportlab.lib.utils.rl_get_module(name, dir)
- reportlab.lib.utils.rl_getmtime(pn, os_path_isfile=<function isfile>, os_path_normpath=<built-in function _path_normpath>, os_path_getmtime=<function getmtime>, time_mktime=<built-in function mktime>)
- reportlab.lib.utils.rl_glob(pattern, glob=<function glob>)
- reportlab.lib.utils.rl_isdir(pn, os_path_isdir=<function isdir>, os_path_normpath=<built-in function _path_normpath>)
- reportlab.lib.utils.rl_isfile(fn, os_path_isfile=<function isfile>)
- reportlab.lib.utils.rl_listdir(pn, os_path_isdir=<function isdir>, os_path_normpath=<built-in function _path_normpath>, os_listdir=<built-in function listdir>)
- reportlab.lib.utils.rl_reraise(t, v, b=None)
- reportlab.lib.utils.simpleSplit(text, fontName, fontSize, maxWidth)
- reportlab.lib.utils.yieldNoneSplits(L)
yield sublists of L separated by None; the Nones disappear
- reportlab.lib.utils.zipImported(ldr=None)
reportlab.lib.validators
Standard verifying functions used by attrmap.
- class reportlab.lib.validators.DerivedValue
This is used for magic values which work themselves out. An example would be an “inherit” property, so that one can have
drawing.chart.categoryAxis.labels.fontName = inherit
and pick up the value from the top of the drawing. Validators will permit this provided that a value can be pulled in which satisfies it. And the renderer will have special knowledge of these so they can evaluate themselves.
- getValue(renderer, attr)
Override this. The renderers will pass the renderer, and the attribute name. Algorithms can then backtrack up through all the stuff the renderer provides, including a correct stack of parent nodes.
- class reportlab.lib.validators.Inherit
- getValue(renderer, attr)
Override this. The renderers will pass the renderer, and the attribute name. Algorithms can then backtrack up through all the stuff the renderer provides, including a correct stack of parent nodes.
- class reportlab.lib.validators.NumericAlign(dp='.', dpLen=0)
for creating the numeric string value for anchors etc etc dp is the character to align on (the last occurrence will be used) dpLen is the length of characters after the dp
- class reportlab.lib.validators.OneOf(enum, *args)
Make validator functions for list of choices.
Usage: f = reportlab.lib.validators.OneOf(‘happy’,’sad’) or f = reportlab.lib.validators.OneOf((‘happy’,’sad’)) f(‘sad’),f(‘happy’), f(‘grumpy’) (1,1,0)
- test(x)
- class reportlab.lib.validators.Percentage(x=0, /)
reportlab.lib.yaml
.h1 Welcome to YAML! YAML is “Yet Another Markup Language” - a markup language which is easier to type in than XML, yet gives us a reasonable selection of formats.
The general rule is that if a line begins with a ‘.’, it requires special processing. Otherwise lines are concatenated to paragraphs, and blank lines separate paragraphs.
If the line “.foo bar bletch” is encountered, it immediately ends and writes out any current paragraph.
It then looks for a parser method called ‘foo’; if found, it is called with arguments (bar, bletch).
If this is not found, it assumes that ‘foo’ is a paragraph style, and the text for the first line of the paragraph is ‘bar bletch’. It would be up to the formatter to decide whether on not ‘foo’ was a valid paragraph.
Special commands understood at present are: dot image filename - adds the image to the document dot beginPre Code - begins a Preformatted object in style ‘Code’ dot endPre - ends a preformatted object.
- class reportlab.lib.yaml.BaseParser
“Simplest possible parser with only the most basic options.
This defines the line-handling abilities and basic mechanism. The class YAMLParser includes capabilities for a fairly rich story.
- beginPre(stylename)
- endPara()
- endPre()
- image(filename)
- parseFile(filename)
- parseText(textBlock)
Parses the a possible multi-line text block
- readLine(line)
- reset()
- class reportlab.lib.yaml.Parser
This adds a basic set of “story” components compatible with HTML & PDF.
Images, spaces
- custom(moduleName, funcName)
Goes and gets the Python object and adds it to the story
- nextPageTemplate(templateName)
- pageBreak()
Inserts a frame break
- vSpace(points)
Inserts a vertical spacer
- reportlab.lib.yaml.parseFile(filename)
- reportlab.lib.yaml.parseText(textBlock)
reportlab.pdfbase
Internal functionality for creating PDF files - not part of API
reportlab.pdfbase.acroform
- class reportlab.pdfbase.acroform.AcroForm(canv, **kwds)
- property canv
- checkForceBorder(x, y, width, height, forceBorder, shape, borderStyle, borderWidth, borderColor, fillColor)
- checkbox(checked=False, buttonStyle='check', shape='square', fillColor=None, borderColor=None, textColor=None, borderWidth=1, borderStyle='solid', size=20, x=0, y=0, tooltip=None, name=None, annotationFlags='print', fieldFlags='required', forceBorder=False, relative=False, dashLen=3)
- checkboxAP(key, value, buttonStyle='circle', shape='square', fillColor=None, borderColor=None, textColor=None, borderWidth=1, borderStyle='solid', size=20, dashLen=3)
- checkboxRelative(**kwds)
same as checkbox except the x and y are relative to the canvas coordinate transform
- choice(value='', fillColor=None, borderColor=None, textColor=None, borderWidth=1, borderStyle='solid', width=120, height=36, x=0, y=0, tooltip=None, name=None, annotationFlags='print', fieldFlags='combo', forceBorder=False, relative=False, fontName=None, fontSize=None, dashLen=3, maxlen=None, options=[])
- choiceRelative(**kwds)
same as textfield except the x and y are relative to the canvas coordinate transform
- static circleArcStream(size, r, arcs=(0, 1, 2, 3), rotated=False)
- colorTuple(c)
- property encRefStr
- fontRef(f)
- formFontNames = {'Courier': 'Cour', 'Courier-Bold': 'CoBo', 'Courier-BoldOblique': 'CoBO', 'Courier-Oblique': 'CoOb', 'Helvetica': 'Helv', 'Helvetica-Bold': 'HeBo', 'Helvetica-BoldOblique': 'HeBO', 'Helvetica-Oblique': 'HeOb', 'Times-Bold': 'TiBo', 'Times-BoldItalic': 'TiBI', 'Times-Italic': 'TiIt', 'Times-Roman': 'Time'}
- format(doc)
- getRef(obj)
- getRefStr(obj)
- listbox(value='', fillColor=None, borderColor=None, textColor=None, borderWidth=1, borderStyle='solid', width=120, height=36, x=0, y=0, tooltip=None, name=None, annotationFlags='print', fieldFlags='', forceBorder=False, relative=False, fontName=None, fontSize=None, dashLen=3, maxlen=None, options=[])
- listboxRelative(**kwds)
same as textfield except the x and y are relative to the canvas coordinate transform
- makeFont(fontName)
- makeStream(width, height, stream, **D)
- radio(value=None, selected=False, buttonStyle='circle', shape='circle', fillColor=None, borderColor=None, textColor=None, borderWidth=1, borderStyle='solid', size=20, x=0, y=0, tooltip=None, name=None, annotationFlags='print', fieldFlags='noToggleToOff required radio', forceBorder=False, relative=False, dashLen=3)
- radioRelative(**kwds)
same as radio except the x and y are relative to the canvas coordinate transform
- static stdColors(t, b, f)
- streamFillColor(c)
- streamStrokeColor(c)
- textfield(value='', fillColor=None, borderColor=None, textColor=None, borderWidth=1, borderStyle='solid', width=120, height=36, x=0, y=0, tooltip=None, name=None, annotationFlags='print', fieldFlags='', forceBorder=False, relative=False, maxlen=100, fontName=None, fontSize=None, dashLen=3)
- textfieldRelative(**kwds)
same as textfield except the x and y are relative to the canvas coordinate transform
- txAP(key, value, iFontName, rFontName, fontSize, shape='square', fillColor=None, borderColor=None, textColor=None, borderWidth=1, borderStyle='solid', width=120, height=36, dashLen=3, wkind='textfield', labels=[], I=[], sel_bg='0.600006 0.756866 0.854904 rg', sel_fg='0 g')
- static varyColors(key, t, b, f)
- zdMark(c, size, ds, iFontName)
reportlab.pdfbase.cidfonts
CID (Asian multi-byte) font support.
This defines classes to represent CID fonts. They know how to calculate their own width and how to write themselves into PDF files.
- class reportlab.pdfbase.cidfonts.CIDEncoding(name, useCache=1)
Multi-byte encoding. These are loaded from CMAP files.
A CMAP file is like a mini-codec. It defines the correspondence between code points in the (multi-byte) input data and Character IDs.
- fastLoad(directory)
- fastSave(directory)
- getData()
Simple persistence helper. Return a dict with all that matters.
- parseCMAPFile(name)
This is a tricky one as CMAP files are Postscript ones. Some refer to others with a ‘usecmap’ command
- translate(text)
Convert a string into a list of CIDs
- class reportlab.pdfbase.cidfonts.CIDFont(face, encoding)
Represents a built-in multi-byte font
- addObjects(doc)
The explicit code in addMinchoObjects and addGothicObjects will be replaced by something that pulls the data from _cidfontdata.py in the next few days.
- formatForPdf(text)
- stringWidth(text, size, encoding=None)
This presumes non-Unicode input. UnicodeCIDFont wraps it for that context
- class reportlab.pdfbase.cidfonts.CIDTypeFace(name)
Multi-byte type face.
Conceptually similar to a single byte typeface, but the glyphs are identified by a numeric Character ID (CID) and not a glyph name.
- getCharWidth(characterId)
- class reportlab.pdfbase.cidfonts.UnicodeCIDFont(face, isVertical=False, isHalfWidth=False)
Wraps up CIDFont to hide explicit encoding choice; encodes text for output as UTF16.
lang should be one of ‘jpn’,chs’,’cht’,’kor’ for now. if vertical is set, it will select a different widths array and possibly glyphs for some punctuation marks.
halfWidth is only for Japanese.
>>> dodgy = UnicodeCIDFont('nonexistent') Traceback (most recent call last): ... KeyError: "don't know anything about CID font nonexistent" >>> heisei = UnicodeCIDFont('HeiseiMin-W3') >>> heisei.name 'HeiseiMin-W3' >>> heisei.language 'jpn' >>> heisei.encoding.name 'UniJIS-UCS2-H' >>> #This is how PDF data gets encoded. >>> print(heisei.formatForPdf('hello')) \000h\000e\000l\000l\000o >>> tokyo = u'東䫬' >>> print(heisei.formatForPdf(tokyo)) gqJ\354 >>> print(heisei.stringWidth(tokyo,10)) 20.0 >>> print(heisei.stringWidth('hello world',10)) 45.83
- formatForPdf(text)
- stringWidth(text, size, encoding=None)
Just ensure we do width test on characters, not bytes…
- reportlab.pdfbase.cidfonts.findCMapFile(name)
Returns full filename, or raises error
- reportlab.pdfbase.cidfonts.precalculate(cmapdir)
- reportlab.pdfbase.cidfonts.structToPDF(structure)
Converts deeply nested structure to PDFdoc dictionary/array objects
- reportlab.pdfbase.cidfonts.test()
reportlab.pdfbase.pdfdoc
The module pdfdoc.py handles the ‘outer structure’ of PDF documents, ensuring that all objects are properly cross-referenced and indexed to the nearest byte. The ‘inner structure’ - the page descriptions - are presumed to be generated before each page is saved. pdfgen.py calls this and provides a ‘canvas’ object to handle page marking operators. piddlePDF calls pdfgen and offers a high-level interface.
The classes within this generally mirror structures in the PDF file and are not part of any public interface. Instead, canvas and font classes are made available elsewhere for users to manipulate.
- class reportlab.pdfbase.pdfdoc.Annotation
superclass for all annotations.
- AnnotationDict(**kw)
- Dict()
- cvtdict(d, escape=1)
transform dict args from python form to pdf string rep as needed
- defaults = [('Type', '/Annot')]
- format(document)
- permitted = ('Type', 'Rect', 'Contents', 'Subtype', 'Border', 'C', 'T', 'M', 'F', 'H', 'BS', 'AA', 'AS', 'Popup', 'P', 'AP')
- required = ('Type', 'Rect', 'Contents', 'Subtype')
- class reportlab.pdfbase.pdfdoc.Destination(name)
not a PDFObject! This is a placeholder that can delegates to a pdf object only after it has been defined by the methods below.
EG a Destination can refer to Appendix A before it has been defined, but only if Appendix A is explicitly noted as a destination and resolved before the document is generated…
- For example the following sequence causes resolution before doc generation.
d = Destination() d.fit() # or other format defining method call d.setPage(p) (at present setPageRef is called on generation of the page).
- fit()
- fitb()
- fitbh(top)
- fitbv(left)
- fith(top)
- fitr(left, bottom, right, top)
- fitv(left)
- format(document)
- page = None
- representation = None
- setPage(page)
- xyz(left, top, zoom)
- class reportlab.pdfbase.pdfdoc.DummyDoc
used to bypass encryption when required
- encrypt = <reportlab.pdfbase.pdfdoc.NoEncryption object>
- exception reportlab.pdfbase.pdfdoc.DuplicatePageLabelPage
- class reportlab.pdfbase.pdfdoc.FreeTextAnnotation(Rect, Contents, DA, **kw)
- Dict()
- permitted = ('Type', 'Rect', 'Contents', 'Subtype', 'Border', 'C', 'T', 'M', 'F', 'H', 'BS', 'AA', 'AS', 'Popup', 'P', 'AP', 'DA')
- class reportlab.pdfbase.pdfdoc.HighlightAnnotation(Rect, Contents, QuadPoints, Color=[0.83, 0.89, 0.95], **kw)
HighlightAnnotation is an annotation that highlights the selected area.
Rect is the mouseover area that will show the contents.
QuadPoints is a list of points to highlight, you can have many groups of four QuadPoints to allow highlighting many lines.
- Dict()
- cvtdict(d, escape=1)
transform dict args from python form to pdf string rep as needed
- permitted = ('Type', 'Rect', 'Contents', 'Subtype', 'Border', 'C', 'T', 'M', 'F', 'H', 'BS', 'AA', 'AS', 'Popup', 'P', 'AP', 'QuadPoints')
- class reportlab.pdfbase.pdfdoc.LinkAnnotation(Rect, Contents, Destination, Border='[0 0 1]', **kw)
- Dict()
- dummyDictString()
- permitted = ('Type', 'Rect', 'Contents', 'Subtype', 'Border', 'C', 'T', 'M', 'F', 'H', 'BS', 'AA', 'AS', 'Popup', 'P', 'AP', 'Dest', 'A', 'PA')
- class reportlab.pdfbase.pdfdoc.NoEncryption
- encode(t)
encode a string, stream, text
- info()
- prepare(document)
- register(objnum, version)
- class reportlab.pdfbase.pdfdoc.OutlineEntryObject
an entry in an outline
- Count = None
- Dest = None
- First = None
- Last = None
- Next = None
- Parent = None
- Prev = None
- Title = None
- format(document)
- class reportlab.pdfbase.pdfdoc.PDFArray(sequence)
- References(document)
make all objects in sequence references
- format(document, IND=b'\n ')
- multiline = True
- class reportlab.pdfbase.pdfdoc.PDFAxialShading(x0, y0, x1, y1, Function, ColorSpace, **kw)
- Dict(document)
- permitted = ('ShadingType', 'ColorSpace', 'Background', 'BBox', 'AntiAlias', 'Coords', 'Domain', 'Function', 'Extend')
- required = ('ShadingType', 'ColorSpace', 'Coords', 'Function')
- class reportlab.pdfbase.pdfdoc.PDFCatalog
- check_format(document)
for use in subclasses
- format(document)
- setPageLayout(layout)
- setPageMode(mode)
- showFullScreen()
- showOutline()
- class reportlab.pdfbase.pdfdoc.PDFCrossReferenceSubsection(firstentrynumber, idsequence)
- format(document)
id sequence should represent contiguous object nums else error. free numbers not supported (yet)
- class reportlab.pdfbase.pdfdoc.PDFCrossReferenceTable
- addsection(firstentry, ids)
- format(document)
- class reportlab.pdfbase.pdfdoc.PDFDestinationFitR(page, left, bottom, right, top)
- format(document)
- typename = 'FitR'
- class reportlab.pdfbase.pdfdoc.PDFDestinationXYZ(page, left, top, zoom)
- format(document)
- typename = 'XYZ'
- class reportlab.pdfbase.pdfdoc.PDFDictionary(dict=None)
- Reference(name, document)
- copy()
- format(document, IND=b'\n ')
- multiline = True
- normalize()
- class reportlab.pdfbase.pdfdoc.PDFDocument(dummyoutline=0, compression=1, invariant=0, filename=None, pdfVersion=(1, 3), lang=None)
- GetPDFData(canvas)
- ID()
A unique fingerprint for the file (unless in invariant mode)
- Reference(obj, name=None)
- SaveToFile(filename, canvas)
- addAnnotation(name, annotation)
- addColor(cmyk)
- addForm(name, form)
add a Form XObject.
- addPage(page)
- addShading(shading)
- annotationName(externalname)
- defaultStreamFilters = None
- encrypt = <reportlab.pdfbase.pdfdoc.NoEncryption object>
- ensureMinPdfVersion(*keys)
Ensure that the pdf version is greater than or equal to that specified by the keys
- format()
- getAvailableFonts()
- getFormBBox(name, boxType='MediaBox')
get the declared bounding box of the form as a list. If you specify a different PDF box definition (e.g. the ArtBox) and it has one, that’s what you’ll get.
- getInternalFontName(psfontname)
- getXObjectName(name)
Lets canvas find out what form is called internally. Never mind whether it is defined yet or not.
- hasForm(name)
test for existence of named form
- inForm()
specify that we are in a form xobject (disable page features, etc)
- inPage()
specify the current object as a page (enables reference binding and other page features)
- refAnnotation(name)
- setAuthor(author)
embedded in PDF file
- setCompression(onoff)
- setCreator(creator)
embeds in PDF file
- setDateFormatter(dateFormatter)
- setKeywords(keywords)
embeds a string containing keywords in PDF file
- setProducer(producer)
embeds in PDF file
- setSubject(subject)
embeds in PDF file
- setTitle(title)
embeds in PDF file
- thisPageName()
- thisPageRef()
- updateSignature(thing)
add information to the signature
- xobjDict(formnames)
construct an xobject dict (for inclusion in a resource dict, usually) from a list of form names (images not yet supported)
- exception reportlab.pdfbase.pdfdoc.PDFError
- class reportlab.pdfbase.pdfdoc.PDFExponentialFunction(C0, C1, N, **kw)
- Dict(document)
- defaults = [('Domain', <reportlab.pdfbase.pdfdoc.PDFArrayCompact object>)]
- permitted = ('FunctionType', 'Domain', 'Range', 'C0', 'C1', 'N')
- required = ('FunctionType', 'Domain', 'N')
- class reportlab.pdfbase.pdfdoc.PDFFile(pdfVersion=(1, 3))
- add(s)
should be constructed as late as possible, return position where placed
- closeOrReset()
- format(document)
- class reportlab.pdfbase.pdfdoc.PDFFormXObject(lowerx, lowery, upperx, uppery)
- Annots = None
- BBox = None
- BBoxList()
get the declared bounding box for the form as a list
- Contents = None
- Matrix = None
- Resources = None
- XObjects = None
- compression = 0
- format(document)
- hasImages = 1
- setStreamList(data)
- stream = None
- class reportlab.pdfbase.pdfdoc.PDFFunction
superclass for all function types.
- Dict(document)
- FunctionDict(**kw)
- defaults = []
- format(document)
- permitted = ('FunctionType', 'Domain', 'Range')
- required = ('FunctionType', 'Domain')
- class reportlab.pdfbase.pdfdoc.PDFFunctionShading(Function, ColorSpace, **kw)
- Dict(document)
- permitted = ('ShadingType', 'ColorSpace', 'Background', 'BBox', 'AntiAlias', 'Domain', 'Matrix', 'Function')
- required = ('ShadingType', 'ColorSpace', 'Function')
- class reportlab.pdfbase.pdfdoc.PDFImageXObject(name, source=None, mask=None)
- format(document)
- loadImageFromA85(source)
- loadImageFromJPEG(imageFile)
- loadImageFromRaw(source)
- loadImageFromSRC(im)
Extracts the stream, width and height
- class reportlab.pdfbase.pdfdoc.PDFInfo
PDF documents can have basic information embedded, viewable from File | Document Info in Acrobat Reader. If this is wrong, you get Postscript errors while printing, even though it does not print.
- author = 'anonymous'
- copy()
shallow copy - useful in pagecatchering
- creator = 'ReportLab PDF Library - www.reportlab.com'
- digest(md5object)
- format(document)
- keywords = ''
- producer = 'ReportLab PDF Library - www.reportlab.com'
- subject = 'unspecified'
- title = 'untitled'
- reportlab.pdfbase.pdfdoc.PDFName(data, lo='!', hi='~')
- class reportlab.pdfbase.pdfdoc.PDFObject
- class reportlab.pdfbase.pdfdoc.PDFOutlines
takes a recursive list of outline destinations like:
out = PDFOutline1() out.setNames(canvas, # requires canvas for name resolution "chapter1dest", ("chapter2dest", ["chapter2section1dest", "chapter2section2dest", "chapter2conclusiondest"] ), # end of chapter2 description "chapter3dest", ("chapter4dest", ["c4s1", "c4s2"]) )
Higher layers may build this structure incrementally. KISS at base level.
- addOutlineEntry(destinationname, level=0, title=None, closed=None)
destinationname of None means “close the tree”
- counter = 0
- currentlevel = -1
- format(document)
- maketree(document, destinationtree, Parent=None, toplevel=0)
- mydestinations = None
- prepare(document, canvas)
prepare all data structures required for save operation (create related objects)
- ready = None
- setDestinations(destinationtree)
- setNameList(canvas, nametree)
Explicit list so I don’t need to do in the caller
- setNames(canvas, *nametree)
- translateNames(canvas, object)
recursively translate tree of names into tree of destinations
- class reportlab.pdfbase.pdfdoc.PDFOutlines0
- format(document)
- text = '\n<<\n /Count\n 0\n /Type\n /Outlines\n>>'
- class reportlab.pdfbase.pdfdoc.PDFPage
- Override_default_compilation = 0
- Trans = None
- XObjects = None
- check_format(document)
for use in subclasses
- compression = 0
- hasImages = 0
- pageheight = 842
- pagewidth = 595
- setCompression(onoff)
- setPageTransition(tranDict)
- setStream(code)
- stream = None
- class reportlab.pdfbase.pdfdoc.PDFPageLabel(style=None, start=None, prefix=None)
- ARABIC = 'D'
- LETTERS_LOWER = 'a'
- LETTERS_UPPER = 'A'
- ROMAN_LOWER = 'r'
- ROMAN_UPPER = 'R'
- class reportlab.pdfbase.pdfdoc.PDFPageLabels
- addPageLabel(page, label)
Adds a new PDFPageLabel to this catalog. The ‘page’ argument, an integer, is the page number in the PDF document with which the ‘label’ should be associated. Page numbering in the PDF starts at zero! Thus, to change the label on the first page, ‘0’ should be provided as an argument, and to change the 6th page, ‘5’ should be provided as the argument.
The ‘label’ argument should be a PDFPageLabel instance, which describes the format of the labels starting on page ‘page’ in the PDF and continuing until the next encounter of a PDFPageLabel.
The order in which labels are added is not important.
- format(document)
- class reportlab.pdfbase.pdfdoc.PDFPages
PAGES TREE WITH ONE INTERNAL NODE, FOR “BALANCING” CHANGE IMPLEMENTATION
- addPage(page)
- check_format(document)
for use in subclasses
- class reportlab.pdfbase.pdfdoc.PDFPostScriptXObject(content=None)
For embedding PD (e.g. tray commands) in PDF
- format(document)
- class reportlab.pdfbase.pdfdoc.PDFRadialShading(x0, y0, r0, x1, y1, r1, Function, ColorSpace, **kw)
- Dict(document)
- permitted = ('ShadingType', 'ColorSpace', 'Background', 'BBox', 'AntiAlias', 'Coords', 'Domain', 'Function', 'Extend')
- required = ('ShadingType', 'ColorSpace', 'Coords', 'Function')
- class reportlab.pdfbase.pdfdoc.PDFResourceDictionary(**kwds)
each element could be reset to a reference if desired
- allProcs()
- basicFonts()
- basicProcs()
- dict_attributes = ('ColorSpace', 'XObject', 'ExtGState', 'Font', 'Pattern', 'Properties', 'Shading')
- format(document)
- setColorSpace(colorsUsed)
- setShading(shadingUsed)
- stdprocs = ['/PDF', '/Text', '/ImageB', '/ImageC', '/ImageI']
- class reportlab.pdfbase.pdfdoc.PDFShading
superclass for all shading types.
- Dict(document)
- ShadingDict(**kw)
- format(document)
- permitted = ('ShadingType', 'ColorSpace', 'Background', 'BBox', 'AntiAlias')
- required = ('ShadingType', 'ColorSpace')
- class reportlab.pdfbase.pdfdoc.PDFStitchingFunction(Functions, Bounds, Encode, **kw)
- Dict(document)
- permitted = ('FunctionType', 'Domain', 'Range', 'Functions', 'Bounds', 'Encode')
- required = ('FunctionType', 'Domain', 'Functions', 'Bounds', 'Encode')
- class reportlab.pdfbase.pdfdoc.PDFStream(dictionary=None, content=None, filters=None)
set dictionary elements explicitly stream.dictionary[name]=value
- format(document)
- class reportlab.pdfbase.pdfdoc.PDFStreamFilterBase85Encode
- decode(text)
- encode(text)
- pdfname = 'ASCII85Decode'
- class reportlab.pdfbase.pdfdoc.PDFStreamFilterZCompress
- decode(encoded)
- encode(text)
- pdfname = 'FlateDecode'
- class reportlab.pdfbase.pdfdoc.PDFString(s, escape=1, enc='auto')
- format(document)
- unicodeEncValid = False
- class reportlab.pdfbase.pdfdoc.PDFTrailer(startxref, Size=None, Prev=None, Root=None, Info=None, ID=None, Encrypt=None)
- format(document)
- class reportlab.pdfbase.pdfdoc.PDFType1Font
no init: set attributes explicitly
- Subtype = 'Type1'
- Type = 'Font'
- format(document)
- local_attributes = ['FirstChar', 'LastChar', 'Widths', 'Encoding', 'ToUnicode', 'FontDescriptor']
- name_attributes = ['Type', 'Subtype', 'BaseFont', 'Name']
- reportlab.pdfbase.pdfdoc.PDFnumber(n)
- class reportlab.pdfbase.pdfdoc.TextAnnotation(Rect, Contents, **kw)
- Dict()
- permitted = ('Type', 'Rect', 'Contents', 'Subtype', 'Border', 'C', 'T', 'M', 'F', 'H', 'BS', 'AA', 'AS', 'Popup', 'P', 'AP', 'QuadPoints', 'Open', 'Name')
- class reportlab.pdfbase.pdfdoc.ViewerPreferencesPDFDictionary(dict=None, validate=None)
- validate = {'CenterWindow': <function checkPDFBoolean>, 'Direction': <reportlab.pdfbase.pdfdoc.checkPDFNames object>, 'DisplayDocTitle': <function checkPDFBoolean>, 'Duplex': <reportlab.pdfbase.pdfdoc.checkPDFNames object>, 'FitWindow': <function checkPDFBoolean>, 'HideMenubar': <function checkPDFBoolean>, 'HideToolbar': <function checkPDFBoolean>, 'HideWindowUI': <function checkPDFBoolean>, 'NonFullScreenPageMode': <reportlab.pdfbase.pdfdoc.checkPDFNames object>, 'PrintArea': <reportlab.pdfbase.pdfdoc.checkPDFNames object>, 'PrintClip': <reportlab.pdfbase.pdfdoc.checkPDFNames object>, 'PrintScaling': <reportlab.pdfbase.pdfdoc.checkPDFNames object>, 'ViewArea': <reportlab.pdfbase.pdfdoc.checkPDFNames object>, 'ViewClip': <reportlab.pdfbase.pdfdoc.checkPDFNames object>}
- reportlab.pdfbase.pdfdoc.checkPDFBoolean(value)
- class reportlab.pdfbase.pdfdoc.checkPDFNames(*names)
- reportlab.pdfbase.pdfdoc.count(tree, closedict=None)
utility for outline: recursively count leaves in a tuple/list tree
- reportlab.pdfbase.pdfdoc.formName(externalname)
- reportlab.pdfbase.pdfdoc.format(element, document, toplevel=0)
Indirection step for formatting. Ensures that document parameters alter behaviour of formatting for all elements.
- reportlab.pdfbase.pdfdoc.pdfdocEnc(x)
- reportlab.pdfbase.pdfdoc.rect_to_quad(Rect)
Utility method to convert a Rect to a QuadPoint
- reportlab.pdfbase.pdfdoc.testpage(document)
- reportlab.pdfbase.pdfdoc.teststream(content=None)
- reportlab.pdfbase.pdfdoc.xObjectName(externalname)
reportlab.pdfbase.pdfform
Support for Acrobat Forms in ReportLab documents
This module is somewhat experimental at this time.
- Includes basic support for
textfields, select fields (drop down lists), and check buttons.
The public interface consists of functions at the moment. At some later date these operations may be made into canvas methods. (comments?)
The …Absolute(…) functions position the fields with respect to the absolute canvas coordinate space – that is, they do not respect any coordinate transforms in effect for the canvas.
The …Relative(…) functions position the ONLY THE LOWER LEFT CORNER of the field using the coordinate transform in effect for the canvas. THIS WILL ONLY WORK CORRECTLY FOR TRANSLATED COORDINATES – THE SHAPE, SIZE, FONTSIZE, AND ORIENTATION OF THE FIELD WILL NOT BE EFFECTED BY SCALING, ROTATION, SKEWING OR OTHER NON-TRANSLATION COORDINATE TRANSFORMS.
Please note that all field names (titles) in a given document must be unique. Textfields and select fields only support the “base 14” canvas fonts at this time.
See individual function docstrings below for more information.
The function test1(…) generates a simple test file.
THIS CONTRIBUTION WAS COMMISSIONED BY REPORTLAB USERS WHO WISH TO REMAIN ANONYMOUS.
- class reportlab.pdfbase.pdfform.AcroForm
- buttonField(canvas, title, value, xmin, ymin, width=16.7704, height=14.907)
- format(document)
- selectField(canvas, title, value, options, xmin, ymin, xmax, ymax)
- textField(canvas, title, xmin, ymin, xmax, ymax, value='', maxlen=1000000, multiline=0)
- reportlab.pdfbase.pdfform.ButtonField(title, value, xmin, ymin, page, width=16.7704, height=14.907)
- reportlab.pdfbase.pdfform.ButtonStream(content, width=16.7704, height=14.907)
- reportlab.pdfbase.pdfform.FormFont(BaseFont, Name)
- reportlab.pdfbase.pdfform.FormFontsDictionary()
- reportlab.pdfbase.pdfform.FormResources()
- reportlab.pdfbase.pdfform.SelectField(title, value, options, xmin, ymin, xmax, ymax, page, font='Helvetica-Bold', fontsize=9, R=0, G=0, B=0.627)
- reportlab.pdfbase.pdfform.TextField(title, value, xmin, ymin, xmax, ymax, page, maxlen=1000000, font='Helvetica-Bold', fontsize=9, R=0, G=0, B=0.627, multiline=0)
- reportlab.pdfbase.pdfform.buttonFieldAbsolute(canvas, title, value, x, y, width=16.7704, height=14.907)
Place a check button field on the current page with name title and default value value (one of “Yes” or “Off”) at ABSOLUTE position (x,y).
- reportlab.pdfbase.pdfform.buttonFieldRelative(canvas, title, value, xR, yR, width=16.7704, height=14.907)
same as buttonFieldAbsolute except the x and y are relative to the canvas coordinate transform
- reportlab.pdfbase.pdfform.buttonStreamDictionary(width=16.7704, height=14.907)
everything except the length for the button appearance streams
- reportlab.pdfbase.pdfform.getForm(canvas)
get form from canvas, create the form if needed
- reportlab.pdfbase.pdfform.resetPdfForm()
- reportlab.pdfbase.pdfform.selectFieldAbsolute(canvas, title, value, options, x, y, width, height)
Place a select field (drop down list) on the current page with name title and with options listed in the sequence options default value value (must be one of options) at ABSOLUTE position (x,y) with dimensions (width, height).
- reportlab.pdfbase.pdfform.selectFieldRelative(canvas, title, value, options, xR, yR, width, height)
same as textFieldAbsolute except the x and y are relative to the canvas coordinate transform
- reportlab.pdfbase.pdfform.textFieldAbsolute(canvas, title, x, y, width, height, value='', maxlen=1000000, multiline=0)
Place a text field on the current page with name title at ABSOLUTE position (x,y) with dimensions (width, height), using value as the default value and maxlen as the maximum permissible length. If multiline is set make it a multiline field.
- reportlab.pdfbase.pdfform.textFieldRelative(canvas, title, xR, yR, width, height, value='', maxlen=1000000, multiline=0)
same as textFieldAbsolute except the x and y are relative to the canvas coordinate transform
reportlab.pdfbase.pdfmetrics
This provides a database of font metric information and efines Font, Encoding and TypeFace classes aimed at end users.
There are counterparts to some of these in pdfbase/pdfdoc.py, but the latter focus on constructing the right PDF objects. These classes are declarative and focus on letting the user construct and query font objects.
The module maintains a registry of font objects at run time.
It is independent of the canvas or any particular context. It keeps a registry of Font, TypeFace and Encoding objects. Ideally these would be pre-loaded, but due to a nasty circularity problem we trap attempts to access them and do it on first access.
- class reportlab.pdfbase.pdfmetrics.EmbeddedType1Face(afmFileName, pfbFileName)
A Type 1 font other than one of the basic 14.
Its glyph data will be embedded in the PDF file.
- addObjects(doc)
Add whatever needed to PDF file, and return a FontDescriptor reference
- getFontFiles()
Info function, return list of the font files this depends on.
- class reportlab.pdfbase.pdfmetrics.Encoding(name, base=None)
Object to help you create and refer to encodings.
- freeze()
- getDifferences(otherEnc)
Return a compact list of the code points differing between two encodings
- This is in the Adobe format: list of
[[b1, name1, name2, name3], [b2, name4]]
where b1…bn is the starting code point, and the glyph names following are assigned consecutive code points.
- isEqual(other)
- makePDFObject()
Returns a PDF Object representing self
- modifyRange(base, newNames)
Set a group of character names starting at the code point ‘base’.
- class reportlab.pdfbase.pdfmetrics.Font(name, faceName, encName, substitutionFonts=None)
Represents a font (i.e combination of face and encoding).
Defines suitable machinery for single byte fonts. This is a concrete class which can handle the basic built-in fonts; not clear yet if embedded ones need a new font class or just a new typeface class (which would do the job through composition)
- addObjects(doc)
Makes and returns one or more PDF objects to be added to the document. The caller supplies the internal name to be used (typically F1, F2… in sequence)
- shapable = False
- stringWidth(text, size, encoding='utf8')
- exception reportlab.pdfbase.pdfmetrics.FontError
- exception reportlab.pdfbase.pdfmetrics.FontNotFoundError
- class reportlab.pdfbase.pdfmetrics.TypeFace(name)
- findT1File(ext='.pfb')
- getFontFiles()
Info function, return list of the font files this depends on.
- reportlab.pdfbase.pdfmetrics.bruteForceSearchForAFM(faceName)
Looks in all AFM files on path for face with given name.
Returns AFM file name or None. Ouch!
- reportlab.pdfbase.pdfmetrics.bruteForceSearchForFile(fn, searchPath=None)
- reportlab.pdfbase.pdfmetrics.dumpFontData()
- reportlab.pdfbase.pdfmetrics.findFontAndRegister(fontName)
search for and register a font given its name
- reportlab.pdfbase.pdfmetrics.getAscent(fontName, fontSize=None)
- reportlab.pdfbase.pdfmetrics.getAscentDescent(fontName, fontSize=None)
- reportlab.pdfbase.pdfmetrics.getDescent(fontName, fontSize=None)
- reportlab.pdfbase.pdfmetrics.getEncoding(encName)
Lazily construct known encodings if not found
- reportlab.pdfbase.pdfmetrics.getFont(fontName)
Lazily constructs known fonts if not found.
Names of form ‘face-encoding’ will be built if face and encoding are known. Also if the name is just one of the standard 14, it will make up a font in the default encoding.
- reportlab.pdfbase.pdfmetrics.getRegisteredFontNames()
Returns what’s in there
- reportlab.pdfbase.pdfmetrics.getTypeFace(faceName)
Lazily construct known typefaces if not found
- reportlab.pdfbase.pdfmetrics.parseAFMFile(afmFileName)
Quick and dirty - gives back a top-level dictionary with top-level items, and a ‘widths’ key containing a dictionary of glyph names and widths. Just enough needed for embedding. A better parser would accept options for what data you wwanted, and preserve the order.
- reportlab.pdfbase.pdfmetrics.registerEncoding(enc)
- reportlab.pdfbase.pdfmetrics.registerFont(font)
Registers a font, including setting up info for accelerated stringWidth
- reportlab.pdfbase.pdfmetrics.registerFontFamily(family, normal=None, bold=None, italic=None, boldItalic=None)
- reportlab.pdfbase.pdfmetrics.registerTypeFace(face)
- reportlab.pdfbase.pdfmetrics.stringWidth(text, fontName, fontSize, encoding='utf8')
Compute width of string in points; not accelerated as fast enough because of instanceStringWidthT1/TTF
- reportlab.pdfbase.pdfmetrics.test()
- reportlab.pdfbase.pdfmetrics.test3widths(texts)
- reportlab.pdfbase.pdfmetrics.testStringWidthAlgorithms()
reportlab.pdfbase.pdfpattern
helper for importing pdf structures into a ReportLab generated document
- class reportlab.pdfbase.pdfpattern.PDFPattern(pattern_sequence, **keywordargs)
- clone()
- eval(L)
- format(document)
- class reportlab.pdfbase.pdfpattern.PDFPatternIf(cond, thenPart=[], elsePart=[])
cond will be evaluated as [cond] in PDFpattern eval. It should evaluate to a list with value 0/1 etc etc. thenPart is a list to be evaluated if the cond evaulates true, elsePart is the false sequence.
reportlab.pdfbase.pdfutils
- reportlab.pdfbase.pdfutils.cacheImageFile(filename, returnInMemory=0, IMG=None)
Processes image as if for encoding, saves to a file with .a85 extension.
- reportlab.pdfbase.pdfutils.cachedImageExists(filename)
Determines if a cached image already exists for a given file.
Determines if a cached image exists which has the same name and equal or newer date to the given file.
- reportlab.pdfbase.pdfutils.makeA85Image(filename, IMG=None, detectJpeg=False)
- reportlab.pdfbase.pdfutils.makeRawImage(filename, IMG=None, detectJpeg=False)
- reportlab.pdfbase.pdfutils.preProcessImages(spec)
Preprocesses one or more image files.
Accepts either a filespec (‘C:mydir*.jpg’) or a list of image filenames, crunches them all to save time. Run this to save huge amounts of time when repeatedly building image documents.
- reportlab.pdfbase.pdfutils.readJPEGInfo(image)
Read width, height and number of components from open JPEG file.
reportlab.pdfbase.rl_codecs
reportlab.pdfbase.ttfonts
TrueType font support
This defines classes to represent TrueType fonts. They know how to calculate their own width and how to write themselves into PDF files. They support subsetting and embedding and can represent all 16-bit Unicode characters.
Note on dynamic fonts
Usually a Font in ReportLab corresponds to a fixed set of PDF objects (Font, FontDescriptor, Encoding). But with dynamic font subsetting a single TTFont will result in a number of Font/FontDescriptor/Encoding object sets, and the contents of those will depend on the actual characters used for printing.
To support dynamic font subsetting a concept of “dynamic font” was introduced. Dynamic Fonts have a _dynamicFont attribute set to 1.
Dynamic fonts have the following additional functions:
def splitString(self, text, doc):
'''Splits text into a number of chunks, each of which belongs to a
single subset. Returns a list of tuples (subset, string). Use
subset numbers with getSubsetInternalName. Doc is used to identify
a document so that different documents may have different dynamically
constructed subsets.'''
def getSubsetInternalName(self, subset, doc):
'''Returns the name of a PDF Font object corresponding to a given
subset of this dynamic font. Use this function instead of
PDFDocument.getInternalFontName.'''
You must never call PDFDocument.getInternalFontName for dynamic fonts.
If you have a traditional static font, mapping to PDF text output operators is simple:
'%s 14 Tf (%s) Tj' % (getInternalFontName(psfontname), text)
If you have a dynamic font, use this instead:
for subset, chunk in font.splitString(text, doc):
'%s 14 Tf (%s) Tj' % (font.getSubsetInternalName(subset, doc), chunk)
(Tf is a font setting operator and Tj is a text ouput operator. You should also escape invalid characters in Tj argument, see TextObject._formatText. Oh, and that 14 up there is font size.)
Canvas and TextObject have special support for dynamic fonts.
- class reportlab.pdfbase.ttfonts.CMapFmt2SubHeader(firstCode, entryCount, idDelta, idRangeOffset)
- entryCount
Alias for field number 1
- firstCode
Alias for field number 0
- idDelta
Alias for field number 2
- idRangeOffset
Alias for field number 3
- reportlab.pdfbase.ttfonts.SUBSETN(n, table=b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./ABCDEFGIJK:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff')
- class reportlab.pdfbase.ttfonts.ShapeData(cluster, x_advance, y_advance, x_offset, y_offset, width)
- class reportlab.pdfbase.ttfonts.ShapedFragWord(iterable=(), /)
list class to distinguish frag words that have been shaped
- class reportlab.pdfbase.ttfonts.ShapedStr(s, shapeData=None)
- class reportlab.pdfbase.ttfonts.TTEncoding
Encoding for TrueType fonts (always UTF-8).
TTEncoding does not directly participate in PDF object creation, since we need a number of different 8-bit encodings for every generated font subset. TTFont itself cares about that.
- exception reportlab.pdfbase.ttfonts.TTFError
TrueType font exception
- class reportlab.pdfbase.ttfonts.TTFNameBytes(b, enc='utf8')
class used to return named strings
- reportlab.pdfbase.ttfonts.TTFOpenFile(fn)
Opens a TTF file possibly after searching TTFSearchPath returns (filename,file)
- class reportlab.pdfbase.ttfonts.TTFont(name, filename, validate=0, subfontIndex=0, asciiReadable=None, shapable=True)
Represents a TrueType font.
Its encoding is always UTF-8.
Note: you cannot use the same TTFont object for different documents at the same time.
Example of usage:
font = ttfonts.TTFont(‘PostScriptFontName’, ‘/path/to/font.ttf’) pdfmetrics.registerFont(font)
canvas.setFont(‘PostScriptFontName’, size) canvas.drawString(x, y, “Some text encoded in UTF-8”)
- addObjects(doc)
Makes one or more PDF objects to be added to the document. The caller supplies the internal name to be used (typically F1, F2, … in sequence).
This method creates a number of Font and FontDescriptor objects. Every FontDescriptor is a (no more than) 256 character subset of the original TrueType font.
- getSubsetInternalName(subset, doc)
Returns the name of a PDF Font object corresponding to a given subset of this dynamic font. Use this function instead of PDFDocument.getInternalFontName.
- property hbFace
return uharbuzz.Face
- hbFont(fontSize=10)
return uharfbuzz Font
- pdfScale(v)
- property shapable
- splitString(text, doc, encoding='utf-8')
Splits text into a number of chunks, each of which belongs to a single subset. Returns a list of tuples (subset, string). Use subset numbers with getSubsetInternalName. Doc is needed for distinguishing subsets when building different documents at the same time.
- stringWidth(text, size, encoding='utf8')
- unregister()
- class reportlab.pdfbase.ttfonts.TTFontFace(filename, validate=0, subfontIndex=0)
TrueType typeface.
Conceptually similar to a single byte typeface, but the glyphs are identified by UCS character codes instead of glyph names.
- addSubsetObjects(doc, fontname, subset)
Generate a TrueType font subset and add it to the PDF document. Returns a PDFReference to the new FontDescriptor object.
- getCharWidth(code)
Returns the width of character U+<code>
- class reportlab.pdfbase.ttfonts.TTFontFile(file, charInfo=1, validate=0, subfontIndex=0)
TTF file parser and generator
- extractInfo(charInfo=1)
Extract typographic information from the loaded font file.
The following attributes will be set:
name PostScript font name flags Font flags ascent Typographic ascender in 1/1000ths of a point descent Typographic descender in 1/1000ths of a point capHeight Cap height in 1/1000ths of a point (0 if not available) bbox Glyph bounding box [l,t,r,b] in 1/1000ths of a point _bbox Glyph bounding box [l,t,r,b] in unitsPerEm unitsPerEm Glyph units per em italicAngle Italic angle in degrees ccw stemV stem weight in 1/1000ths of a point (approximate)
If charInfo is true, the following will also be set:
defaultWidth default glyph width in 1/1000ths of a point charWidths dictionary of character widths for every supported UCS character code
This will only work if the font has a Unicode cmap (platform 3, encoding 1, format 4 or platform 0 any encoding format 4). Setting charInfo to false avoids this requirement
- makeSubset(subset)
Create a subset of a TrueType font
- class reportlab.pdfbase.ttfonts.TTFontMaker
Basic TTF file generator
- add(tag, data)
Adds a table to the TTF file.
- makeStream()
Finishes the generation and returns the TTF file as a string
- class reportlab.pdfbase.ttfonts.TTFontParser(file, validate=0, subfontIndex=0)
Basic TTF file parser
- checksumFile()
- checksumTables()
- fileKind = 'TTF'
- getSubfont(subfontIndex)
- get_chunk(pos, length)
Return a chunk of raw data at given position
- get_table(tag)
Return the given TTF table
- get_table_pos(tag)
Returns the offset and size of a given TTF table.
- get_ulong(pos)
Return an unsigned long at given position
- get_ushort(pos)
Return an unsigned short at given position
- readFile(f)
- readHeader()
read the sfnt header at the current position
- readTTCHeader()
- readTableDirectory()
- read_short()
Reads a signed short
- read_tag()
Read a 4-character tag
- read_uint8()
- read_ulong()
Reads an unsigned long
- read_ushort()
Reads an unsigned short
- seek(pos)
Moves read pointer to a given offset in file.
- seek_table(tag, offset_in_table=0)
Moves read pointer to the given offset within a given table and returns absolute offset of that position in the file.
- skip(delta)
Skip the given number of bytes.
- ttcVersions = (65536, 131072)
- ttfVersions = (65536, 1953658213, 1953784678)
- reportlab.pdfbase.ttfonts.freshTTFont(ttfn, ttfpath, **kwds)
return a new instance corrsponding to a ttf path
- reportlab.pdfbase.ttfonts.makeShapedFragWord(w, K=[], V=[])
- reportlab.pdfbase.ttfonts.makeToUnicodeCMap(fontname, subset)
Creates a ToUnicode CMap for a given subset. See Adobe _PDF_Reference (ISBN 0-201-75839-3) for more information.
- reportlab.pdfbase.ttfonts.shapeFragWord(w, features=None)
- reportlab.pdfbase.ttfonts.shapeStr(s, fontName, fontSize)
- reportlab.pdfbase.ttfonts.splice(stream, offset, value)
Splices the given value into stream at the given offset and returns the resulting stream (the original is unchanged)
reportlab.pdfgen
Defines a high-level Canvas interface for creating PDF files
reportlab.pdfgen.canvas
The Canvas object is the primary interface for creating PDF files. See doc/reportlab-userguide.pdf for copious examples.
- class reportlab.pdfgen.canvas.Canvas(filename, pagesize=None, bottomup=1, pageCompression=None, invariant=None, verbosity=0, encrypt=None, cropMarks=None, pdfVersion=None, enforceColorSpace=None, initialFontName=None, initialFontSize=None, initialLeading=None, cropBox=None, artBox=None, trimBox=None, bleedBox=None, lang=None, **kwds)
This class is the programmer’s interface to the PDF file format. Methods are (or will be) provided here to do just about everything PDF can do.
The underlying model to the canvas concept is that of a graphics state machine that at any given point in time has a current font, fill color (for figure interiors), stroke color (for figure borders), line width and geometric transform, among many other characteristics.
Canvas methods generally either draw something (like canvas.line) using the current state of the canvas or change some component of the canvas state (like canvas.setFont). The current state can be saved and restored using the saveState/restoreState methods.
Objects are “painted” in the order they are drawn so if, for example two rectangles overlap the last draw will appear “on top”. PDF form objects (supported here) are used to draw complex drawings only once, for possible repeated use.
There are other features of canvas which are not visible when printed, such as outlines and bookmarks which are used for navigating a document in a viewer.
Here is a very silly example usage which generates a Hello World pdf document.
Example:
from reportlab.pdfgen import canvas c = canvas.Canvas("hello.pdf") from reportlab.lib.units import inch # move the origin up and to the left c.translate(inch,inch) # define a large font c.setFont("Helvetica", 80) # choose some colors c.setStrokeColorRGB(0.2,0.5,0.3) c.setFillColorRGB(1,0,1) # draw a rectangle c.rect(inch,inch,6*inch,9*inch, fill=1) # make text go straight up c.rotate(90) # change color c.setFillColorRGB(0,0,0.77) # say hello (note after rotate the y coord needs to be negative!) c.drawString(3*inch, -3*inch, "Hello World") c.showPage() c.save()
- STATE_ATTRIBUTES = ['_x', '_y', '_fontname', '_fontsize', '_textMode', '_leading', '_currentMatrix', '_fillMode', '_charSpace', '_wordSpace', '_horizScale', '_textRenderMode', '_rise', '_textLineMatrix', '_textMatrix', '_lineCap', '_lineJoin', '_lineDash', '_lineWidth', '_mitreLimit', '_fillColorObj', '_strokeColorObj', '_extgstate']
- STATE_RANGE = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
- absolutePosition(x, y)
return the absolute position of x,y in user space w.r.t. default user space
- property acroForm
get form from canvas, create the form if needed
- addLiteral(s, escaped=1)
introduce the literal text of PDF operations s into the current stream. Only use this if you are an expert in the PDF file format.
- addOutlineEntry(title, key, level=0, closed=None)
Adds a new entry to the outline at given level. If LEVEL not specified, entry goes at the top level. If level specified, it must be no more than 1 greater than the outline level in the last call.
The key must be the (unique) name of a bookmark. the title is the (non-unique) name to be displayed for the entry.
If closed is set then the entry should show no subsections by default when displayed.
Example:
c.addOutlineEntry("first section", "section1") c.addOutlineEntry("introduction", "s1s1", 1, closed=1) c.addOutlineEntry("body", "s1s2", 1) c.addOutlineEntry("detail1", "s1s2s1", 2) c.addOutlineEntry("detail2", "s1s2s2", 2) c.addOutlineEntry("conclusion", "s1s3", 1) c.addOutlineEntry("further reading", "s1s3s1", 2) c.addOutlineEntry("second section", "section1") c.addOutlineEntry("introduction", "s2s1", 1) c.addOutlineEntry("body", "s2s2", 1, closed=1) c.addOutlineEntry("detail1", "s2s2s1", 2) c.addOutlineEntry("detail2", "s2s2s2", 2) c.addOutlineEntry("conclusion", "s2s3", 1) c.addOutlineEntry("further reading", "s2s3s1", 2)
generated outline looks like:
- first section |- introduction |- body | |- detail1 | |- detail2 |- conclusion | |- further reading - second section |- introduction |+ body |- conclusion | |- further reading
Note that the second “body” is closed.
Note that you can jump from level 5 to level 3 but not from 3 to 5: instead you need to provide all intervening levels going down (4 in this case). Note that titles can collide but keys cannot.
- addPageLabel(pageNum, style=None, start=None, prefix=None)
add a PDFPageLabel for pageNum
- addPostScriptCommand(command, position=1)
Embed literal Postscript in the document.
With position=0, it goes at very beginning of page stream; with position=1, at current point; and with position=2, at very end of page stream. What that does to the resulting Postscript depends on Adobe’s header :-)
Use with extreme caution, but sometimes needed for printer tray commands. Acrobat 4.0 will export Postscript to a printer or file containing the given commands. Adobe Reader 6.0 no longer does as this feature is deprecated. 5.0, I don’t know about (please let us know!). This was funded by Bob Marshall of Vector.co.uk and tested on a Lexmark 750. See test_pdfbase_postscript.py for 2 test cases - one will work on any Postscript device, the other uses a ‘setpapertray’ command which will error in Distiller but work on printers supporting it.
- arc(x1, y1, x2, y2, startAng=0, extent=90)
Draw a partial ellipse inscribed within the rectangle x1,y1,x2,y2, starting at startAng degrees and covering extent degrees. Angles start with 0 to the right (+x) and increase counter-clockwise. These should have x1<x2 and y1<y2.
- beginForm(name, lowerx=0, lowery=0, upperx=None, uppery=None)
declare the current graphics stream to be a named form. A graphics stream can either be a page or a form, not both. Some operations (like bookmarking) are permitted for pages but not forms. The form will not automatically be shown in the document but must be explicitly referenced using doForm in pages that require the form.
- beginPath()
Returns a fresh path object. Paths are used to draw complex figures. The object returned follows the protocol for a pathobject.PDFPathObject instance
- beginText(x=0, y=0, direction=None)
Returns a fresh text object. Text objects are used to add large amounts of text. See PDFTextObject
- bezier(x1, y1, x2, y2, x3, y3, x4, y4)
Bezier curve with the four given control points
- bookmarkHorizontal(key, relativeX, relativeY, **kw)
w.r.t. the current transformation, bookmark this horizontal.
- bookmarkHorizontalAbsolute(key, top, left=0, fit='XYZ', **kw)
Bind a bookmark (destination) to the current page at a horizontal position. Note that the yhorizontal of the book mark is with respect to the default user space (where the origin is at the lower left corner of the page) and completely ignores any transform (translation, scale, skew, rotation, etcetera) in effect for the current graphics state. The programmer is responsible for making sure the bookmark matches an appropriate item on the page.
- bookmarkPage(key, fit='Fit', left=None, top=None, bottom=None, right=None, zoom=None)
This creates a bookmark to the current page which can be referred to with the given key elsewhere.
PDF offers very fine grained control over how Acrobat reader is zoomed when people link to this. The default is to keep the user’s current zoom settings. the last arguments may or may not be needed depending on the choice of ‘fitType’.
Fit types and the other arguments they use are:
XYZ left top zoom - fine grained control. null or zero for any of the parameters means ‘leave as is’, so “0,0,0” will keep the reader’s settings. NB. Adobe Reader appears to prefer “null” to 0’s.
Fit - entire page fits in window
FitH top - top coord at top of window, width scaled to fit.
FitV left - left coord at left of window, height scaled to fit
FitR left bottom right top - scale window to fit the specified rectangle
(question: do we support /FitB, FitBH and /FitBV which are hangovers from version 1.1 / Acrobat 3.0?)
- circle(x_cen, y_cen, r, stroke=1, fill=0)
draw a cirle centered at (x_cen,y_cen) with radius r (special case of ellipse)
- clipPath(aPath, stroke=1, fill=0, fillMode=None)
clip as well as drawing
- cross(x, y, size=5, gap=1, text=None, strokeColor=None, strokeWidth=None, fontSize=3)
- delCatalogEntry(key)
you’ll get an error here if it’s not been set
- delViewerPreference(pref)
you’ll get an error here if none have been set
- doForm(name)
use a form XObj in current operation stream.
The form should either have been defined previously using beginForm … endForm, or may be defined later. If it is not defined at save time, an exception will be raised. The form will be drawn within the context of the current graphics state.
- drawAlignedString(x, y, text, pivotChar='.', mode=None, charSpace=0, direction=None, wordSpace=None, shaping=False)
Draws a string aligned on the first ‘.’ (or other pivot character).
The centre position of the pivot character will be used as x. So, you could draw a straight line down through all the decimals in a column of numbers, and anything without a decimal should be optically aligned with those that have.
There is one special rule to help with accounting formatting. Here’s how normal numbers should be aligned on the ‘dot’. Look at the LAST two:
12,345,67 987.15 42 -1,234.56 (456.78) (456) 27 inches 13cm
Since the last three do not contain a dot, a crude dot-finding rule would place them wrong. So we test for the special case where no pivot is found, digits are present, but the last character is not a digit. We then work back from the end of the string This case is a tad slower but hopefully rare.
- drawBoundary(sb, x1, y1, width, height)
draw a boundary as a rectangle (primarily for debugging).
- drawCentredString(x, y, text, mode=None, charSpace=0, direction=None, wordSpace=None, shaping=False)
Draws a string centred on the x coordinate.
We’re British, dammit, and proud of our spelling!
- drawImage(image, x, y, width=None, height=None, mask=None, preserveAspectRatio=False, anchor='c', anchorAtXY=False, showBoundary=False, extraReturn=None)
Draws the image (ImageReader object or filename) as specified.
“image” may be an image filename or an ImageReader object.
x and y define the lower left corner of the image you wish to draw (or of its bounding box, if using preserveAspectRation below).
If width and height are not given, the width and height of the image in pixels is used at a scale of 1 point to 1 pixel.
If width and height are given, the image will be stretched to fill the given rectangle bounded by (x, y, x+width, y-height).
If you supply negative widths and/or heights, it inverts them and adjusts x and y accordingly.
The method returns the width and height of the underlying image, since this is often useful for layout algorithms and saves you work if you have not specified them yourself.
The mask parameter supports transparent backgrounds. It takes 6 numbers and defines the range of RGB values which will be masked out or treated as transparent. For example with [0,2,40,42,136,139], it will mask out any pixels with a Red value from 0-2, Green from 40-42 and Blue from 136-139 (on a scale of 0-255).
New post version 2.0: drawImage can center an image in a box you provide, while preserving its aspect ratio. For example, you might have a fixed square box in your design, and a collection of photos which might be landscape or portrait that you want to appear within the box. If preserveAspectRatio is true, your image will appear within the box specified.
If preserveAspectRatio is True, the anchor property can be used to specify how images should fit into the given box. It should be set to one of the following values, taken from the points of the compass (plus ‘c’ for ‘centre’):
nw n ne w c e sw s se
The default value is ‘c’ for ‘centre’. Thus, if you want your bitmaps to always be centred and appear at the top of the given box, set anchor=’n’. There are good examples of this in the output of test_pdfgen_general.py
Unlike drawInlineImage, this creates ‘external images’ which are only stored once in the PDF file but can be drawn many times. If you give it the same filename twice, even at different locations and sizes, it will reuse the first occurrence, resulting in a saving in file size and generation time. If you use ImageReader objects, it tests whether the image content has changed before deciding whether to reuse it.
In general you should use drawImage in preference to drawInlineImage unless you have read the PDF Spec and understand the tradeoffs.
- drawInlineImage(image, x, y, width=None, height=None, preserveAspectRatio=False, anchor='c', anchorAtXY=False, showBoundary=False, extraReturn=None)
See drawImage, which should normally be used instead…
drawInlineImage behaves like drawImage, but stores the image content within the graphics stream for the page. This means that the mask parameter for transparency is not available. It also means that there is no saving in file size or time if the same image is reused.
In theory it allows images to be displayed slightly faster; however, we doubt if the difference is noticeable to any human user these days. Only use this if you have studied the PDF specification and know the implications.
- drawPath(aPath, stroke=1, fill=0, fillMode=None)
Draw the path object in the mode indicated
- drawRightString(x, y, text, mode=None, charSpace=0, direction=None, wordSpace=None, shaping=False)
Draws a string right-aligned with the x coordinate
- drawString(x, y, text, mode=None, charSpace=0, direction=None, wordSpace=None, shaping=False)
Draws a string in the current text styles.
- drawText(aTextObject)
Draws a text object
- ellipse(x1, y1, x2, y2, stroke=1, fill=0)
Draw an ellipse defined by an enclosing rectangle.
Note that (x1,y1) and (x2,y2) are the corner points of the enclosing rectangle.
- endForm(**extra_attributes)
emit the current collection of graphics operations as a Form as declared previously in beginForm.
- freeTextAnnotation(contents, DA, Rect=None, addtopage=1, name=None, relative=0, **kw)
DA is the default appearance string???
- getAvailableFonts()
Returns the list of PostScript font names available.
Standard set now, but may grow in future with font embedding.
- getCatalogEntry(key)
- getCurrentPageContent()
Return uncompressed contents of current page buffer.
This is useful in creating test cases and assertions of what got drawn, without necessarily saving pages to disk
- getPageNumber()
get the page number for the current page being generated.
- getViewerPreference(pref)
you’ll get an error here if none have been set
- getpdfdata()
Returns the PDF data that would normally be written to a file. If there is current data a ShowPage is executed automatically. After this operation the canvas must not be used further.
- grid(xlist, ylist)
Lays out a grid in current line style. Supply list of x an y positions.
- hasForm(name)
Query whether form XObj really exists yet.
- highlightAnnotation(contents, Rect, QuadPoints=None, Color=[0.83, 0.89, 0.95], addtopage=1, name=None, relative=0, **kw)
Allows adding of a highlighted annotation.
Rect: Mouseover area to show contents of annotation QuadPoints: List of four x/y points [TOP-LEFT, TOP-RIGHT, BOTTOM-LEFT, BOTTOM-RIGHT]
These points outline the areas to highlight. You can have multiple groups of four to allow multiple highlighted areas. Is in the format [x1, y1, x2, y2, x3, y3, x4, y4, x1, y1, x2, y2, x3, y3, x4, y4] etc QuadPoints defaults to be area inside of passed in Rect
Color: The color of the highlighting.
- init_graphics_state()
- inkAnnotation(contents, InkList=None, Rect=None, addtopage=1, name=None, relative=0, **kw)
- inkAnnotation0(contents, InkList=None, Rect=None, addtopage=1, name=None, relative=0, **kw)
- line(x1, y1, x2, y2)
draw a line segment from (x1,y1) to (x2,y2) (with color, thickness and other attributes determined by the current graphics state).
- linearGradient(x0, y0, x1, y1, colors, positions=None, extend=True)
- lines(linelist)
Like line(), permits many lines to be drawn in one call. for example for the figure:
| -- -- | crosshairs = [(20,0,20,10), (20,30,20,40), (0,20,10,20), (30,20,40,20)] canvas.lines(crosshairs)
- linkAbsolute(contents, destinationname, Rect=None, addtopage=1, name=None, thickness=0, color=None, dashArray=None, **kw)
rectangular link annotation positioned wrt the default user space. The identified rectangle on the page becomes a “hot link” which when clicked will send the viewer to the page and position identified by the destination.
Rect identifies (lowerx, lowery, upperx, uppery) for lower left and upperright points of the rectangle. Translations and other transforms are IGNORED (the rectangular position is given with respect to the default user space. destinationname should be the name of a bookmark (which may be defined later but must be defined before the document is generated).
You may want to use the keyword argument Border=’[0 0 0]’ to suppress the visible rectangle around the during viewing link.
- linkRect(contents, destinationname, Rect=None, addtopage=1, name=None, relative=1, thickness=0, color=None, dashArray=None, **kw)
rectangular link annotation w.r.t the current user transform. if the transform is skewed/rotated the absolute rectangle will use the max/min x/y
- linkURL(url, rect, relative=0, thickness=0, color=None, dashArray=None, kind='URI', **kw)
Create a rectangular URL ‘hotspot’ in the given rectangle.
if relative=1, this is in the current coord system, otherwise in absolute page space. The remaining options affect the border appearance; the border is drawn by Acrobat, not us. Set thickness to zero to hide it. Any border drawn this way is NOT part of the page stream and will not show when printed to a Postscript printer or distilled; it is safest to draw your own.
- listLoadedFonts0()
Convenience function to list all loaded fonts
- pageHasData()
Info function - app can call it after showPage to see if it needs a save
- pop_state_stack()
- push_state_stack()
- radialGradient(x, y, radius, colors, positions=None, extend=True)
- rect(x, y, width, height, stroke=1, fill=0)
draws a rectangle with lower left corner at (x,y) and width and height as given.
- resetTransforms()
I want to draw something (eg, string underlines) w.r.t. the default user space. Reset the matrix! This should be used usually as follows:
canv.saveState() canv.resetTransforms() #...draw some stuff in default space coords... canv.restoreState() # go back!
- restoreState()
restore the graphics state to the matching saved state (see saveState).
- rotate(theta)
Rotate the canvas by the angle theta (in degrees).
- roundRect(x, y, width, height, radius, stroke=1, fill=0)
Draws a rectangle with rounded corners. The corners are approximately quadrants of a circle, with the given radius.
- save()
Saves and close the PDF document in the file. If there is current data a ShowPage is executed automatically. After this operation the canvas must not be used further.
- saveState()
Save the current graphics state to be restored later by restoreState.
- For example:
canvas.setFont(“Helvetica”, 20) canvas.saveState() … canvas.setFont(“Courier”, 9) … canvas.restoreState() # if the save/restore pairs match then font is Helvetica 20 again.
- scale(x, y)
Scale the horizontal dimension by x and the vertical by y (with respect to the current graphics state). For example canvas.scale(2.0, 0.5) will make everything short and fat.
- setArtBox(size)
- setAuthor(author)
identify the author for invisible embedding inside the PDF document. the author annotation will appear in the the text of the file but will not automatically be seen when the document is viewed, but is visible in document properties etc etc.
- setBleedBox(size)
- setBlendMode(v)
- setCatalogEntry(key, value)
- setCreator(creator)
write a creator into the PDF file that won’t automatically display in the document itself. This should be used to name the original app which is passing data into ReportLab, if you wish to name it.
- setCropBox(size, name='crop')
accepts a 2-tuple in points for name+’Box’ size for this and subsequent pages
- setDash(array=[], phase=0)
Two notations. pass two numbers, or an array and phase
- setDateFormatter(dateFormatter)
accepts a func(yyyy,mm,dd,hh,m,s) used to create embedded formatted date
- setEncrypt(encrypt)
Set the encryption used for the pdf generated by this canvas. If encrypt is a string object, it is used as the user password for the pdf. If encrypt is an instance of reportlab.lib.pdfencrypt.StandardEncryption, this object is used to encrypt the pdf. This allows more finegrained control over the encryption settings.
- setFont(psfontname, size, leading=None)
Sets the font. If leading not specified, defaults to 1.2 x font size. Raises a readable exception if an illegal font is supplied. Font names are case-sensitive! Keeps track of font name and size for metrics.
- setFontSize(size=None, leading=None)
Sets font size or leading without knowing the font face
- setKeywords(keywords)
write a list of keywords into the PDF file which shows in document properties. Either submit a single string or a list/tuple
- setLineCap(mode)
0=butt,1=round,2=square
- setLineJoin(mode)
0=mitre, 1=round, 2=bevel
- setLineWidth(width)
- setMiterLimit(limit)
- setOutlineNames0(*nametree)
nametree should can be a recursive tree like so:
c.setOutlineNames( "chapter1dest", ("chapter2dest", ["chapter2section1dest", "chapter2section2dest", "chapter2conclusiondest"] ), # end of chapter2 description "chapter3dest", ("chapter4dest", ["c4s1", "c4s2"]) )
each of the string names inside must be bound to a bookmark before the document is generated.
- setPageCallBack(func)
func(pageNum) will be called on each page end.
- This is mainly a hook for progress monitoring.
Call setPageCallback(None) to clear a callback.
- setPageCompression(pageCompression=1)
Possible values None, 1 or 0 If None the value from rl_config will be used. If on, the page data will be compressed, leading to much smaller files, but takes a little longer to create the files. This applies to all subsequent pages, or until setPageCompression() is next called.
- setPageDuration(duration=None)
Allows hands-off animation of presentations :-)
If this is set to a number, in full screen mode, Acrobat Reader will advance to the next page after this many seconds. The duration of the transition itself (fade/flicker etc.) is controlled by the ‘duration’ argument to setPageTransition; this controls the time spent looking at the page. This is effective for all subsequent pages.
- setPageRotation(rot)
Instruct display device that this page is to be rotated
- setPageSize(size)
accepts a 2-tuple in points for paper size for this and subsequent pages
- setPageTransition(effectname=None, duration=1, direction=0, dimension='H', motion='I')
PDF allows page transition effects for use when giving presentations. There are six possible effects. You can just guive the effect name, or supply more advanced options to refine the way it works. There are three types of extra argument permitted, and here are the allowed values:
direction_arg = [0,90,180,270] dimension_arg = ['H', 'V'] motion_arg = ['I','O'] (start at inside or outside)
This table says which ones take which arguments:
PageTransitionEffects = { 'Split': [direction_arg, motion_arg], 'Blinds': [dimension_arg], 'Box': [motion_arg], 'Wipe' : [direction_arg], 'Dissolve' : [], 'Glitter':[direction_arg] }
Have fun!
- setProducer(producer)
change the default producer value
- setSubject(subject)
write a subject into the PDF file that won’t automatically display in the document itself.
- setTitle(title)
write a title into the PDF file that won’t automatically display in the document itself.
- setTrimBox(size)
- setViewerPreference(pref, value)
set one of the allowed enbtries in the documents viewer preferences
- shade(shading)
- showFullScreen0()
Specify that Acrobat Reader should start in full screen mode. showFullScreen() and showOutline() conflict; the one called last wins.
- showOutline()
Specify that Acrobat Reader should start with the outline tree visible. showFullScreen() and showOutline() conflict; the one called last wins.
- showPage()
Close the current page and possibly start on a new page.
- skew(alpha, beta)
- stringWidth(text, fontName=None, fontSize=None)
gets width of a string in the given font and size
- textAnnotation(contents, Rect=None, addtopage=1, name=None, relative=0, **kw)
Experimental, but works.
- textAnnotation0(contents, Rect=None, addtopage=1, name=None, relative=0, **kw)
Experimental, but works.
- transform(a, b, c, d, e, f)
adjoin a mathematical transform to the current graphics state matrix. Not recommended for beginners.
- translate(dx, dy)
move the origin from the current (0,0) point to the (dx,dy) point (with respect to the current graphics state).
- wedge(x1, y1, x2, y2, startAng, extent, stroke=1, fill=0)
Like arc, but connects to the centre of the ellipse. Most useful for pie charts and PacMan!
- class reportlab.pdfgen.canvas.ShowBoundaryValue(color=(0, 0, 0), width=0.1, dashArray=None)
reportlab.pdfgen.pathobject
PDFPathObject is an efficient way to draw paths on a Canvas. Do not instantiate directly, obtain one from the Canvas instead.
Progress Reports: 8.83, 2000-01-13, gmcm: created from pdfgen.py
- class reportlab.pdfgen.pathobject.PDFPathObject(code=None)
Represents a graphic path. There are certain ‘modes’ to PDF drawing, and making a separate object to expose Path operations ensures they are completed with no run-time overhead. Ask the Canvas for a PDFPath with getNewPathObject(); moveto/lineto/ curveto wherever you want; add whole shapes; and then add it back into the canvas with one of the relevant operators.
Path objects are probably not long, so we pack onto one line
the code argument allows a canvas to get the operations appended directly so avoiding the final getCode
- arc(x1, y1, x2, y2, startAng=0, extent=90)
Contributed to piddlePDF by Robert Kern, 28/7/99. Draw a partial ellipse inscribed within the rectangle x1,y1,x2,y2, starting at startAng degrees and covering extent degrees. Angles start with 0 to the right (+x) and increase counter-clockwise. These should have x1<x2 and y1<y2.
The algorithm is an elliptical generalization of the formulae in Jim Fitzsimmon’s TeX tutorial <URL: http://www.tinaja.com/bezarc1.pdf>.
- arcTo(x1, y1, x2, y2, startAng=0, extent=90)
Like arc, but draws a line from the current point to the start if the start is not the current point.
- circle(x_cen, y_cen, r)
adds a circle to the path
- close()
draws a line back to where it started
- curveTo(x1, y1, x2, y2, x3, y3)
- ellipse(x, y, width, height)
adds an ellipse to the path
- getCode()
pack onto one line; used internally
- lineTo(x, y)
- moveTo(x, y)
- rect(x, y, width, height)
Adds a rectangle to the path
- roundRect(x, y, width, height, radius)
Draws a rectangle with rounded corners. The corners are approximately quadrants of a circle, with the given radius.
reportlab.pdfgen.pdfgeom
This module includes any mathematical methods needed for PIDDLE. It should have no dependencies beyond the Python library.
So far, just Robert Kern’s bezierArc.
- reportlab.pdfgen.pdfgeom.bezierArc(x1, y1, x2, y2, startAng=0, extent=90)
bezierArc(x1,y1, x2,y2, startAng=0, extent=90) –> List of Bezier curve control points.
(x1, y1) and (x2, y2) are the corners of the enclosing rectangle. The coordinate system has coordinates that increase to the right and down. Angles, measured in degress, start with 0 to the right (the positive X axis) and increase counter-clockwise. The arc extends from startAng to startAng+extent. I.e. startAng=0 and extent=180 yields an openside-down semi-circle.
The resulting coordinates are of the form (x1,y1, x2,y2, x3,y3, x4,y4) such that the curve goes from (x1, y1) to (x4, y4) with (x2, y2) and (x3, y3) as their respective Bezier control points.
reportlab.pdfgen.pdfimages
Image functionality sliced out of canvas.py for generalization
- class reportlab.pdfgen.pdfimages.PDFImage(image, x, y, width=None, height=None, caching=0)
Wrapper around different “image sources”. You can make images from a PIL Image object, a filename (in which case it uses PIL), an image we previously cached (optimisation, hardly used these days) or a JPEG (which PDF supports natively).
- PIL_imagedata()
- cache_imagedata()
- drawInlineImage(canvas, preserveAspectRatio=False, anchor='sw', anchorAtXY=False, showBoundary=False, extraReturn=None)
Draw an Image into the specified rectangle. If width and height are omitted, they are calculated from the image size. Also allow file names as well as images. This allows a caching mechanism
- format(document)
Allow it to be used within pdfdoc framework. This only defines how it is stored, not how it is drawn later.
- getImageData(preserveAspectRatio=False)
Gets data, height, width - whatever type of image
- jpg_imagedata()
- non_jpg_imagedata(image)
reportlab.pdfgen.textobject
PDFTextObject is an efficient way to add text to a Canvas. Do not instantiate directly, obtain one from the Canvas instead.
Progress Reports: 8.83, 2000-01-13, gmcm: created from pdfgen.py
- reportlab.pdfgen.textobject.BidiIndex(*args, **kwds)
- class reportlab.pdfgen.textobject.PDFTextObject(canvas, x=0, y=0, direction=None)
PDF logically separates text and graphics drawing; text operations need to be bracketed between BT (Begin text) and ET operators. This class ensures text operations are properly encapusalted. Ask the canvas for a text object with beginText(x, y). Do not construct one directly. Do not use multiple text objects in parallel; PDF is not multi-threaded!
It keeps track of x and y coordinates relative to its origin.
- getCode()
pack onto one line; used internally
- getCursor()
Returns current text position relative to the last origin.
- getStartOfLine()
Returns a tuple giving the text position of the start of the current line.
- getX()
Returns current x position relative to the last origin.
- getY()
Returns current y position relative to the last origin.
- moveCursor(dx, dy)
Starts a new line at an offset dx,dy from the start of the current line. This does not move the cursor relative to the current position, and it changes the current offset of every future line drawn (i.e. if you next do a textLine() call, it will move the cursor to a position one line lower than the position specificied in this call.
- setCharSpace(charSpace)
Adjusts inter-character spacing
- setFont(psfontname, size, leading=None)
Sets the font. If leading not specified, defaults to 1.2 x font size. Raises a readable exception if an illegal font is supplied. Font names are case-sensitive! Keeps track of font anme and size for metrics.
- setHorizScale(horizScale)
Stretches text out horizontally
- setLeading(leading)
How far to move down at the end of a line.
- setRise(rise)
Move text baseline up or down to allow superscript/subscripts
- setTextOrigin(x, y)
- setTextRenderMode(mode)
Set the text rendering mode.
0 = Fill text 1 = Stroke text 2 = Fill then stroke 3 = Invisible 4 = Fill text and add to clipping path 5 = Stroke text and add to clipping path 6 = Fill then stroke and add to clipping path 7 = Add to clipping path
after we start clipping we mustn’t change the mode back until after the ET
- setTextTransform(a, b, c, d, e, f)
Like setTextOrigin, but does rotation, scaling etc.
- setWordSpace(wordSpace)
Adjust inter-word spacing. This can be used to flush-justify text - you get the width of the words, and add some space between them.
- setXPos(dx)
Starts a new line dx away from the start of the current line - NOT from the current point! So if you call it in mid-sentence, watch out.
- textLine(text='')
prints string at current point, text cursor moves down. Can work with no argument to simply move the cursor down.
- textLines(stuff, trim=1)
prints multi-line or newlined strings, moving down. One comon use is to quote a multi-line block in your Python code; since this may be indented, by default it trims whitespace off each line and from the beginning; set trim=0 to preserve whitespace.
- textOut(text)
prints string at current point, text cursor moves across.
- reportlab.pdfgen.textobject.bidiFragWord(*args, **kwds)
- reportlab.pdfgen.textobject.bidiListWrap(*args, **kwds)
- reportlab.pdfgen.textobject.bidiShapedText(text, direction='RTL', clean=True, fontName='Helvetica', fontSize=10, shaping=False)
- reportlab.pdfgen.textobject.bidiStrWrap(*args, **kwds)
- reportlab.pdfgen.textobject.bidiText(*args, **kwds)
- reportlab.pdfgen.textobject.bidiWordList(*args, **kwds)
- reportlab.pdfgen.textobject.innerBidiStrWrap(*args, **kwds)
- reportlab.pdfgen.textobject.isBidiList(_)
- reportlab.pdfgen.textobject.isBidiStr(_)
- reportlab.pdfgen.textobject.log2vis(*args, **kwds)
reportlab.platypus
Page Layout and Typography Using Scripts” - higher-level framework for flowing documents
reportlab.platypus.doctemplate
This module contains the core structure of platypus.
rlatypus constructs documents. Document styles are determined by DocumentTemplates.
Each DocumentTemplate contains one or more PageTemplates which defines the look of the pages of the document.
Each PageTemplate has a procedure for drawing the “non-flowing” part of the page (for example the header, footer, page number, fixed logo graphic, watermark, etcetera) and a set of Frames which enclose the flowing part of the page (for example the paragraphs, tables, or non-fixed diagrams of the text).
A document is built when a DocumentTemplate is fed a sequence of Flowables. The action of the build consumes the flowables in order and places them onto frames on pages as space allows. When a frame runs out of space the next frame of the page is used. If no frame remains a new page is created. A new page can also be created if a page break is forced.
The special invisible flowable NextPageTemplate can be used to specify the page template for the next page (which by default is the one being used for the current frame).
- class reportlab.platypus.doctemplate.ActionFlowable(action=())
This Flowable is never drawn, it can be used for data driven controls For example to change a page template (from one column to two, for example) use NextPageTemplate which creates an ActionFlowable.
- apply(doc)
This is called by the doc.build processing to allow the instance to implement its behaviour
- identity(maxLen=None)
This method should attempt to return a string that can be used to identify a particular flowable uniquely. The result can then be used for debugging and or error printouts
- class reportlab.platypus.doctemplate.BaseDocTemplate(filename, **kw)
First attempt at defining a document template class.
The basic idea is simple.
The document has a list of data associated with it this data should derive from flowables. We’ll have special classes like PageBreak, FrameBreak to do things like forcing a page end etc.
The document has one or more page templates.
Each page template has one or more frames.
The document class provides base methods for handling the story events and some reasonable methods for getting the story flowables into the frames.
The document instances can override the base handler routines.
Most of the methods for this class are not called directly by the user, but in some advanced usages they may need to be overridden via subclassing.
EXCEPTION: doctemplate.build(…) must be called for most reasonable uses since it builds a document using the page template.
Each document template builds exactly one document into a file specified by the filename argument on initialization.
Possible keyword arguments for the initialization:
pageTemplates: A list of templates. Must be nonempty. Names assigned to the templates are used for referring to them so no two used templates should have the same name. For example you might want one template for a title page, one for a section first page, one for a first page of a chapter and two more for the interior of a chapter on odd and even pages. If this argument is omitted then at least one pageTemplate should be provided using the addPageTemplates method before the document is built.
pageSize: a 2-tuple or a size constant from reportlab/lib/pagesizes.pu. Used by the SimpleDocTemplate subclass which does NOT accept a list of pageTemplates but makes one for you; ignored when using pageTemplates.
showBoundary: if set draw a box around the frame boundaries.
leftMargin:
rightMargin:
topMargin:
bottomMargin: Margin sizes in points (default 1 inch). These margins may be overridden by the pageTemplates. They are primarily of interest for the SimpleDocumentTemplate subclass.
allowSplitting: If set flowables (eg, paragraphs) may be split across frames or pages (default: 1)
title: Internal title for document (does not automatically display on any page)
author: Internal author for document (does not automatically display on any page)
- addPageTemplates(pageTemplates)
add one or a sequence of pageTemplates
- afterFlowable(flowable)
called after a flowable has been rendered
- afterInit()
This is called after initialisation of the base class.
- afterPage()
This is called after page processing, and immediately after the afterDrawPage method of the current page template.
- beforeDocument()
This is called before any processing is done on the document.
- beforePage()
This is called at the beginning of page processing, and immediately before the beforeDrawPage method of the current page template.
- build(flowables, filename=None, canvasmaker=<class 'reportlab.pdfgen.canvas.Canvas'>)
Build the document from a list of flowables. If the filename argument is provided then that filename is used rather than the one provided upon initialization. If the canvasmaker argument is provided then it will be used instead of the default. For example a slideshow might use an alternate canvas which places 6 slides on a page (by doing translations, scalings and redefining the page break operations).
- clean_hanging()
handle internal postponed actions
- docAssign(var, expr, lifetime)
- docEval(expr)
- docExec(stmt, lifetime)
- filterFlowables(flowables)
called to filter flowables at the start of the main handle_flowable method. Upon return if flowables[0] has been set to None it is discarded and the main method returns.
- handle_breakBefore(flowables)
preprocessing step to allow pageBreakBefore and frameBreakBefore attributes
- handle_currentFrame(fx, resume=0)
change to the frame with name or index fx
- handle_documentBegin()
implement actions at beginning of document
- handle_flowable(flowables)
try to handle one flowable from the front of list flowables.
- handle_frameBegin(resume=0, pageTopFlowables=None)
What to do at the beginning of a frame
- handle_frameEnd(resume=0)
Handles the semantics of the end of a frame. This includes the selection of the next frame or if this is the last frame then invoke pageEnd.
- handle_keepWithNext(flowables)
implements keepWithNext
- handle_nextFrame(fx, resume=0)
On endFrame change to the frame with name or index fx
- handle_nextPageTemplate(pt)
On endPage change to the page template with name or index pt
- handle_pageBegin()
Perform actions required at beginning of page. shouldn’t normally be called directly
- handle_pageBreak(slow=None)
some might choose not to end all the frames
- handle_pageEnd()
show the current page check the next page template hang a page begin
- multiBuild(story, maxPasses=10, **buildKwds)
Makes multiple passes until all indexing flowables are happy.
Returns number of passes
- notify(kind, stuff)
Forward to any listeners
- pageRef(label)
hook to register a page number
- setPageCallBack(func)
Simple progress monitor - func(pageNo) called on each new page
- setProgressCallBack(func)
Cleverer progress monitor - func(typ, value) called regularly
- class reportlab.platypus.doctemplate.CurrentFrameFlowable(ix, resume=0)
- class reportlab.platypus.doctemplate.Indenter(left=0, right=0)
Increases or decreases left and right margins of frame.
This allows one to have a ‘context-sensitive’ indentation and makes nested lists way easier.
- frameAction(frame)
- height = 0
- width = 0
- class reportlab.platypus.doctemplate.IndexingFlowable
Abstract interface definition for flowables which might hold references to other pages or themselves be targets of cross-references. XRefStart, XRefDest, Table of Contents, Indexes etc.
- afterBuild()
Called after build ends but before isSatisfied
- beforeBuild()
Called by multiBuild before it starts; use this to clear old contents
- isIndexing()
Hook for IndexingFlowables - things which have cross references
- isSatisfied()
- notify(kind, stuff)
This will be called by the framework wherever ‘stuff’ happens. ‘kind’ will be a value that can be used to decide whether to pay attention or not.
- class reportlab.platypus.doctemplate.LCActionFlowable(action=())
- draw()
Should never be called.
- locChanger = 1
- wrap(availWidth, availHeight)
Should never be called.
- exception reportlab.platypus.doctemplate.LayoutError
- class reportlab.platypus.doctemplate.NextPageTemplate(pt)
- locChanger = 1
When you get to the next page, use the template specified (change to two column, for example)
- class reportlab.platypus.doctemplate.NotAtTopPageBreak(nextTemplate=None)
- frameAction(frame)
- locChanger = 1
- class reportlab.platypus.doctemplate.NullActionFlowable(action=())
- apply(doc)
This is called by the doc.build processing to allow the instance to implement its behaviour
- class reportlab.platypus.doctemplate.PageAccumulator(name=None)
gadget to accumulate information in a page and then allow it to be interrogated at the end of the page
- add(*args)
- attachToPageTemplate(pt)
- onDrawStr(value, *args)
- onDrawText(*args)
- onPage(canv, doc)
this will be called at the start of the page
- onPageEnd(canv, doc)
this will be called at the end of a page
- pageEndAction(canv, doc)
this should be overridden to do something useful
- reset()
- class reportlab.platypus.doctemplate.PageTemplate(id=None, frames=[], onPage=<function _doNothing>, onPageEnd=<function _doNothing>, pagesize=None, autoNextPageTemplate=None, cropBox=None, artBox=None, trimBox=None, bleedBox=None)
essentially a list of Frames and an onPage routine to call at the start of a page when this is selected. onPageEnd gets called at the end. derived classes can also implement beforeDrawPage and afterDrawPage if they want
- afterDrawPage(canv, doc)
This is called after the last flowable for the page has been processed. You might use this if the page header or footer needed knowledge of what flowables were drawn on this page.
- beforeDrawPage(canv, doc)
Override this if you want additional functionality or prefer a class based page routine. Called before any flowables for this page are processed.
- checkPageSize(canv, doc)
This gets called by the template framework If canv size != template size then the canv size is set to the template size or if that’s not available to the doc size.
- class reportlab.platypus.doctemplate.SimpleDocTemplate(filename, **kw)
A special case document template that will handle many simple documents. See documentation for BaseDocTemplate. No pageTemplates are required for this special case. A page templates are inferred from the margin information and the onFirstPage, onLaterPages arguments to the build method.
A document which has all pages with the same look except for the first page may can be built using this special approach.
- build(flowables, onFirstPage=<function _doNothing>, onLaterPages=<function _doNothing>, canvasmaker=<class 'reportlab.pdfgen.canvas.Canvas'>)
build the document using the flowables. Annotate the first page using the onFirstPage function and later pages using the onLaterPages function. The onXXX pages should follow the signature
- def myOnFirstPage(canvas, document):
# do annotations and modify the document …
The functions can do things like draw logos, page numbers, footers, etcetera. They can use external variables to vary the look (for example providing page numbering or section names).
- handle_pageBegin()
override base method to add a change of page template after the firstpage.
reportlab.platypus.figures
This includes some demos of platypus for use in the API proposal
- class reportlab.platypus.figures.DrawingFigure(modulename, classname, caption, baseDir=None, background=None)
Drawing with a caption below it. Clunky, scaling fails.
- drawFigure()
- class reportlab.platypus.figures.Figure(width, height, caption='', captionFont='Helvetica-Oblique', captionSize=12, background=None, captionTextColor=Color(0, 0, 0, 1), captionBackColor=None, border=None, spaceBefore=12, spaceAfter=12, captionGap=None, captionAlign='centre', captionPosition='bottom', hAlign='CENTER')
- draw()
- drawBackground()
For use when using a figure on a differently coloured background. Allows you to specify a colour to be used as a background for the figure.
- drawBorder()
- drawCaption()
- drawFigure()
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.figures.FlexFigure(width, height, caption, background=None, captionFont='Helvetica-Oblique', captionSize=8, captionTextColor=Color(0, 0, 0, 1), shrinkToFit=1, growToFit=1, spaceBefore=12, spaceAfter=12, captionGap=9, captionAlign='centre', captionPosition='top', scaleFactor=None, hAlign='CENTER', border=1)
Base for a figure class with a caption. Can grow or shrink in proportion
- split(availWidth, availHeight)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.figures.ImageFigure(filename, caption, background=None, scaleFactor=None, hAlign='CENTER', border=None)
Image with a caption below it
- drawFigure()
- class reportlab.platypus.figures.PageFigure(background=None)
Shows a blank page in a frame, and draws on that. Used in illustrations of how PLATYPUS works.
- drawFigure()
- drawVirtualPage()
- class reportlab.platypus.figures.PlatPropFigure1
This shows a page with a frame on it
- drawVirtualPage()
- reportlab.platypus.figures.demo1(canvas)
- reportlab.platypus.figures.drawPage(canvas, x, y, width, height)
- reportlab.platypus.figures.test1()
reportlab.platypus.flowables
A flowable is a “floating element” in a document whose exact position is determined by the other elements that precede it, such as a paragraph, a diagram interspersed between paragraphs, a section header, etcetera. Examples of non-flowables include page numbering annotations, headers, footers, fixed diagrams or logos, among others.
Flowables are defined here as objects which know how to determine their size and which can draw themselves onto a page with respect to a relative “origin” position determined at a higher level. The object’s draw() method should assume that (0,0) corresponds to the bottom left corner of the enclosing rectangle that will contain the object. The attributes vAlign and hAlign may be used by ‘packers’ as hints as to how the object should be placed.
Some Flowables also know how to “split themselves”. For example a long paragraph might split itself between one page and the next.
Packers should set the canv attribute during wrap, split & draw operations to allow the flowable to work out sizes etc in the proper context.
The “text” of a document usually consists mainly of a sequence of flowables which flow into a document from top to bottom (with column and page breaks controlled by higher level components).
- class reportlab.platypus.flowables.AnchorFlowable(name)
create a bookmark in the pdf
- draw()
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.BalancedColumns(F, nCols=2, needed=72, spaceBefore=0, spaceAfter=0, showBoundary=None, leftPadding=None, innerPadding=None, rightPadding=None, topPadding=None, bottomPadding=None, name='', endSlack=0.1, boxStrokeColor=None, boxStrokeWidth=0, boxFillColor=None, boxMargin=None, vLinesStrokeColor=None, vLinesStrokeWidth=None)
combine a list of flowables and an Image
- getSpaceAfter()
returns how much space should follow this item if another item follows on the same page.
- getSpaceBefore()
returns how much space should precede this item if another item precedess on the same page.
- identity(maxLen=None)
This method should attempt to return a string that can be used to identify a particular flowable uniquely. The result can then be used for debugging and or error printouts
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.BulletDrawer(value='0', bulletAlign='left', bulletType='1', bulletColor='black', bulletFontName='Helvetica', bulletFontSize=12, bulletOffsetY=0, bulletDedent=0, bulletDir='ltr', bulletFormat=None)
- drawOn(indenter, canv, x, y, _sW=0)
- class reportlab.platypus.flowables.CallerMacro(drawCallable=None, wrapCallable=None)
like Macro, but with callable command(s) drawCallable(self) wrapCallable(self,aW,aH)
- draw()
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.CondPageBreak(height)
- identity(maxLen=None)
This method should attempt to return a string that can be used to identify a particular flowable uniquely. The result can then be used for debugging and or error printouts
- locChanger = 1
use up a frame if not enough vertical space effectively CondFrameBreak
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.DDIndenter(flowable, leftIndent=0, rightIndent=0)
- drawOn(canv, x, y, _sW=0)
Tell it to draw itself on the canvas. Do not override
- identity(maxLen=None)
This method should attempt to return a string that can be used to identify a particular flowable uniquely. The result can then be used for debugging and or error printouts
- split(aW, aH)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.DocAssert(cond, format=None)
- funcWrap(aW, aH)
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.DocAssign(var, expr, life='forever')
At wrap time this flowable evaluates var=expr in the doctemplate namespace
- func()
- funcWrap(aW, aH)
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.DocExec(stmt, lifetime='forever')
at wrap time exec stmt in doc._nameSpace
- class reportlab.platypus.flowables.DocIf(cond, thenBlock, elseBlock=[])
- checkBlock(block)
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.DocPara(expr, format=None, style=None, klass=None, escape=True)
at wrap time create a paragraph with the value of expr as text if format is specified it should use %(__expr__)s for string interpolation of the expression expr (if any). It may also use %(name)s interpolations for other variables in the namespace. suitable defaults will be used if style and klass are None
- add_content(*args)
- func()
- get_value(aW, aH)
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.DocWhile(cond, whileBlock)
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.FailOnDraw
- draw()
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.FailOnWrap
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.Flowable
Abstract base class for things to be drawn. Key concepts:
It knows its size
It draws in its own coordinate system (this requires the base API to provide a translate() function.
- drawOn(canvas, x, y, _sW=0)
Tell it to draw itself on the canvas. Do not override
- getKeepWithNext()
returns boolean determining whether the next flowable should stay with this one
- getSpaceAfter()
returns how much space should follow this item if another item follows on the same page.
- getSpaceBefore()
returns how much space should precede this item if another item precedess on the same page.
- identity(maxLen=None)
This method should attempt to return a string that can be used to identify a particular flowable uniquely. The result can then be used for debugging and or error printouts
- isIndexing()
Hook for IndexingFlowables - things which have cross references
- minWidth()
This should return the minimum required width
- split(availWidth, availheight)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- splitOn(canv, aW, aH)
intended for use by packers allows setting the canvas on during the actual split
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- wrapOn(canv, aW, aH)
intended for use by packers allows setting the canvas on during the actual wrap
- class reportlab.platypus.flowables.FrameBG(color=None, left=0, right=0, start=True, strokeWidth=None, strokeColor=None, strokeDashArray=None)
Start or stop coloring the frame background left & right are distances from the edge of the frame to start stop colouring. if start in (‘frame’,’frame-permanent’) then the background is filled from here to the bottom of the frame and immediately discarded for the frame case.
- draw()
- class reportlab.platypus.flowables.FrameSplitter(nextTemplate, nextFrames=[], gap=10, required=72, adjustHeight=True)
When encountered this flowable should either switch directly to nextTemplate if remaining space in the current frame is less than gap+required or it should temporarily modify the current template to have the frames from nextTemplate that are listed in nextFrames and switch to the first of those frames.
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.HRFlowable(width='80%', thickness=1, lineCap='round', color=Color(.827451, .827451, .827451, 1), spaceBefore=1, spaceAfter=1, hAlign='CENTER', vAlign='BOTTOM', dash=None)
Like the hr tag
- draw()
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.Image(filename, width=None, height=None, kind='direct', mask='auto', lazy=1, hAlign='CENTER', useDPI=False)
an image (digital picture). Formats supported by PIL/Java 1.4 (the Python/Java Imaging Library are supported. Images as flowables may be aligned horizontally in the frame with the hAlign parameter - accepted values are ‘CENTER’, ‘LEFT’ or ‘RIGHT’ with ‘CENTER’ being the default. We allow for two kinds of lazyness to allow for many images in a document which could lead to file handle starvation. lazy=1 don’t open image until required. lazy=2 open image when required then shut it.
- draw()
- identity(maxLen=None)
This method should attempt to return a string that can be used to identify a particular flowable uniquely. The result can then be used for debugging and or error printouts
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.ImageAndFlowables(I, F, imageLeftPadding=0, imageRightPadding=3, imageTopPadding=0, imageBottomPadding=3, imageSide='right', imageHref=None)
combine a list of flowables and an Image
- deepcopy()
- drawOn(canv, x, y, _sW=0)
we simulate being added to a frame
- getSpaceAfter()
returns how much space should follow this item if another item follows on the same page.
- getSpaceBefore()
returns how much space should precede this item if another item precedess on the same page.
- split(availWidth, availHeight)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.KeepInFrame(maxWidth, maxHeight, content=[], mergeSpace=1, mode='shrink', name='', hAlign='LEFT', vAlign='BOTTOM', fakeWidth=None)
- drawOn(canv, x, y, _sW=0)
we simulate being added to a frame
- identity(maxLen=None)
This method should attempt to return a string that can be used to identify a particular flowable uniquely. The result can then be used for debugging and or error printouts
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.KeepTogether(flowables, maxHeight=None)
- identity(maxLen=None)
This method should attempt to return a string that can be used to identify a particular flowable uniquely. The result can then be used for debugging and or error printouts
- split(aW, aH)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- splitAtTop = False
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.LIIndenter(flowable, leftIndent=0, rightIndent=0, bullet=None, spaceBefore=None, spaceAfter=None)
- drawOn(canv, x, y, _sW=0)
Tell it to draw itself on the canvas. Do not override
- split(aW, aH)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- class reportlab.platypus.flowables.ListFlowable(flowables, start=None, style=None, **kwds)
- split(aW, aH)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.ListItem(flowables, style=None, **kwds)
- class reportlab.platypus.flowables.Macro(command)
This is not actually drawn (i.e. it has zero height) but is executed when it would fit in the frame. Allows direct access to the canvas through the object ‘canvas’
- draw()
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.PTOContainer(contentList, trailerList, headerList)
A container for flowables decorated with trailer & header lists. If the split operation would be called then the trailer and header lists are injected before and after the split. This allows specialist “please turn over” and “continued from previous” like behaviours.
- split(availWidth, availHeight)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.PageBreak(nextTemplate=None)
- locChanger = 1
Move on to the next page in the document. This works by consuming all remaining space in the frame!
- class reportlab.platypus.flowables.PageBreakIfNotEmpty(nextTemplate=None)
- class reportlab.platypus.flowables.ParagraphAndImage(P, I, xpad=3, ypad=3, side='right')
combine a Paragraph and an Image
- draw()
- getSpaceAfter()
returns how much space should follow this item if another item follows on the same page.
- getSpaceBefore()
returns how much space should precede this item if another item precedess on the same page.
- split(availWidth, availHeight)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.PlacedStory(x, y, maxWidth, maxHeight, content=[], mergeSpace=1, mode='shrink', name='', anchor='sw', fakeWidth=None, hAlign='LEFT', vAlign='BOTTOM', showBoundary=None, origin='page')
- drawOn(canv, lx, ly, _sW=0)
Tell it to draw itself on the canvas. Do not override
- wrap(_aW, _aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.Preformatted(text, style, bulletText=None, dedent=0, maxLineLength=None, splitChars=None, newLineChars='')
This is like the HTML <PRE> tag. It attempts to display text exactly as you typed it in a fixed width “typewriter” font. By default the line breaks are exactly where you put them, and it will not be wrapped. You can optionally define a maximum line length and the code will be wrapped; and extra characters to be inserted at the beginning of each wrapped line (e.g. ‘> ‘).
- draw()
- minWidth()
This should return the minimum required width
- split(availWidth, availHeight)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.SetPageTopFlowables(F, show=False)
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.SetTopFlowables(F, show=False)
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.SlowPageBreak(nextTemplate=None)
- class reportlab.platypus.flowables.Spacer(width, height, isGlue=False)
A spacer just takes up space and doesn’t draw anything - it guarantees a gap between objects.
- class reportlab.platypus.flowables.TopPadder(f)
wrap a single flowable so that its first bit will be padded to fill out the space so that it appears at the bottom of its frame
- drawOn(canvas, x, y, _sW=0)
Tell it to draw itself on the canvas. Do not override
- split(aW, aH)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.TraceInfo
Holder for info about where an object originated
- class reportlab.platypus.flowables.UseUpSpace
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.flowables.XBox(width, height, text='A Box')
Example flowable - a box with an x through it and a caption. This has a known size, so does not need to respond to wrap().
- draw()
- reportlab.platypus.flowables.splitLine(line_to_split, lines_splitted, maximum_length, split_characters, new_line_characters)
- reportlab.platypus.flowables.splitLines(lines, maximum_length, split_characters, new_line_characters)
reportlab.platypus.frames
A frame is a container for content on a page.
- class reportlab.platypus.frames.Frame(x1, y1, width, height, leftPadding=6, bottomPadding=6, rightPadding=6, topPadding=6, id=None, showBoundary=0, overlapAttachedSpace=None, _debug=None)
A Frame is a piece of space in a document that is filled by the “flowables” in the story. For example in a book like document most pages have the text paragraphs in one or two frames. For generality a page might have several frames (for example for 3 column text or for text that wraps around a graphic).
After creation a Frame is not usually manipulated directly by the applications program – it is used internally by the platypus modules.
Here is a diagramatid abstraction for the definitional part of a Frame:
width x2,y2 +---------------------------------+ | l top padding r | h | e +-------------------------+ i | e | f | | g | i | t | | h | g | | | t | h | p | | | t | a | | p | | d | | a | | | | d | | +-------------------------+ | | bottom padding | +---------------------------------+ (x1,y1) <-- lower left corner
NOTE!! Frames are stateful objects. No single frame should be used in two documents at the same time (especially in the presence of multithreading.
- add(flowable, canv, trySplit=0)
Draws the flowable at the current position. Returns 1 if successful, 0 if it would not fit. Raises a LayoutError if the object is too wide, or if it is too high for a totally empty frame, to avoid infinite loops
- addFromList(drawlist, canv)
Consumes objects from the front of the list until the frame is full. If it cannot fit one object, raises an exception.
- add_generated_content(*C)
- drawBoundary(canv, __boundary__=None)
- split(flowable, canv)
Ask the flowable to split using up the available space.
reportlab.platypus.multicol
- class reportlab.platypus.multicol.MultiCol(contents, widths, minHeightNeeded=36, spaceBefore=None, spaceAfter=None)
- drawOn(canv, x, y, _sW=0)
we simulate being added to a frame
- getSpaceAfter()
returns how much space should follow this item if another item follows on the same page.
- getSpaceBefore()
returns how much space should precede this item if another item precedess on the same page.
- nWidths(aW)
- split(aW, aH)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- wrap(aW, aH)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
reportlab.platypus.para
new experimental paragraph implementation
Intended to allow support for paragraphs in paragraphs, hotlinks, embedded flowables, and underlining. The main entry point is the function
def Paragraph(text, style, bulletText=None, frags=None)
Which is intended to be plug compatible with the “usual” platypus paragraph except that it supports more functionality.
In this implementation you may embed paragraphs inside paragraphs to create hierarchically organized documents.
This implementation adds the following paragraph-like tags (which support the same attributes as paragraphs, for font specification, etc).
Unnumberred lists (ala html):
<ul> <li>first one</li> <li>second one</li> </ul>
Also <ul type=”disc”> (default) or <ul type=”circle”>, <ul type=”square”>.
Numberred lists (ala html):
<ol> <li>first one</li> <li>second one</li> </ol>
Also <ul type=”1”> (default) or <ul type=”a”>, <ul type=”A”>.
Display lists (ala HTML):
For example
<dl bulletFontName=”Helvetica-BoldOblique” spaceBefore=”10” spaceAfter=”10”> <dt>frogs</dt> <dd>Little green slimy things. Delicious with <b>garlic</b></dd> <dt>kittens</dt> <dd>cute, furry, not edible</dd> <dt>bunnies</dt> <dd>cute, furry,. Delicious with <b>garlic</b></dd> </dl>
ALSO the following additional internal paragraph markup tags are supported
<u>underlined text</u>
<a href=”http://www.reportlab.com”>hyperlinked text</a> <a href=”http://www.reportlab.com” color=”blue”>hyperlinked text</a>
<link destination=”end” >Go to the end (go to document internal destination)</link> <link destination=”start” color=”cyan”>Go to the beginning</link>
- <setLink destination=”start” color=”magenta”>This is the document start
(define document destination inside paragraph, color is optional)</setLink>
- reportlab.platypus.para.EmbedInRml2pdf()
make the para the default para implementation in rml2pdf
- class reportlab.platypus.para.EvalStringObject(attdict, content, extra, context)
this will only work if rml2pdf is present
- execute(engine, textobject, canvas)
- getOp(tuple, engine)
- tagname = 'evalString'
- width(engine)
- class reportlab.platypus.para.FastPara(style, simpletext)
paragraph with no special features (not even a single ampersand!)
- draw()
- getSpaceAfter()
returns how much space should follow this item if another item follows on the same page.
- getSpaceBefore()
returns how much space should precede this item if another item precedess on the same page.
- split(availableWidth, availableHeight)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- wrap(availableWidth, availableHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.para.HotLink(url)
- end_at(x, y, para, canvas, textobject)
- link(rect, canvas)
- class reportlab.platypus.para.NameObject(attdict, content, extra, context)
- execute(engine, textobject, canvas)
- tagname = 'name'
- class reportlab.platypus.para.PageNumberObject(example='XXX')
- execute(engine, textobject, canvas)
- width(engine)
- class reportlab.platypus.para.Para(style, parsedText=None, bulletText=None, state=None, context=None, baseindent=0)
- compileComponent(parsedText, program)
- compileProgram(parsedText, program=None)
- compile_(attdict, content, extra, program)
- compile_a(attdict, content, extra, program)
- compile_b(attdict, content, extra, program)
- compile_bullet(attdict, content, extra, program)
- compile_dl(attdict, content, extra, program)
- compile_evalString(attdict, content, extra, program)
- compile_font(attdict, content, extra, program)
- compile_getName(attdict, content, extra, program)
- compile_greek(attdict, content, extra, program)
- compile_i(attdict, content, extra, program)
- compile_link(attdict, content, extra, program)
- compile_name(attdict, content, extra, program)
- compile_ol(attdict, content, extra, program)
- compile_pageNumber(attdict, content, extra, program)
- compile_para(attdict, content, extra, program, stylename='para.defaultStyle')
- compile_seq(attdict, content, extra, program)
- compile_seqDefault(attdict, content, extra, program)
- compile_seqReset(attdict, content, extra, program)
- compile_setLink(attdict, content, extra, program)
- compile_sub(attdict, content, extra, program)
- compile_super(attdict, content, extra, program)
- compile_tt(attdict, content, extra, program)
- compile_u(attdict, content, extra, program)
- compile_ul(attdict, content, extra, program, tagname='ul')
- do_bullet(text, program)
- draw()
- getSpaceAfter()
returns how much space should follow this item if another item follows on the same page.
- getSpaceBefore()
returns how much space should precede this item if another item precedess on the same page.
- linearize(program=None, parsedText=None)
- shiftfont(program, face=None, bold=None, italic=None)
- spaceAfter = 0
- spaceBefore = 0
- split(availableWidth, availableHeight)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- wrap(availableWidth, availableHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- reportlab.platypus.para.Paragraph(text, style, bulletText=None)
intended to be like a platypus Paragraph but better.
- class reportlab.platypus.para.SeqDefaultObject(attdict, content, extra, context)
- getOp(tuple, engine)
- class reportlab.platypus.para.SeqResetObject(attdict, content, extra, context)
- getOp(tuple, engine)
- class reportlab.platypus.para.SimpleStyle(name, parent=None, **kw)
simplified paragraph style without all the fancy stuff
- addAttributes(dictionary)
- alignment = 0
- backColor = None
- bulletFontName = 'Helvetica'
- bulletFontSize = 10
- bulletIndent = 0
- firstLineIndent = 0
- fontName = 'Helvetica'
- fontSize = 10
- leading = 12
- leftIndent = 0
- name = 'basic'
- rightIndent = 0
- spaceAfter = 0
- spaceBefore = 0
- textColor = Color(0,0,0,1)
- class reportlab.platypus.para.StyleAttributeConverters
- alignment = [<function readAlignment>]
- backColor = [<function readColor>]
- bulletFontSize = [<function readLength>]
- bulletIndent = [<function readLength>]
- firstLineIndent = [<function readLength>]
- fontSize = [<function readLength>]
- leading = [<function readLength>]
- leftIndent = [<function readLength>]
- rightIndent = [<function readLength>]
- spaceAfter = [<function readLength>]
- spaceBefore = [<function readLength>]
- textColor = [<function readColor>]
- class reportlab.platypus.para.UnderLineHandler(color=None)
- end_at(x, y, para, canvas, textobject)
- start_at(x, y, para, canvas, textobject)
- reportlab.platypus.para.buildContext(stylesheet=None)
- reportlab.platypus.para.defaultContext()
- reportlab.platypus.para.handleSpecialCharacters(engine, text, program=None)
- reportlab.platypus.para.lengthSequence(s, converter=<function readLength>)
from “(2, 1)” or “2,1” return [2,1], for example
- class reportlab.platypus.para.paragraphEngine(program=None)
- TEXT_STATE_VARIABLES = ('indent', 'rightIndent', 'fontName', 'fontSize', 'leading', 'fontColor', 'lineOpHandlers', 'rise', 'alignment')
- centerAlign(line, lineLength, maxLength)
- cleanProgram(line)
collapse adjacent spacings
- fitLine(program, totalLength)
fit words (and other things) onto a line
- format(maxwidth, maxheight, program, leading=0)
return program with line operations added if at least one line fits
- getState()
- insertShift(line, shift)
- justifyAlign(line, lineLength, maxLength)
- popTextState()
- pushTextState()
- resetState(state)
- rightAlign(line, lineLength, maxLength)
- runOpCodes(program, canvas, textobject)
render the line(s)
- shrinkWrap(line)
- reportlab.platypus.para.readAlignment(text)
- reportlab.platypus.para.readBool(text)
- reportlab.platypus.para.readColor(text)
Read color names or tuples, RGB or CMYK, and return a Color object.
- reportlab.platypus.para.readLength(text)
Read a dimension measurement: accept “3in”, “5cm”, “72 pt” and so on.
- reportlab.platypus.para.simpleJustifyAlign(line, currentLength, maxLength)
simple justification with only strings
- reportlab.platypus.para.splitspace(text)
- reportlab.platypus.para.stringLine(line, length)
simple case: line with just strings and spacings which can be ignored
- reportlab.platypus.para.test()
- reportlab.platypus.para.test2(canv, testpara)
reportlab.platypus.paragraph
The standard paragraph implementation
- class reportlab.platypus.paragraph.FragLine(**attr)
class FragLine contains a styled line (ie a line with more than one style):
extraSpace unused space for justification only wordCount 1+spaces in line for justification purposes words [ParaFrags] style text lumps to be concatenated together fontSize maximum fontSize seen on the line; not used at present, but could be used for line spacing.
- class reportlab.platypus.paragraph.ParaLines(**attr)
- class ParaLines contains the broken into lines representation of Paragraphs
kind=0 Simple fontName, fontSize, textColor apply to whole Paragraph lines [(extraSpace1,words1),….,(extraspaceN,wordsN)]
kind==1 Complex lines [FragLine1,…,FragLineN]
- class reportlab.platypus.paragraph.Paragraph(text, style, bulletText=None, caseSensitive=1)
text a string of stuff to go into the paragraph. style is a style definition as in reportlab.lib.styles. bulletText is an optional bullet defintion. caseSensitive set this to 0 if you want the markup tags and their attributes to be case-insensitive.
This class is a flowable that can format a block of text into a paragraph with a given style.
The paragraph Text can contain XML-like markup including the tags: <b> … </b> - bold < u [color=”red”] [width=”pts”] [offset=”pts”]> < /u > - underline
width and offset can be empty meaning use existing canvas line width or with an f/F suffix regarded as a fraction of the font size
< strike > < /strike > - strike through has the same parameters as underline <i> … </i> - italics <u> … </u> - underline <strike> … </strike> - strike through <super> … </super> - superscript <sub> … </sub> - subscript <font name=fontfamily/fontname color=colorname size=float> <span name=fontfamily/fontname color=colorname backcolor=colorname size=float style=stylename> <onDraw name=callable label=”a label”/> <index [name=”callablecanvasattribute”] label=”a label”/> <link>link text</link>
- attributes of links
size/fontSize/uwidth/uoffset=num name/face/fontName=name fg/textColor/color/ucolor=color backcolor/backColor/bgcolor=color dest/destination/target/href/link=target underline=bool turn on underline
- <a>anchor text</a>
- attributes of anchors
size/fontSize/uwidth/uoffset=num fontName=name fg/textColor/color/ucolor=color backcolor/backColor/bgcolor=color href=href underline=”yes|no”
<a name=”anchorpoint”/> <unichar name=”unicode character name”/> <unichar value=”unicode code point”/> <img src=”path” width=”1in” height=”1in” valign=”bottom”/>
width=”w%” –> fontSize*w/100 idea from Roberto Alsina height=”h%” –> linewidth*h/100 <ralsina@netmanagers.com.ar>
The whole may be surrounded by <para> </para> tags
The <b> and <i> tags will work for the built-in fonts (Helvetica /Times / Courier). For other fonts you need to register a family of 4 fonts using reportlab.pdfbase.pdfmetrics.registerFont; then use the addMapping function to tell the library that these 4 fonts form a family e.g. from reportlab.lib.fonts import addMapping addMapping(‘Vera’, 0, 0, ‘Vera’) #normal addMapping(‘Vera’, 0, 1, ‘Vera-Italic’) #italic addMapping(‘Vera’, 1, 0, ‘Vera-Bold’) #bold addMapping(‘Vera’, 1, 1, ‘Vera-BoldItalic’) #italic and bold
It will also be able to handle any MathML specified Greek characters.
- beginText(x, y)
- breakLines(width)
Returns a broken line structure. There are two cases
- For the simple case of a single formatting input fragment the output is
- A fragment specifier with
kind = 0
fontName, fontSize, leading, textColor
lines= A list of lines
Each line has two items.
unused width in points
word list
- When there is more than one input formatting fragment the output is
- A fragment specifier with
kind = 1
- lines= A list of fragments each having fields
extraspace (needed for justified)
fontSize
- words=word list
each word is itself a fragment with various settings
in addition frags becomes a frag word list
This structure can be used to easily draw paragraphs with the various alignments. You can supply either a single width or a list of widths; the latter will have its last item repeated until necessary. A 2-element list is useful when there is a different first line indent; a longer list could be created to facilitate custom wraps around irregular objects.
- breakLinesCJK(maxWidths)
Initially, the dumbest possible wrapping algorithm. Cannot handle font variations.
- draw()
- drawPara(debug=0)
Draws a paragraph according to the given style. Returns the final y position at the bottom. Not safe for paragraphs without spaces e.g. Japanese; wrapping algorithm will go infinite.
- static dumpFrags(frags, indent=4, full=False)
- getActualLineWidths0()
Convenience function; tells you how wide each line actually is. For justified styles, this will be the same as the wrap width; for others it might be useful for seeing if paragraphs will fit in spaces.
- getPlainText(identify=None)
Convenience function for templates which want access to the raw text, without XML tags.
- minWidth()
Attempt to determine a minimum sensible width
- split(availWidth, availHeight)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- reportlab.platypus.paragraph.cleanBlockQuotedText(text, joiner=' ')
This is an internal utility which takes triple- quoted text form within the document and returns (hopefully) the paragraph the user intended originally.
reportlab.platypus.paraparser
The parser used to process markup within paragraphs
- class reportlab.platypus.paraparser.ParaFrag(**attr)
class ParaFrag contains the intermediate representation of string segments as they are being parsed by the ParaParser. fontname, fontSize, rise, textColor, cbDefn
- class reportlab.platypus.paraparser.ParaParser(verbose=0, caseSensitive=0, ignoreUnknownTags=1, crashOnError=True)
- end_a()
- end_b()
- end_br()
- end_bullet()
- end_em()
- end_font()
- end_greek()
- end_i()
- end_img()
- end_index()
- end_link()
- end_nobr()
- end_onDraw()
- end_ondraw()
- end_para()
- end_seq()
- end_seqChain()
- end_seqDefault()
- end_seqFormat()
- end_seqReset()
- end_seqchain()
- end_seqdefault()
- end_seqformat()
- end_seqreset()
- end_span()
- end_strike()
- end_strong()
- end_sub()
- end_sup()
- end_super()
- end_u()
- end_unichar()
- end_unknown()
- findSpanStyle(style)
- getAttributes(attr, attrMap)
- handle_cdata(data)
- handle_charref(name)
- handle_data(data)
Creates an intermediate representation of string segments.
- handle_endtag(tag)
Called by HTMLParser when a tag ends
- handle_entityref(name)
Handles a named entity.
- handle_starttag(tag, attrs)
Called by HTMLParser when a tag starts
- parse(text, style)
attempt replacement for parse
- start_a(attributes)
- start_b(attributes)
- start_br(attr)
- start_bullet(attr)
- start_em(attributes)
- start_font(attr)
- start_greek(attr)
- start_i(attributes)
- start_img(attributes)
- start_index(attr)
- start_link(attributes)
- start_nobr(attrs)
- start_onDraw(attr)
- start_ondraw(attr)
- start_para(attr)
- start_seq(attr)
- start_seqChain(attr)
- start_seqDefault(attr)
- start_seqFormat(attr)
- start_seqReset(attr)
- start_seqchain(attr)
- start_seqdefault(attr)
- start_seqformat(attr)
- start_seqreset(attr)
- start_span(attr)
- start_strike(attributes)
- start_strong(attributes)
- start_sub(attributes)
- start_sup(attributes)
- start_super(attributes)
- start_u(attributes)
- start_unichar(attr)
- start_unknown(attr)
- syntax_error(lineno, message)
- tt_parse(tt, style)
parse from tupletree form
reportlab.platypus.tableofcontents
Experimental class to generate Tables of Contents easily
This module defines a single TableOfContents() class that can be used to create automatically a table of tontents for Platypus documents like this:
story = [] toc = TableOfContents() story.append(toc) # some heading paragraphs here… doc = MyTemplate(path) doc.multiBuild(story)
The data needed to create the table is a list of (level, text, pageNum) triplets, plus some paragraph styles for each level of the table itself. The triplets will usually be created in a document template’s method like afterFlowable(), making notification calls using the notify() method with appropriate data like this:
(level, text, pageNum) = … self.notify(‘TOCEntry’, (level, text, pageNum))
Optionally the list can contain four items in which case the last item is a destination key which the entry should point to. A bookmark with this key needs to be created first like this:
key = ‘ch%s’ % self.seq.nextf(‘chapter’) self.canv.bookmarkPage(key) self.notify(‘TOCEntry’, (level, text, pageNum, key))
As the table of contents need at least two passes over the Platypus story which is why the multiBuild() method must be called.
The level<NUMBER>ParaStyle variables are the paragraph styles used to format the entries in the table of contents. Their indentation is calculated like this: each entry starts at a multiple of some constant named delta. If one entry spans more than one line, all lines after the first are indented by the same constant named epsilon.
- reportlab.platypus.tableofcontents.AlphabeticIndex
alias of
SimpleIndex
- class reportlab.platypus.tableofcontents.ReferenceText(textPattern, targetKey)
Fakery to illustrate how a reference would work if we could put it in a paragraph.
- beforeBuild()
Called by multiBuild before it starts; use this to clear old contents
- drawOn(canvas, x, y, _sW=0)
Tell it to draw itself on the canvas. Do not override
- notify(kind, stuff)
This will be called by the framework wherever ‘stuff’ happens. ‘kind’ will be a value that can be used to decide whether to pay attention or not.
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
- class reportlab.platypus.tableofcontents.SimpleIndex(**kwargs)
Creates multi level indexes. The styling can be cutomized and alphabetic headers turned on and off.
- addEntry(text, pageNum, key=None)
Allows incremental buildup
- beforeBuild()
Called by multiBuild before it starts; use this to clear old contents
- clearEntries()
- draw()
- drawOn(canvas, x, y, _sW=0)
Don’t do this at home! The standard calls for implementing draw(); we are hooking this in order to delegate ALL the drawing work to the embedded table object.
- getCanvasMaker(canvasmaker=<class 'reportlab.pdfgen.canvas.Canvas'>)
- getFormatFunc(formatName)
- getLevelStyle(n)
Returns the style for level n, generating and caching styles on demand if not present.
- isIndexing()
Hook for IndexingFlowables - things which have cross references
- isSatisfied()
- notify(kind, stuff)
The notification hook called to register all kinds of events.
Here we are interested in self._notifyKind (default IndexEntry) events only.
- setup(style=None, dot=None, tableStyle=None, headers=True, name=None, format='123', offset=0)
This method makes it possible to change styling and other parameters on an existing object.
style is the paragraph style to use for index entries. dot can either be None or a string. If it’s None, entries are immediatly followed by their
corresponding page numbers. If it’s a string, page numbers are aligned on the right side of the document and the gap filled with a repeating sequence of the string.
- tableStyle is the style used by the table which the index uses to draw itself. Use this to
change properties like spacing between elements.
headers is a boolean. If it is True, alphabetic headers are displayed in the Index when the first letter changes. If False, we just output some extra space before the next item name makes it possible to use several indexes in one document. If you want this use this
parameter to give each index a unique name. You can then index a term by refering to the name of the index which it should appear in:
<index item=”term” name=”myindex” />
format can be ‘I’, ‘i’, ‘123’, ‘ABC’, ‘abc’
- split(availWidth, availHeight)
At this stage we do not care about splitting the entries, we will just return a list of platypus tables. Presumably the calling app has a pointer to the original TableOfContents object; Platypus just sees tables.
- wrap(availWidth, availHeight)
All table properties should be known by now.
- class reportlab.platypus.tableofcontents.TableOfContents(**kwds)
This creates a formatted table of contents.
It presumes a correct block of data is passed in. The data block contains a list of (level, text, pageNumber) triplets. You can supply a paragraph style for each level (starting at zero). Set dotsMinLevel to determine from which level on a line of dots should be drawn between the text and the page number. If dotsMinLevel is set to a negative value, no dotted lines are drawn.
- addEntries(listOfEntries)
Bulk creation of entries in the table of contents.
If you knew the titles but not the page numbers, you could supply them to get sensible output on the first run.
- addEntry(level, text, pageNum, key=None)
Adds one entry to the table of contents.
This allows incremental buildup by a doctemplate. Requires that enough styles are defined.
- beforeBuild()
Called by multiBuild before it starts; use this to clear old contents
- clearEntries()
- drawOn(canvas, x, y, _sW=0)
Don’t do this at home! The standard calls for implementing draw(); we are hooking this in order to delegate ALL the drawing work to the embedded table object.
- getLevelStyle(n)
Returns the style for level n, generating and caching styles on demand if not present.
- isIndexing()
Hook for IndexingFlowables - things which have cross references
- isSatisfied()
- notify(kind, stuff)
The notification hook called to register all kinds of events.
Here we are interested in self._notifyKind (default TOCEntry) events only.
- split(availWidth, availHeight)
At this stage we do not care about splitting the entries, we will just return a list of platypus tables. Presumably the calling app has a pointer to the original TableOfContents object; Platypus just sees tables.
- wrap(availWidth, availHeight)
All table properties should be known by now.
- reportlab.platypus.tableofcontents.drawPageNumbers(canvas, style, pages, availWidth, availHeight, dot=' . ', formatter=None)
Draws pagestr on the canvas using the given style. If dot is None, pagestr is drawn at the current position in the canvas. If dot is a string, pagestr is drawn right-aligned. If the string is not empty, the gap is filled with it.
- reportlab.platypus.tableofcontents.listdiff(l1, l2)
- reportlab.platypus.tableofcontents.makeTuple(x)
- reportlab.platypus.tableofcontents.unquote(txt)
reportlab.platypus.tables
Tables are created by passing the constructor a tuple of column widths, a tuple of row heights and the data in row order. Drawing of the table can be controlled by using a TableStyle instance. This allows control of the color and weight of the lines (if any), and the font, alignment and padding of the text.
None values in the sequence of row heights or column widths, mean that the corresponding rows or columns should be automatically sized.
All the cell values should be convertible to strings; embedded newline ‘n’ characters cause the value to wrap (ie are like a traditional linefeed).
See the test output from running this module as a script for a discussion of the method for constructing tables and table styles.
- class reportlab.platypus.tables.CellStyle(name, parent=None)
- alignment = 'LEFT'
- background = 'white'
- bottomPadding = 3
- color = 'black'
- copy(result=None)
- destination = None
- direction = None
- firstLineIndent = 0
- fontname = 'Helvetica'
- fontsize = 10
- href = None
- leading = 12
- leftPadding = 6
- rightPadding = 6
- shaping = None
- topPadding = 3
- valign = 'BOTTOM'
- class reportlab.platypus.tables.LongTable(data, colWidths=None, rowHeights=None, style=None, repeatRows=0, repeatCols=0, splitByRow=1, splitInRow=0, emptyTableAction=None, ident=None, hAlign=None, vAlign=None, normalizedData=0, cellStyles=None, rowSplitRange=None, spaceBefore=None, spaceAfter=None, longTableOptimize=None, minRowHeights=None, cornerRadii=__UNSET__, renderCB=None)
Henning von Bargen’s changes will be active
- class reportlab.platypus.tables.Table(data, colWidths=None, rowHeights=None, style=None, repeatRows=0, repeatCols=0, splitByRow=1, splitInRow=0, emptyTableAction=None, ident=None, hAlign=None, vAlign=None, normalizedData=0, cellStyles=None, rowSplitRange=None, spaceBefore=None, spaceAfter=None, longTableOptimize=None, minRowHeights=None, cornerRadii=__UNSET__, renderCB=None)
- draw()
- identity(maxLen=30)
Identify our selves as well as possible
- minWidth()
This should return the minimum required width
- normCellRange(sc, ec, sr, er)
ensure cell range ends are with the table bounds
- normalizeData(data)
Takes a block of input data (list of lists etc.) and - coerces unicode strings to non-unicode UTF8 - coerces nulls to ‘’ -
- onSplit(T, byRow=1)
This method will be called when the Table is split. Special purpose tables can override to do special stuff.
- setStyle(tblstyle)
- split(availWidth, availHeight)
This will be called by more sophisticated frames when wrap fails. Stupid flowables should return []. Clever flowables should split themselves and return a list of flowables. If they decide that nothing useful can be fitted in the available space (e.g. if you have a table and not enough space for the first row), also return []
- wrap(availWidth, availHeight)
This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.
reportlab.platypus.xpreformatted
A ‘rich preformatted text’ widget allowing internal markup
- class reportlab.platypus.xpreformatted.PythonPreformatted(text, style, bulletText=None, dedent=0, frags=None)
Used for syntax-colored Python code, otherwise like XPreformatted.
- escapeHtml(text)
- fontify(code)
Return a fontified version of some Python code.
- formats = {'comment': ('<font color="green">', '</font>'), 'identifier': ('<font color="red">', '</font>'), 'keyword': ('<font color="blue"><b>', '</b></font>'), 'parameter': ('<font color="black">', '</font>'), 'rest': ('', ''), 'string': ('<font color="gray">', '</font>')}
- class reportlab.platypus.xpreformatted.XPreformatted(text, style, bulletText=None, frags=None, caseSensitive=1, dedent=0)
- breakLines(width)
Returns a broken line structure. There are two cases
- For the simple case of a single formatting input fragment the output is
- A fragment specifier with
kind = 0
fontName, fontSize, leading, textColor
lines= A list of lines
Each line has two items:
unused width in points
a list of words
- When there is more than one input formatting fragment the out put is
- A fragment specifier with
kind = 1
lines = A list of fragments each having fields:
extraspace (needed for justified)
fontSize
words=word list
each word is itself a fragment with
various settings
This structure can be used to easily draw paragraphs with the various alignments. You can supply either a single width or a list of widths; the latter will have its last item repeated until necessary. A 2-element list is useful when there is a different first line indent; a longer list could be created to facilitate custom wraps around irregular objects.
- breakLinesCJK(width)
Returns a broken line structure. There are two cases
- For the simple case of a single formatting input fragment the output is
- A fragment specifier with
kind = 0
fontName, fontSize, leading, textColor
lines= A list of lines
Each line has two items:
unused width in points
a list of words
- When there is more than one input formatting fragment the out put is
- A fragment specifier with
kind = 1
lines = A list of fragments each having fields:
extraspace (needed for justified)
fontSize
words=word list
each word is itself a fragment with
various settings
This structure can be used to easily draw paragraphs with the various alignments. You can supply either a single width or a list of widths; the latter will have its last item repeated until necessary. A 2-element list is useful when there is a different first line indent; a longer list could be created to facilitate custom wraps around irregular objects.