Reputation: 5512
I have a few 1924 × 2972 JPG files in a folder (/img/). I want to 1) Convert them to PDFs and 2) Combine them into a single PDF. But I am not successful. I am new to python. Please let me know how I can proceed.
from PIL import Image
import glob
from fpdf import FPDF #
imagelist = []
for filename in glob.glob('img/*.jpg'): #assuming jpg
im=Image.open(filename)
imagelist.append(im)
pdf = FPDF()
# imagelist is the list with all image filenames
for image in imagelist:
pdf.add_page()
pdf.image(image, 10,210,297)
pdf.output("yourfile.pdf", "F")
Error:
File "<ipython-input-39-9fb5b6258b5e>", line 1, in <module>
pdf.image(image, 10,210,297)
File "/Users/xyz/anaconda/lib/python3.6/site-packages/fpdf/fpdf.py", line 150, in wrapper
return fn(self, *args, **kwargs)
File "/Users/xyz/anaconda/lib/python3.6/site-packages/fpdf/fpdf.py", line 960, in image
if not name in self.images:
TypeError: unhashable type: 'JpegImageFile'
Upvotes: 3
Views: 10255
Reputation: 1
i resolve this problem with fpdf2
pip install fpdf2
from fpdf import FPDF
pdf = FPDF(unit="pt", format="A4")
pdf.image(#path image , x, y, width, height)
I encountered this problem initially because I just installed fpdf, which this library probably no longer supports.
Upvotes: 0
Reputation: 126
In your second loop, you need to actually reference the path to each jpg:
pdf.image(image, 10,210,297)
Edit: additionally, I think you just need the path to each image (rather than opening each image using Image.open
. Try the following:
import glob
from fpdf import FPDF #
imagelist = glob.glob('img/*.jpg')
pdf = FPDF()
# imagelist is the list with all image filenames
for image in imagelist:
pdf.add_page()
pdf.image(image, 10,210,297)
pdf.output("yourfile.pdf", "F")
Upvotes: 3