I wanted to specify a folder containing multiple jpeg files and convert it to one pdf file, so I wrote the following code in Python, but only one jpeg file in the folder was converted to pdf.
I'd appreciate it if you could point out what's wrong.
import img2pdf,os
from PIL import Image
base_Image=r "Path of file containing jpeg"
Create_pdf=r "Path where you want to put the pdf you made"
os.chdir(base_Image)
path="./"
files=os.listdir(path)
pdf_name = Create_pdf+"\\"+"converted"+".pdf"
for i in files:
if i.endswith(".jpeg"):
Image_Name=i
img=Image.open(Image_Name)
cov_pdf=img2pdf.convert(Image_Name)
file=open(pdf_name, "wb")
file.write(cov_pdf)
img.close()
file.close()
file=open(pdf_name, "wb")
processing new pdf every time an image is loaded, it seems that a pdf file containing only the last image is created.
You can create a file that combines multiple images into a single pdf using the sample code below.(Check python 3.6.1)
sample code
import img2pdf
importos
import re
from PIL import Image
from pathlib import Path
base_Image=r "Path of file containing jpeg"
Create_pdf=r "Path where you want to put the pdf you made"
path=Path(base_Image)
images=sorted ([str(p) for pin path.glob('**/*') if re.search('/*\.(jpg|jpeg)', str(p), re.IGNORECASE)])
pdf_name = os.path.join(Create_pdf, "converted.pdf")
with open(pdf_name, "wb") asf:
f.write(img2pdf.convert(images))
© 2024 OneMinuteCode. All rights reserved.