Showing posts with label PDF Generator. Show all posts
Showing posts with label PDF Generator. Show all posts

Image to PDF Converter in Python – Simple Project for Beginners

← Back to Projects

Image to PDF Converter Project in Python

About the project: This is a Python project for an Image to PDF Converter.

This program will take one or more image files (JPEG, PNG, etc.) from a specified directory and combine them into a single PDF document.

To use this program, you'll need to install the Pillow library, which is used for image manipulation.

You can install it with following command:


pip install Pillow

This Python script is a complete and interactive tool. When you run it, you'll be prompted to enter a folder path containing images and a name for the output PDF. The program will then handle the conversion for you.

Project Level: For Beginner

You can use green copy button to directly copy the below snippet code, paste it and run the code in any Python editor you have in your system.

Steps to follow:

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with any filename and .py extension.

Step 4: Run (Press F5 if using python IDLE)


# image_to_pdf_converter.py

import os
from PIL import Image

def convert_images_to_pdf(image_folder, output_pdf):
    """
    Converts all images in a specified folder to a single PDF.

    Args:
        image_folder (str): The path to the folder containing image files.
        output_pdf (str): The filename for the output PDF.
    """
    try:
        image_list = []
        # Get all image files from the directory
        for filename in sorted(os.listdir(image_folder)):
            if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
                filepath = os.path.join(image_folder, filename)
                try:
                    img = Image.open(filepath).convert('RGB')
                    image_list.append(img)
                except Exception as e:
                    print(f"Error opening image file {filename}: {e}")
                    
        if not image_list:
            print("No image files found in the specified directory.")
            return

        # Save the first image, and append the rest to it as additional pages
        first_image = image_list[0]
        rest_of_images = image_list[1:]

        # Ensure the output filename has a .pdf extension
        if not output_pdf.lower().endswith('.pdf'):
            output_pdf += '.pdf'
        
        first_image.save(output_pdf, "PDF", resolution=100.0, save_all=True, append_images=rest_of_images)
        print(f"\nSuccessfully created '{output_pdf}' with {len(image_list)} images.")

    except FileNotFoundError:
        print(f"Error: The directory '{image_folder}' was not found.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

def main():
    """
    Main function to run the Image to PDF Converter.
    """
    print("--- Python Image to PDF Converter ---")
    
    # Get the directory from the user
    image_folder = input("Enter the path to the folder with your images: ").strip()
    
    # Get the desired output filename
    output_pdf = input("Enter the name for the output PDF file (e.g., my_document.pdf): ").strip()
    
    if image_folder and output_pdf:
        convert_images_to_pdf(image_folder, output_pdf)
    else:
        print("Invalid input. Please provide both a folder path and an output filename.")

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()

The above code snippet code is a direct copy-paste code that will run in editors with python. This is much easier to test your code and you can change the code to customize the values.



💬 Challenge: Can you extend this to batch convert subfolders too? Let us know in the comments!


← Back to Projects


Featured Post

Indexing in SQL and NoSQL: Improve Database Performance with Simple Tips

  🔷 Part 8: Indexing and Query Optimization in SQL and NoSQL This post will introduce the basics of indexing in both  SQL  and  MongoDB ,...

Popular Posts