Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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` from120to, say, 150to 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 -> ^^^^^  ^^^^

Solution 2:

disclaimer: I am the author of pText the library I will use in this solution.

Let's start by creating an empty Document:

pdf: Document = Document()# create empty pagepage: Page = Page()# add page to document
pdf.append_page(page)

Next we are going to load an Image using Pillow

import requests
from PIL import Image as PILImage

im = PILImage.open(
        requests.get(
            "https://365psd.com/images/listing/fbe/ups-logo-49752.jpg", stream=True
        ).raw
    )

Now we can create a LayoutElementImage and use its layout method

Image(im).layout(
        page,
        bounding_box=Rectangle(Decimal(20), Decimal(724), Decimal(64), Decimal(64)),
    )

Keep in mind the origin (in PDF space) is at the lower left corner.

Lastly, we need to store the Document

# attempt to store PDFwithopen("output.pdf", "wb") as out_file_handle:
    PDF.dumps(out_file_handle, pdf)

You can obtain pText either on GitHub, or using PyPi There are a ton more examples, check them out to find out more about working with images.

Solution 3:

You can check pdfme library. It's the most powerful library in python to create PDF documents. You can add urls, footnotes, headers and footers, tables, anything you would need in a PDF document.

The only problem I see is that currently pdfme only supports jpg format for images. But if that's not a problem it will help you with your task.

Check the docs here.

Post a Comment for "Create Pdf With Fpdf In Python. Can Not Move Image To The Right In A Loop"