Convert Images to PDFs using Tkinter


Python is a scripting language and thus, it helps in many ways to create file converters such as CSV to PDF, PDF to DOC, and vice-versa. With the help of certain libraries, we can also create an application that converts images into PDF. To create such an application, we use the img2pdf module in Python. It helps to parse the image binary and converts it into PDFs.

We will follow these steps to create an application,

  • First, make sure the system has img2pdf requirements already in place. Type pip install img2pdf on your terminal to install the package. Import img2pdf in the notebook.

  • Import filedialog to open a dialog box that asks users to select multiple images in the directory.

  • Import tkinter Library by typing from tkinter import *

  • Create a basic structure using Tkinter Library such as Button Widget to open the File Dialog, Label widget to show the message.

  • Define a function to open the dialog Box which asks users to select multiple images in the directory.

  • Define a function for opening the file as binary and convert it into PDF using the convert method.

Example

# Import required Libraries
from tkinter import *
from tkinter import filedialog
import img2pdf
from tkinter import ttk
# Create an instance of tkinter frame
win = Tk()
#set the geometry
win.geometry('750x250')
win.title("Image to PDF")
def select_file():
   global images
   images = filedialog.askopenfilenames(initialdir = "",title = "Select Images")
   Label(win, text=images).pack()
#Convert Image to PDF
def image_to_pdf():
   for image in enumerate(images):
      with open(f"{image}.pdf", "wb") as file:
         file.write(img2pdf.convert(images))
         Label(frame,text=file).pack()
# Add Labels and Buttons
Label(win, text = "Image to PDF Convertor",font = "Caveat 25 bold").pack(pady = 30)
ttk.Button(win, text = "Select Images",command = select_file).pack(ipadx = 10)
frame = Frame(win)
frame.pack()
ttk.Button(frame, text = "Convert and Save",command = image_to_pdf).pack(side = LEFT, pady=20,ipadx = 10)
win.mainloop()

Output

Running the above code will display the application window that will convert the images into PDF file.

Now, select an Image file from the local directory and click the "Convert and Save" button to convert and save it as PDF.

Updated on: 21-Apr-2021

400 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements