import os
from pdf2image import convert_from_path

# Define the path where your PDFs are stored
pdf_folder_path = 'input'
# Define the path where you want the images to be saved
output_folder_path = 'output'

def convert_pdf_to_images(pdf_path, output_folder):
    # Convert PDF to images
    images = convert_from_path(pdf_path)
    pdf_name = os.path.basename(pdf_path).replace('.pdf', '')

    # Create a folder for each PDF file based on its name
    pdf_output_path = os.path.join(output_folder, pdf_name)
    os.makedirs(pdf_output_path, exist_ok=True)

    # Save each image as a PNG file
    for i, image in enumerate(images, start=1):
        image_path = os.path.join(pdf_output_path, f"{i}.png")
        image.save(image_path, 'PNG')
        print(f"Saved: {image_path}")

def batch_convert_pdfs(pdf_folder, output_folder):
    # Iterate through all files in the pdf_folder
    for filename in os.listdir(pdf_folder):
        if filename.endswith('.pdf'):
            pdf_path = os.path.join(pdf_folder, filename)
            print(f"Converting: {pdf_path}")
            convert_pdf_to_images(pdf_path, output_folder)

# Call the batch conversion function
batch_convert_pdfs(pdf_folder_path, output_folder_path)
