Description

This script can be placed in a folder and when it runs, it converts all pdfs to pngs. If the pdf is a one-pager, the png has the same filename. If the pdf has multiple pages, the output pngs receive a suffix with the page number.

Before running, the library pdf2image must be installed:

pip install pdf2image

Code

import os
from pdf2image import convert_from_path
 
def pdf_to_png(input_folder):
    # Get all PDF files in the folder
    pdf_files = [f for f in os.listdir(input_folder) if f.lower().endswith('.pdf')]
    
    # Iterate over each PDF file
    for pdf_file in pdf_files:
        pdf_path = os.path.join(input_folder, pdf_file)
        # Convert PDF pages to images
        images = convert_from_path(pdf_path)
        
        # Base name for the output files (without extension)
        base_name = os.path.splitext(pdf_file)[0]
        
        # Check the number of pages and save accordingly
        if len(images) == 1:
            # If single page, save with the original name as .png
            output_name = f"{base_name}.png"
            output_path = os.path.join(input_folder, output_name)
            images[0].save(output_path, 'PNG')
            print(f"Single-page PDF '{pdf_file}' converted to '{output_name}'")
        else:
            # For multi-page PDFs, save each page with '-page_number' format
            for i, page in enumerate(images):
                output_name = f"{base_name}-{i+1}.png"
                output_path = os.path.join(input_folder, output_name)
                page.save(output_path, 'PNG')
                print(f"Page {i+1} of file '{pdf_file}' converted to '{output_name}'")
 
if __name__ == "__main__":
    # Current working directory where the script is located
    current_folder = os.path.dirname(os.path.abspath(__file__))
    pdf_to_png(current_folder)