1
from pdf2image import convert_from_path
images = convert_from_path('path.pdf',poppler_path=r"E:/software/poppler-0.67.0/bin")
for i in range(len(images)):
        images[i].save('image_name'+ str(i) +'.jpg', 'JPEG')

But now I want to convert more than 100 pdf files into images. Is there any way? Thanks in advance.

jtlz2
  • 7,700
  • 9
  • 64
  • 114
techMayu
  • 31
  • 8

2 Answers2

2

You can use glob to 'glob' the file names into a list: Python glob is here https://docs.python.org/3/library/glob.html - but it's a general expression for using wildcard expansion in the (*nix) filesystem [https://en.wikipedia.org/wiki/Glob_(programming)]. I assume it works under windows :)

Then you just loop over the files. Hey presto!

import glob
from pdf2image import convert_from_path

poppler_path = r"E:/software/poppler-0.67.0/bin"

pdf_filenames = glob.glob('/path/to/image_dir/*.pdf')

for pdf_filename in pdf_filenames:
    images = convert_from_path(pdf_filename, poppler_path=poppler_path)
    for i in range(len(images)):
        images[i].save(f"{pdf_filename}{i}.jpg", 'JPEG')

!TIP: f"{pdf_filename}{i}.jpg" is a python f-string which gives a the reader a better idea of what the string will look like eventually. You might want to zero pad the integers there, because at some point you might want to 'glob' those or some such. There are lots of ways to achieve that - see How to pad zeroes to a string? for example.

jtlz2
  • 7,700
  • 9
  • 64
  • 114
0

You will possibly need to use the os module.

First step:

  • Use the os.listdir function like this
 os.listdir(path to folder containing pdf files)

to get a list of paths within that folder.

To be more specific the os.isfile() to check if the current path is a file or a folder .

  • Perform the conversion if the path lead to a file like this.
images = convert_from_path('path.pdf',poppler_path=r"E:/software/poppler-0.67.0/bin")
for i in range(len(images)):
        images[i].save('image_name'+ str(i) +'.jpg', 'JPEG')

Otherwise use recursion to traverse the folder even more. Here's a link to a repo where I recursively resized images in a folder . It could be useful to digest this idea. Link to a recursive resizing of images in a given path.