Issue
I have generated a report in python that looks similar to the one below that I've taken from this tutorial.
While this page is easy to set up if you manually enter the path to each image, like this:
pdf.add_page()
pdf.image("/Users/Foo/Graph1.png", 5, 20, WIDTH/2-10)
pdf.image("/Users/Foo/Graph2.png", WIDTH/2, 20, WIDTH/2-10)
pdf.image("/Users/Foo/Graph3.png", 5, 110, WIDTH/2-10)
pdf.image("/Users/Foo/Graph4.png", WIDTH/2, 110, WIDTH/2-10)
pdf.image("/Users/Foo/Graph5.png", 5, 200, WIDTH/2-10)
pdf.image("/Users/Foo/Graph6.png", WIDTH/2, 200, WIDTH/2-10)
The above code will not work if the directory does not always have the same number of png files in it.
I started writing the function as below, but need help with the part that comes after it.
def addtopage(function):
for f in os.listdir('path'):
if f.endswith('png') in f:
#add it to the next position in the pdf
My question is, how can I create a for loop that will automatically loop through the folder, grab every .png in the folder, and place them into the next position on a pdf page with the format in the image above?
Thank you!
Solution
You could try something like:
def addtopage(function):
png_count = 0
start_y = 20
img_ht = 90
for f in os.listdir('path'):
if f.endswith('png') in f:
if png_count%2 == 0
pdf.image(f, 5, start_y, WIDTH/2-10)
else:
pdf.image(f, WIDTH/2-10, start_y, WIDTH/2-10)
start_y += img_ht
png_count += 1
if png_count%6 == 0:
pdf.add_page()
You could still improve this code and have some more variables that will allow for more flexibility, but this should give a good boilerplate for the same. Also, if you are using ppyfpdf, I would suggest taking a look at fpdf2. It is a fork from PyFPDF itself and is being actively maintained (PyFPDF received its last commit in 2018).
Answered By - veedata
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.