Graphics and Charts¶
Graphics and Charts
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
charts¶
Business charts
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
- 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, canvasKwds={})¶
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, canvasKwds={})¶
Returns a PDF as a string in memory, without touching the disk
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.draw(drawing, canvas, x, y, showBoundary=<reportlab.rl_config._unset_ object>)¶
As it says
- reportlab.graphics.renderPM.drawToFile(d, fn, fmt='GIF', dpi=72, bg=16777215, configPIL=None, showBoundary=<reportlab.rl_config._unset_ object>, backend='_renderPM')¶
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.save(d, fn, fmt='GIF', dpi=72, bg=16777215, configPIL=None, showBoundary=<reportlab.rl_config._unset_ object>, backend='_renderPM')¶
create a pixmap and draw drawing, d to it then save as a file configPIL dict is passed to image save method
renderPS¶
Render drawing objects in Postscript
- reportlab.graphics.renderPS.draw(drawing, canvas, x=0, y=0, showBoundary=0)¶
As it says
- reportlab.graphics.renderPS.drawToString(d, showBoundary=0)¶
Returns a PS as a string in memory, without touching the disk
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
- reportlab.graphics.renderSVG.draw(drawing, canvas, x=0, y=0, showBoundary=0)¶
As it says.
- reportlab.graphics.renderSVG.drawToString(d, showBoundary=0, **kwds)¶
Returns a SVG as a string in memory, without touching the disk
- 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()]”/>
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.
- drawNode(node)¶
This is the recursive method called for each node in the tree
- drawNodeDispatcher(node)¶
dispatch on the node’s (super) class: shared code
- 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
- 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
samples¶
Example drawings to review, used in autogenerated docs
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
- 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
- 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.
- 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)¶
Convenience to help you set transforms
- scale(sx, sy)¶
Convenience to help you set transforms
- shift(x, y)¶
Convenience function to set the origin arbitrarily
- skew(kx, ky)¶
Convenience to help you set transforms
- translate(dx, dy)¶
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.
- copy()¶
Return a clone of this shape.
- getBounds()¶
Returns bounding rectangle of object as (x1,y1,x2,y2)
- 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.
- getBounds()¶
Returns bounding rectangle of object as (x1,y1,x2,y2)
- 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
- copy()¶
Return a clone of this shape.
- getBounds()¶
Returns bounding rectangle of object as (x1,y1,x2,y2)
- reportlab.graphics.shapes.getPointsBounds(pointList)¶
Helper function for list of points
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.
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.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 patch given in rl_config.py, for example in reportlab/lib/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.smallArrow()¶
create a small PIL image
- reportlab.graphics.testshapes.writePDF(drawings)¶
Create and save a PDF file containing some drawings.
widgetbase¶
Base class for user-defined graphical widgets
- class reportlab.graphics.widgetbase.CandleStickProperties(**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.
- 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
- 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
- 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.TwoCircles¶
- 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
- 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.
- 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.
- 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.tpcGetItem(obj, x)¶
return obj if it’s not a TypedPropertyCollection else obj[x]
widgets¶
Some non-chart widgets