DEV Community

Shivesh Tiwari
Shivesh Tiwari

Posted on • Edited on

How to Create a GUI pdf to jpg/png Converter Tool in Python

If you are into technical writing, you must have faced some situations where you need to convert pdf to some image format or convert a image into other format. What do you do? A quick google search and you'll get some websites that do this task perfectly, but suppose if you're offline? Why not build a tool ourselves? A lightweight tool, easy to use, and most importantly GUI based.

Unlocking the power of Python and the magic of graphical user interfaces (GUIs), we embark on an exciting journey to create a versatile and intuitive PDF to JPG/PNG converter tool. In this article, we'll unravel the secrets behind building a user-friendly application that seamlessly transforms PDF documents into vibrant image files with just a few clicks.

One can also expand this GUI and add more conversion options like png to jpg, pdf to docx, etc.

Screenshot of the GUI

Tkinter Setup

Create a file main.py and setup tkinter.

import tkinter as tk
from tkinter.ttk import *

window = tk.Tk()
window.title("Pdf to jpg/png Converter")
window.resizable(0, 0)
window.config(width=50)

# Create a GUI here

window.mainloop()
Enter fullscreen mode Exit fullscreen mode

This is a basic setup of the Tkinter file.
Now lets create a file to handle all our conversions.

Converter funcitons

Create a python file in the same folder and name it "Converter.py". It will contain some functions to handle the conversion of pdf to jpg and png.
We are going to use PyMuPDF
pip install PyMuPDF
We need to import this as fitz.
So, the code in Converter.py will look like:

import fitz

def ConvertPDFtoImage(file, extension, outputType):
    doc = fitz.open(file, filetype="pdf")
    filename = file.split('.')[0]

    for idx, page in enumerate(doc):  
        pix = page.get_pixmap(dpi=600)
        the_page_bytes=pix.pil_tobytes(format=outputType)
        with open(f"{filename}-page-{idx}.{extension}", "wb") as outf:
            outf.write(the_page_bytes)
Enter fullscreen mode Exit fullscreen mode

In the function ConvertPDFtoImage we are getting 3 arguements. Firstly, we need to open the file that we have to convert from pdf to jpg/png. Then to handle the filename to save the file, we will get the filename from the given file, by using split('.') we'll separate the filename and the extension and the output will be a list, then split('.')[0] will give the first element of the list, which is the filename.
Now run a loop, with index and page for the given file and start conversion by the above code. Finally, save the files.

Now almost all basic setup is done. Now lets create the GUI.

Tkinter GUI

Add this code in your main.py file above the window.mainloop()

# Create a StringVar to handle the changed value of tkinter Entry
file_str = tk.StringVar(window)

fileLabel = Label(text="Enter File Path:", font=('Calibri', 11))
fileLabel.pack(fill=tk.X, padx=16, pady=(16, 0))
inputTxt = tk.Entry(
    font=('Calibri', 12),
    textvariable=file_str
)
inputTxt.pack(fill=tk.X, padx=16)

separateLabel = tk.Label(text="Or")
separateLabel.pack(pady=5)

def chooseFileCommand():
    file = filedialog.askopenfilename()

    if file is not None:
        file_str.set(file)

chooseFile = tk.Button(   # Add a choose file button
    text="Choose File",
    command=chooseFileCommand
)
chooseFile.pack(pady=(0, 10))

# Create a frame to contain the conversion options
frame1 = tk.Frame(window, width=50, padx=16, pady=16)
frame1.columnconfigure(0, weight=1)
frame1.columnconfigure(0, weight=3)

label1 = tk.Label(
    frame1,  # This label should be in frame
    text='Convert to:',
    padx=10,
    font=('Calibri', 12)
).grid(column=0, row=0)

combo = Combobox(
    frame1,
    state="readonly",
    values=["png", "jpg"],
)
combo.current(0)
combo.grid(column=1, row=0)

frame1.pack()

def handleConversion():
    print("Convert:", file_str.get())
    print("To:", combo.get())
    file = file_str.get()
    extension = combo.get()

    if (extension == 'png'):
        ConvertPDFtoImage(file, extension, 'PNG')
    if (extension == 'jpg'):
        ConvertPDFtoImage(file, extension, 'JPEG')

convertBtn = tk.Button(
    window,
    text="Convert", 
    bg="royalblue", 
    fg="white", 
    border=0,
    padx=5,
    font=('Calibri', 12, 'bold'), 
    command=handleConversion
)
convertBtn.pack(pady=10, padx=16, side="right")
Enter fullscreen mode Exit fullscreen mode

After doing this, you're GUI pdf to jpg/png conversion tool is ready. Make sure you give your appreciation to this post if you liked it, as it gives motivation to further make more posts like this. Also subscribe for more like this.

Till then,
Bye Bye, See ya!

Top comments (0)