pythonreportlab

Reportlab canvas.DrawImage resizing not working


I'd like to add a logo to to the canvas so that it repeats with each page of a report, but the problem is that the PNG image is quite large. I've tried resizing it inside the canvas.DrawImage command, but each time the image comes back in its original size.

Here is what I am trying, but it has no effect:

def on_page(canvas, doc, pagesize=A4):
    page_num = canvas.getPageNumber()
    image = Image('/opt/rspro/home/e8409/projects/CRAMM logo.png')
    image._restrictSize(1 * inch, 2 * inch)
    canvas.drawImage(image, 0,0)
    canvas.showPage()

from reportlab.platypus import PageTemplate

portrait_template = PageTemplate(
  id='portrait', 
  frames=portrait_frame,
  onPage=on_page, 
  pagesize=A4)


from reportlab.platypus import BaseDocTemplate

doc = BaseDocTemplate(
  'report.pdf',
  pageTemplates=[
    portrait_template
  ]
)


Appreciate any assistance -- I'd rather not have to write a bunch of separate code to resize the image separate from the reportlab command.


Solution

  • When using drawImage method, you need to provide width and height:

    from reportlab.lib.utils import ImageReader
    
    image_path = '/opt/rspro/home/e8409/projects/CRAMM logo.png'
    img = ImageReader(image_path)
    img_width, img_height = img.getSize()
    canvas.drawImage(image_path, 0, 0, width=desired_width, height=desired_height, preserveAspectRatio=True)