[reportlab-users] getRGBdata

Robin Becker reportlab-users@reportlab.com
Thu, 15 Apr 2004 17:43:04 +0100

Ulrich Wisser wrote:

> Hello,
> could please someone point out how to put a graphic in the header of my 
> first page? Please find my code below. I tried with several diffrent jpg 
> and gif and png graphic files. I always do get the same error:
>   File "/home/zope/lib/python2.1/reportlab/pdfgen/canvas.py", line 586,
>   in drawImage
>     rawdata = image.getRGBData()
>   AttributeError: PDFImage instance has no attribute 'getRGBData'
> Please replace PDFImage with Image or PIL_Image.  Just in case it 
> matters, this is a Zope External Script.

NIL desperandum.

I ran this script and it works for me, but it needs to be massaged into your way 
of doing things. The main change is not to use a PDFImage object, but reference 
the file name directly. The Canvas.drawImage method can accept strings 
(filenames) or an ImageReader object. The ImageReader class is defined in 
reportlab/lib/utils. The ImageReader object can be initialised with a filename 
or a filelike object. The intention is to allow us to use either jython +java.IO 
or python+PIL to get access to the guts of an image.

from reportlab.platypus.paragraph import Paragraph
from reportlab.platypus.tables import Table
from reportlab.platypus.doctemplate import *
from reportlab.platypus import Flowable, PageBreak, Image
from reportlab.lib.units import inch, cm
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet
from PIL import Image as PIL_Image
from reportlab.pdfgen.pdfimages import PDFImage
from reportlab.pdfgen import canvas
import cStringIO

def putLogo(canvas, doc):
doc.pagesize[0]-5*cm, doc.pagesize[1] - 3*cm, width=4*cm, height=2*cm)

report = cStringIO.StringIO ()
document = SimpleDocTemplate(report, pagesize=A4)
styles = getSampleStyleSheet()
style = styles["Normal"]
text = Paragraph("Hello World", style)
document.build([text], onFirstPage=putLogo)

Robin Becker