# package reportlab.pdfgen

The basics

## module 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()

  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

  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)

    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)

    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)

    Draws a string right-aligned with the x coordinate

  drawString(x, y, text, mode=None, charSpace=0, direction=None, wordSpace=None)

    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.

  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.

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

  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

  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.

  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.

  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

  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.

  setViewerPreference(pref, value)

    set one of the allowed enbtries in the documents viewer preferences

  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.

  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!