Skip to content

Latest commit

 

History

History
75 lines (47 loc) · 1.83 KB

reportlab-images-ipython.rst

File metadata and controls

75 lines (47 loc) · 1.83 KB

Reportlab Images in IPython

tags:Python, IPython
category:Software
Author: Trevor
Date: 2015-01-01

With a bit of work we can get IPython to render ReportLab objects directly to the page as Matplotlib plots.

Huge thanks to github user deeplook, this is basically a modification of this IPython notebook.

First our imports.

from reportlab.lib import colors
from reportlab.graphics import renderPM
from reportlab.graphics.shapes import Drawing, Rect
from reportlab.graphics.charts.linecharts import HorizontalLineChart
from io import BytesIO
from IPython.core import display

Now we create a hook that causes reportlab drawings to actually be rendered when we type out its name.

def display_reportlab_drawing(drawing):
    buff=BytesIO()
    renderPM.drawToFile(drawing,buff,fmt='png',dpi=72)
    data=buff.getvalue()
    ip_img=display.Image(data=data,format='png',embed=True)
    return ip_img._repr_png_()
png_formatter=get_ipython().display_formatter.formatters['image/png']
drd=png_formatter.for_type(Drawing,display_reportlab_drawing)

Now that's done, we can start creating ReportLab objects and see them immediately.

drawing = Drawing(150,100)
drawing.add(Rect(0,0,150,100,strokeColor=colors.black,fillColor=colors.antiquewhite))
drawing

reportlab-images-ipython_files/reportlab-images-ipython_8_0.png

chart=HorizontalLineChart()
drawing.add(chart)
drawing

reportlab-images-ipython_files/reportlab-images-ipython_11_0.png