Create PDF from a list of images
Install FPDF for Python:
pip install fpdf
Now you can use the same logic:
from fpdf import FPDFpdf = FPDF()# imagelist is the list with all image filenamesfor image in imagelist: pdf.add_page() pdf.image(image,x,y,w,h)pdf.output("yourfile.pdf", "F")
You can find more info at the tutorial page or the official documentation.
The best method to convert multiple images to PDF I have tried so far is to use PIL
purely. It's quite simple yet powerful:
from PIL import Imageim1 = Image.open("/Users/apple/Desktop/bbd.jpg")im2 = Image.open("/Users/apple/Desktop/bbd1.jpg")im3 = Image.open("/Users/apple/Desktop/bbd2.jpg")im_list = [im2,im3]pdf1_filename = "/Users/apple/Desktop/bbd1.pdf"im1.save(pdf1_filename, "PDF" ,resolution=100.0, save_all=True, append_images=im_list)
Just set save_all
to True
and append_images
to the list of images which you want to add.
You might encounter the AttributeError: 'JpegImageFile' object has no attribute 'encoderinfo'
. The solution is here Error while saving multiple JPEGs as a multi-page PDF
Note:Install the newest PIL
to make sure save_all
argument is available for PDF.
If you use Python 3, you can use the python module img2pdf
install it using pip3 install img2pdf
and then you can use it in a scriptusing import img2pdf
sample code
import osimport img2pdfwith open("output.pdf", "wb") as f: f.write(img2pdf.convert([i for i in os.listdir('path/to/imageDir') if i.endswith(".jpg")]))
or (If you get any error with previous approach due to some path issue)
# convert all files matching a globimport globwith open("name.pdf","wb") as f: f.write(img2pdf.convert(glob.glob("/path/to/*.jpg")))