How to convert images to PDF in Python
Tkinter, Pillow and ReportLab . Modules
Tkinter is the standard GUI library for Python. It provides a wide range of widgets such as buttons, stickers, and text boxes that make app development like playing music or converting text easy. To install Tkinter in your system, open a terminal and type:
pip install tkinter
The Pillow module is a powerful Python image library that makes it easy to perform image operations such as resizing, cropping, and filtering. Integrating it with OpenAI API and DALL·E 2, you can create photos with text prompts.
To install Pillow, run this command:
pip install Pillow
ReportLab is an open source Python library for creating PDFs and graphics. It has various tools for you to use to create documents with pictures, text and tables. They are useful for programmatically generating reports. As a result, you can build company reports, invoices and certificates, and add a watermark logo in text. To install ReportLab:
pip install reportlab
Define the structure of the image to PDF converter
Import the required modules and create a class named ImageToPDFConverter. Define a constructor to create the class and take the native Tkinter window object as an argument. Initializes an empty list to store the path of the images selected by the user. Set the title and size of the application. Create two buttons named Select Images and Convert to PDF.
Switch the window into which you want to place the button, the content on the button will be visible. It's the command the button will execute when clicked and the font format the button will apply. Arrange the buttons using pack() method & give them a padding of 10 vertically.
import tkinter as tk from tkinter import filedialog, messagebox from PIL import Image, ImageTk from reportlab.lib.pagesizes import landscape from reportlab.pdfgen import canvas class ImageToPDFConverter: def __init__(self, root): self.root = root self.image_paths = [] self.root.title("Image to PDF Converter") self.root.geometry("750x600") self.select_images_button = tk.Button(self.root, text="Select Images", command=self.select_images, font=("Helvetica", 12),) self.select_images_button.pack(pady=10) self.convert_to_pdf_button = tk.Button(self.root, text="Convert to PDF", command=self.convert_to_pdf,font=("Helvetica", 12),) self.convert_to_pdf_button.pack(pady=10)
Define a label by switching it to the main window to place the label in, the content on it to display, the label font format to use, and a vertical padding of 10 (pixels).
Similarly, define a frame to preview the selected image and set its main window, width and height. Arrange it with a padding of 10.
self.select_images_label = tk.Label(self.root, text="Select Images", font=("Helvetica", 14)) self.select_images_label.pack(pady=10) self.preview_frame = tk.Frame(self.root, width=380, height=200) self.preview_frame.pack(pady=10)
Select a photo and create a preview window
Define a method, select_images() . Use Tkinter's filedialog class to open a select multiple images dialog and store them in the images_path list . Switch to the initial directory in which the dialog will open, the title to display, and the file type that the dialog box allows for selection.
Defines a loop that repeats over all paths of the image the user has selected. Use Pillow's open() method to open the image file and pass the maximum size required to the resize method. Convert this PIL image to a Tkinter compatible PhotoImage. Create a label inside the preview pane you did earlier and display the image. Use the grid manager to arrange the images in a three-column grid layout.
def select_images(self): self.image_paths = filedialog.askopenfilenames(initialdir="/", title="Select Images", filetypes=(("Image Files", "*.jpg *.png"),)) for i, image_path in enumerate(self.image_paths): image = Image.open(image_path) image = self.resize_image(image, width=150, height=150) photo = ImageTk.PhotoImage(image) label = tk.Label(self.preview_frame, image=photo) label.image = photo label.grid(row=i // 3, column=i % 3, padx=10, pady=10)
Define a method, resize_image() to resize the image, including the size of the image and the maximum size you defined earlier. Calculate the aspect ratio and use it to set the new width and height. Use PIL's resize method to resize the image keeping the same aspect ratio. Use bilinear interpolation to resample for smoother results.
def resize_image(self, image, width, height): aspect_ratio = min(width / float(image.size[0]), height / float(image.size[1])) new_width = int(aspect_ratio * image.size[0]) new_height = int(aspect_ratio * image.size[1]) resized_image = image.resize((new_width, new_height), resample=Image.Resampling.BILINEAR) return resized_image
Convert images to PDF
Define a function, convert_to_pdf() . Use filedialog to ask for the destination path for the PDF file. Set the default file type and extension to . pdf . Use ReportLab's canvas module to draw the horizontal page. Repeat the path of the images, open them, set the size of the PDF page to be the same as the size of the image, and draw the image from the top left corner to the specified size.
The showPage() method allows the PDF to move to the next page. After the program completes this process, save the PDF file and display a message box with the path.
def convert_to_pdf(self): pdf_path = filedialog.asksaveasfilename(defaultextension=".pdf", filetypes=(("PDF Files", "*.pdf"),)) c = canvas.Canvas(pdf_path, pagesize=landscape) for image_path in self.image_paths: image = Image.open(image_path) width, height = image.size c.setPageSize((width, height)) c.drawImage(image_path, 0, 0, width=width, height=height) c.showPage() c.save() messagebox.showinfo("Conversion Successful", f"PDF saved at {pdf_path}")
Create a Tkinter root window and pass it to the class field. The mainloop() function tells Python to run the Tkinter event loop and listen for events until you close the window.
if __name__ == "__main__": root = tk.Tk() app = ImageToPDFConverter(root) root.mainloop()
Put all the code together and the image to PDF converter is ready to use.
You should read it
- What is Python? Why choose Python?
- 5 choose the best Python IDE for you
- Bookmark 5 best Python programming learning websites
- Multiple choice quiz about Python - Part 3
- Why should you learn Python programming language?
- For in Python loop
- Python data type: string, number, list, tuple, set and dictionary
- Multiple choice quiz about Python - Part 4
May be interested
- How to batch format photos in Windows 10on windows 10, you have the trick to change the batch image format without users needing support tools.
- For in Python loopin this article, we will learn more about for for loop in python as well as its variations, how to use for to repeat a string of elements in python such as list, string or other iterative objects.
- Manage files and folders in Pythonpython also provides a variety of methods to handle various directory-related operations. in this article, we will learn about managing files and directories in python, namely creating folders, renaming folders, listing folders and working with them.
- How to convert content in photos into textin order to convert the content in the photo into text, we can use the newocr website completely free of charge.
- Multiple choice quiz about Python - Part 3today's topic quantrimang wants to challenge you is about file and exception handling in python. let's try the following 15 questions!
- 5 choose the best Python IDE for youin order to learn well python, it is essential that you find yourself an appropriate ide to develop. quantrimang would like to introduce some of the best environments to help improve your productivity.
- What is Python? Why choose Python?python is a powerful, high-level, object-oriented programming language, created by guido van rossum. python is easy to learn and emerging as one of the best introductory programming languages for people who are first exposed to programming languages.
- Module time in Pythonpython has a time module used to handle time-related tasks. tipsmake.com will work with you to find out the details and functions related to the time specified in this module. let's follow it!
- Python data type: string, number, list, tuple, set and dictionaryin this section, you'll learn how to use python as a computer, grasp python's data types and take the first step towards python programming.
- How to install Python on Windows, macOS, Linuxto get started with python, you first need to install python on the computer you are using, be it windows, macos or linux. below is a guide to installing python on your computer, specific to each operating system.