Reputation: 1308
I am trying to generate an pdf using Reportlab. It is acceptably easy. I have a function like the one below that returns the image and I just add it to the document.
def create_logo(bsolute_path):
image = Image(absolute_path)
image.drawHeight = 1 * inch
image.drawWidth = 2 * inch
return [image]
It works but not as I want it to. The problem I have is that it rescales my image. E.g. If i have an image 3000px(width) x 1000px (height) which has a scale 1 to 3, i get in the pdf a rescaled image: 1 to 2.
What i basically want is to just specify the maximum width and height and let reportlab resize it (not rescale it), if the image is too big.
Can this be done in Reportlab or should I do that myself?
Thanks!
Upvotes: 3
Views: 8611
Reputation: 11
Although my answer is too late for you but for somebody else with same problem. Your problem of image scaling can be solved by knowing the dpi of the image. I had an image of 59x19 pixels that i wanted to paste on the pdf. How i did it successfuly is as below.
from reportlab .pdfgen import canvas
from reportlab.lib.utils import ImageReader
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import mm
xloc=10
yloc=10
c=canvas.Canvas(pdfPath,pagesize=A4) # put you pdf path here
c.draw(image, xloc,yloc,15*mm,5*mm)
Now A 59px at 96dpi in mm translates to 15mm similarly 19px at 96dpi will be 5mm. see https://www.pixelto.net/px-to-mm-converter. This will preserve your aspect ratio. Also i observed somthing strange. 59px actually come out to be 15.610416667mm but if i use the decimal part too the image is blur.
Upvotes: 0
Reputation: 439
You can set preserveAspectRatio=True
. So proportions should be 1:3 as expected.
drawImage(image, x, y, width=None, height=None, mask=None, preserveAspectRatio=True, anchor='c')
You can add scale factor as a constant.
Hope this helps.
Upvotes: 3
Reputation: 10172
This worked for me:
image = Image(absolute_path,width=2*inch,height=1*inch,kind='proportional')
Upvotes: 5
Reputation: 1308
I found this also :
Image aspect ratio using Reportlab in Python
but in the end i used this method :
def create_logo(absolute_path):
image = Image(absolute_path)
image._restrictSize(2 * inch, 1 * inch)
Upvotes: 4