I'm an newbie and I'm trying to create a multipage pdf with img2pdf (recursive), but only the last picture is saved in a pdf file.
from pathlib import Path
import os
import img2pdf
main_dir = Path(Path.cwd(),'MAIN')
for subfolder in main_dir.iterdir():
if subfolder.is_file():
continue
for filename in subfolder.iterdir():
#pdf as foldername
pdf_name = os.path.basename(subfolder)
#write image-file to pdf file
with open(pdf_name+".pdf", "wb") as f:
f.write(img2pdf.convert(str(filename)))
When I test it with print(filename) all images are going through the loop.
Maybe someone can tell me where my misconception is.
img2pdf
module can directly take a list of image file names as an argument and converts them into pdf. Take a look at the documentation here
from pathlib import Path
import os
import img2pdf
main_dir = Path(Path.cwd(),'your/path/to/images/folder')
for subfolder in main_dir.iterdir():
imgs = []
if subfolder.is_file():
continue
for filename in subfolder.iterdir():
imgs.append(os.path.join(subfolder, filename))
pdf_name = os.path.basename(subfolder)
with open(pdf_name+".pdf", "wb") as f:
f.write(img2pdf.convert(imgs))