Reputation: 21
How do you output all images in a directory to the same pdf output using fpdf. I can get the last file in the folder to output as a pdf or output multiple pdfs for each image, but not all images in the same pdf like a catalog. I'm sure it is the for loop but can't sort it out properly.
from fpdf import FPDF
from PIL import Image
import glob
import os
# set here
image_directory = '/home/User/Desktop/images/'
extensions = ('*.jpg','*.jpeg','*.png','*.gif')
# set 0 if you want to fit pdf to image
# unit : pt
margin = 10
imagelist=[]
for ext in extensions:
imagelist.extend(glob.glob(os.path.join(image_directory,ext)))
pdf = FPDF(unit="pt", format=[width + 2*margin, height + 2*margin])
pdf.add_page()
cover = Image.open(imagePath)
width, height = cover.size
for imagePath in imagelist:
pdf.image(imagePath, margin, margin)
destination = os.path.splitext(imagePath)[0]
pdf.output(destination + ".pdf", "F")
Upvotes: 1
Views: 5808
Reputation: 21
You will have to start a new page for every picture in the beginning of the for loop and end with writing everything to the PDF.
pdf = FPDF()
imagefiles = ["test1.png","test2.png"]
for one_image in imagefiles:
pdf.add_page()
pdf.image(one_image,x,y,w,h)
pdf.output("out.pdf")
Upvotes: 0
Reputation: 21
Still not sure why fpdf was not grouping the iteration of image files as a single PDF output but img2pdf accepted a list of file names worked very nicely.
import img2pdf
imagefiles = ["test1.jpg", "test2.png"]
with open("images.pdf","wb") as f:
f.write(img2pdf.convert(imagefiles))
Upvotes: 1