Image to PDF in python with GUI using Tkinter – Tutorial

Here in this tutorial, we are going to create a desktop application “using Python Tkinter” which can convert any Image(JPG or PNG) to PDF formatted file.
Let’s create Image to PDF in python with GUI by following these simple steps.
Requirements to get started
You will need PIL/Pillow (python library) to open, read and converting images. Run these commands in terminal to install Pillow
For Mac and Linux
pip3 install Pillow
For windows
py -m pip install Pillow
Finished?
After you finish this, we can follow the next steps.
Python function to convert Image to PDF encoding.
First of all let’s define a function to convert image encoding to pdf format.
from PIL import Image
#...
def convert(img_path):
img = Image.open(img_path)
try:
pdf = img.convert('RGB')
return pdf
except:
return False
Here, “img_path” is path of the image file and the function will return a PDF(bytes). If you don’t need a GUI, you can use this function to convert the Image file into PDF.
Full code – Image to PDF converter
from PIL import Image
from Tkinter
def convert(img_path):
img = Image.open(img_path)
try:
pdf = img.convert('RGB')
return pdf
except:
return False
def button_click():
image_path = filedialog.askopenfilename(filetypes=['Image Files', '.png', '.jpg'])
pdf = convert(image_path)
if pdf:
file_path = filedialog.asksaveasfilename(filetypes=['PDF Files', '*.pdf']) +'.pdf'
pdf.save(file_path)
messagebox.showinfo('Saved', f'Your PDF is saved at\n{file_path}')
else:
messagebox.showerror('Error', 'An error Occured while converting file')
GUI
app = filedialog.Tk()
app.title('PDF Converter')
button = ttk.Button(app, text='Select & Convert', command=button_click)
button.place(relx=0.5, rely=0.5, anchor='center')
app.mainloop()
Result – Image to PDF
Follow us on Instagram for regular updates.
For any query Feel free to contact us.