ReportLab Library Reference¶
API main index
This page covers modules within reportlab/lib which may be of use to developers. We have tried only to include things we intend people to use; a lot of code in /lib/ is used by our package itself, and we reserve the right to change it if it’s not documented here.
Hint: review tests and user guide and see what is actually imported
Users definitely need:
- units
- colors
- utils
See what else is commonly imported and used in the test scripts!
If in doubt, include it and put a comment so Andy can review.
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
colors¶
Defines standard colour-handling classes and colour names.
We define standard classes to hold colours in two models: RGB and CMYK. These 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
- 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
- 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).
- clone(**kwds)¶
copy then change values in kwds
- rgb()¶
Returns a three-tuple of components
- rgba()¶
Returns a four-tuple of components
- reportlab.lib.colors.HexColor(val, htmlOnly=False, alpha=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.
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
- 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.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.rgb2cmyk(r, g, b)¶
one way to get cmyk from rgb
- reportlab.lib.colors.toColorOrNone(arg, default=None)¶
as above but allows None as a legal value
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.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.
- class reportlab.lib.utils.FmtSelfDict¶
mixin to provide the _fmt method
- class reportlab.lib.utils.ImageReader(fileName, ident=None)¶
Wraps up either PIL or Java to get data from bitmaps
- getRGBData()¶
Return byte array of RGB data as string
- identity()¶
try to return information that will identify the instance
- reportlab.lib.utils.annotateException(msg, enc='utf8')¶
add msg to the args of an existing exception
- 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'])) ['a', 'b', 'c'] >>> commasplit((commajoin(['a,', ' b ', 'c'])) ['a,', 'b', 'c'] >>> commasplit((commajoin(['a ', ',b', 'c'])) ['a', ',b', '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('a,b,c') ['a', 'b', 'c'] >>> commasplit('a,, , b , c ') ['a,', 'b', 'c'] >>> commasplit('a, ,,b, c') ['a', ',b', 'c']
- 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.fileName2Utf8(fn)¶
attempt to convert a filename to utf8
- 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.getImageData(imageFileName)¶
Get width, height and RGB pixels from image file. Wraps Java/PIL
- reportlab.lib.utils.getStringIO(buf=None)¶
unified StringIO instance interface
- 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.isSourceDistro()¶
return truth if a source file system distribution
- reportlab.lib.utils.open_for_read(name, mode='b', urlopen=<function urlopen at 0x2429cf8>)¶
attempt to open a file or URL for reading
- 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.recursiveGetAttr(obj, name)¶
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