How to convert images to PDF in Python
You can easily build an image to PDF converter in Python . Here are detailed instructions.
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
- How to set up Python to program on WSL
- More than 100 Python exercises have solutions (sample code)
- 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
- Manage files and folders in Python
- How to use GPT-3 with Python
Maybe you are interested
This program will help you become invisible before the webcam lens is recording live Brain research explains the difference in the impact of technology on men and women 'Eyes glued' to the screen before going to bed is not harmful to the mental health of the bar, teenager! Can ants survive if they fall from the roof of the building? Did you know: people and pigs have the same skin structure, human nervous system and round worms are the same ... The scoliosis of the spine, the back always feels sore, turns out to be the cause