Convert PDFS to JPEGS and move the converted jpegs to their respective subfolders

Viewed 37

I wanted to convert all my pdfs to jpegs from a parent directory(has 2 or 3 sub-folders) and place the converted jpegs in the respective sub-folders from where they were picked for conversion.

Below is my code i used for converting pdfs to jpegs.

data_dir_1 = pathlib.Path("C:/Users/parent_directory/")

for root, dirs, files in os.walk(data_dir_1, "*.pdf"):
    for file in files:
        if file.endswith(".pdf"):
            # print(file)
            print(os.path.join(root, file))
            pages = convert_from_path(os.path.join(root, file), 500)
            for page in pages:
                page.save(file + ".jpg", "JPEG")

Could someone please help with a way how I can move them to their respective sub-folders from where they were picked?

1 Answers

As per pdf2image documentation, convert_from_path accepts an "output_folder" parameter.

So, I would suggest trying like this:

import os
import pathlib

from pdf2image import convert_from_path

data_dir_1 = pathlib.Path("C:/Users/parent_directory/")

for root, dirs, files in os.walk(data_dir_1, "*.pdf"):
    for file in files:
        if file.endswith(".pdf"):
            images = convert_from_path(
                pdf_path=os.path.join(root, file), dpi=500, output_folder=root
            )
Related