Table of Contents
Tkinter, Pillow and Reportlab. Modules
This practical guide explains how to convert images to pdf in python with clear steps and useful context. It also covers common requirements, potential problems, and the details that can help you get better results.
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.
Conclusion
Understanding Convert Image to PDF in Python makes it easier to compare options, avoid common mistakes, and apply the information in this guide more effectively. Review the relevant requirements before making changes or choosing a solution.
FAQ
How do you convert images to pdf in python?
Follow the steps in this guide in order, confirm the required settings or tools, and verify the result before making additional changes.
Is it safe to convert images to pdf in python?
It is generally safe when you follow the recommended instructions, use trusted tools, and avoid changing settings you do not understand.
What should you do if the process does not work?
Recheck the requirements, restart the device or application when appropriate, and review each step for missed settings or compatibility issues.
Reader Comments 0
Sign in with email or Google to join the discussion.