pythonfpdf

create pdf with fpdf in python. can not move image to the right in a loop


I use FPDF to generate a pdf with python. i have a problem for which i am looking for a solution. in a folder "images", there are pictures that I would like to display each on ONE page. I did that - maybe not elegant. unfortunately i can't move the picture to the right. it looks like pdf_set_y won't work in the loop.

from fpdf import FPDF

from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir('../images') if isfile(join('../images', f))]


pdf = FPDF('L')
pdf.add_page()
pdf.set_font('Arial', 'B', 16)

onlyfiles = ['VI 1.png', 'VI 2.png', 'VI 3.png']
y = 10

for image in onlyfiles:
    pdf.set_x(10)
    pdf.set_y(y)
    pdf.cell(10, 10, 'please help me' + image, 0, 0, 'L')
    y = y + 210 #to got to the next page

    pdf.set_x(120)
    pdf.set_y(50)
    pdf.image('../images/' + image, w=pdf.w/2.0, h=pdf.h/2.0)

pdf.output('problem.pdf', 'F')

Would be great if you have a solution/help for me. Thanks alot greets alex


Solution

  • I see the issue. You want to specify the x and y location in the call to pdf.image(). That assessment is based on the documentation for image here: https://pyfpdf.readthedocs.io/en/latest/reference/image/index.html

    So you can instead do this (just showing for loop here):

    for image in onlyfiles:
        pdf.set_x(10)
        pdf.set_y(y)
        pdf.cell(10, 10, 'please help me' + image, 0, 0, 'L')
        y = y + 210 # to go to the next page
    
        # increase `x` from 120 to, say, 150 to move the image to the right
        pdf.image('../images/' + image, x=120, y=50, w=pdf.w/2.0, h=pdf.h/2.0)
        #                        new -> ^^^^^  ^^^^