3

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'
maximusdooku
  • 5,242
  • 10
  • 54
  • 94

1 Answers1

3

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")
  • Done. Not working yet. Please see the error message. – maximusdooku Mar 18 '17 at 22:22
  • Ah. Thank you very much for the edit. It works now. But the images are cutoff and I am not getting the full image as PDF. Am I using wrong dimensions? The images are 1924 × 2972 – maximusdooku Mar 18 '17 at 22:33
  • I'm not totally sure, I would recommend reading the [docs](https://pyfpdf.readthedocs.io/en/latest/reference/image/index.html). How did you come up with the [10,210,297] numbers you're passing to pdf.image()? – Jonathan Ellington Mar 18 '17 at 22:49
  • Still trying to figure out stuff. I took at A4 values from here. Not sure whwat 10 is. I just put in a random value. http://stackoverflow.com/questions/27327513/create-pdf-from-a-list-of-images – maximusdooku Mar 18 '17 at 22:54
  • Try with no arguments, ie pdf.image(image) -- based on the [doc](https://pyfpdf.readthedocs.io/en/latest/reference/image/index.html), the defaults look sensible – Jonathan Ellington Mar 18 '17 at 22:56
  • The doc for image() specifies the ways the size can be specified. Your best bet is to explicitly specify a single dimension, and the other will scale accordingly: pdf.image(image, w=150) Play with that number until you get what you like. Otherwise if you dig in the docs I'm sure you'll find a way to make it stretch the entire page. – Jonathan Ellington Mar 18 '17 at 23:10