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. 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

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.ColorType

alias of reportlab.lib.colors.Color

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

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.opaqueColor(c)

utility to check we have a color that’s not fully transparent

reportlab.lib.colors.parseColorClassFromString(arg)

Parses known classes which holds color information from string and constructs respective object. It constructs CMYKColor, PCMYKColor, CMYKColorSep and PCMYKColorSep now.

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.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:

  1. To record error data:

    dbg = DebugMemo(fn='dbgmemo.dbg',myVar=value)
    dbg.add(anotherPayload='aaaa',andagain='bbb')
    dbg.dump()
    
  2. To show the recorded info:

    dbg = DebugMemo(fn='dbgmemo.dbg',mode='r')
    dbg.load()
    dbg.show()
    
  3. 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.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

getRGBData()

Return byte array of RGB data as string

identity()

try to return information that will identify the instance

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.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.escapeOnce(data)

Ensure XML output is escaped just once, irrespective of input

>>> escapeOnce('A & B')
'A &amp; B'
>>> escapeOnce('C &amp; D')
'C &amp; D'
>>> escapeOnce('E &amp;amp; F')
'E &amp; F'
reportlab.lib.utils.escapeTextOnce(text)

Escapes once only

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 PIL

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.makeFileName(s)

force filename strings to unicode so python can handle encoding stuff

reportlab.lib.utils.open_for_read(name, mode='b')

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.rawBytes(s)

converts first 256 unicodes 1-1

reportlab.lib.utils.rawUnicode(s)

converts first 256 unicodes 1-1

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.yieldNoneSplits(L)

yield sublists of L separated by None; the Nones disappear