How to have an auto page break for pyfpdf when the image exceeds the page dimensions?

764 Views Asked by At

I looked at a similar question here but there doesn't seem to be a solution except to switch to a different library.

I have created some code to automatically space my images vertically and horizontally, but I am having a problem with auto page breaks when the image inserted is larger than the page (since the image will get cut off).

def generate_pdf_report(start_height):
    name = "PDF"
    page_width = 210
    page_height = 297
    object_margins = 10
    objects_per_row = 1
    objects_in_path = 6 ##SAMPLE VARIABLE
    total_margins = object_margins * (objects_per_row + 1)
    object_width = (page_width - total_margins)/objects_per_row

    pdf = FPDF()
    pdf.add_page()

    pdf.set_font('Arial', 'B', 16)

    object_counter = 0
    height_position = start_height
    for item in range(objects_in_path):
        object_counter += 1
        position = object_counter % objects_per_row
        if position == 0:
            start_position = object_width * (objects_per_row - 1) + object_margins * objects_per_row
            pdf.image("test_image.jpg", x=start_position, y=height_position, w=object_width)
            height_position += start_height + object_margins
        else:
            start_position = object_width * (position - 1) + object_margins * position
            pdf.image("test_image.jpg", x=start_position, y=height_position, w=object_width)

    pdf.output('test_pdf.pdf')

Is there some kind of way to return the dimensions of each image inserted using pdf.image()? Since I set the width of the image, the height is automatically scaled by default. So currently I have to actually manually set the start_height parameter of the function depending on the resulting height of the image--else it can overlap or have too large a gap. Since I don't have the image height to adequately space the images or skip to the next page

There is one solution I can think of which is to measure the image outside the pyfpdf package and determine the width-height ratio of the image so I can determine the height of the final image. But I think there should be a better and easier way?

0

There are 0 best solutions below