Home > Article > Backend Development > How to add PDF in Tkinter GUI Python?
This article will teach us how to display PDF files in Tkinter GUI. We will use the PyMuPDF library to read the pdf file and convert it to an image, and then use Tkinter to display the image.
For our task we will perform the following steps -
Read PDF files.
Define a transformation matrix to be applied to the PDF page to obtain the image.
Calculate the total number of pages for error checking.
Define the screen (canvas) of the GUI.
Define a helper function for converting PDF pages to PIL images.
Define a function to display a page image in the GUI.
Add buttons, labels, scroll bars, etc. and configure them.
First, we first run the following command in the terminal to install the PyMuPDF package.
python -m pip install --upgrade pip python -m pip install --upgrade pymupdf
Now we need to import the libraries we will use. Import Fitz
import fitz from tkinter import * from PIL import Image, ImageTk
Here fitz is a utility library provided with the PyMuPDF library for getting PDF pages as images.
We first use the fitz.open function to open the PDF file to be displayed in the GUI. This returns a document object that can be used to access the page.
# open pdf file file_name = "sample.pdf" doc = fitz.open(file_name)
Now we need to specify how to view the page. By defining the matrix function below, we can "fitz" to maintain 1x scaling.
# transformation matrix we can apply on pages zoom = 1 mat = fitz.Matrix(zoom, zoom)
Let’s also count the number of pages -
# count number of pages num_pages = 0 for p in doc: num_pages += 1
Now we will define a screen, add a scrollbar and a canvas to our code -
# initialize and set screen size root = Tk() root.geometry('750x700') # add scroll bar scrollbar = Scrollbar(root) scrollbar.pack(side = RIGHT, fill = Y) # add canvas canvas = Canvas(root, yscrollcommand = scrollbar.set) canvas.pack(side = LEFT, fill = BOTH, expand = 1)
Here our screen is represented by the name "root" and has dimensions of 750x700. We also added a scrollbar and specified that it be on the right and fill the entire height. Again, we add the canvas to the left and fill the entire screen on both sides!
In order to receive the page number that the user wants to read, we need the page number as input. We can do this -
# define entry point (field for taking inputs) entry = Entry(root)
# add a label for the entry point label = Label(root, text="Enter page number to display:")
The parameter "root" tells us that these objects will be associated with the screen "root".
Now we will define a helper function to get the image of the PDF file from the page number.
def pdf_to_img(page_num): page = doc.load_page(page_num) pix = page.get_pixmap(matrix=mat) return Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
Here we first use doc.load_page to load the page and pass the page number as a parameter. We then convert the PDF page to get the pixel representation of the page in the second line. Finally, we convert the pixel representation to PIL image format.
Now we define a function show_image to display images in the Tkinter GUI.
def show_image(): try: page_num = int(entry.get()) - 1 assert page_num >= 0 and page_num < num_pages im = pdf_to_img(page_num) img_tk = ImageTk.PhotoImage(im) frame = Frame(canvas) panel = Label(frame, image=img_tk) panel.pack(side="bottom", fill="both", expand="yes") frame.image = img_tk canvas.create_window(0, 0, anchor='nw', window=frame) frame.update_idletasks() canvas.config(scrollregion=canvas.bbox("all")) except: pass
First, we read the page number from the previously defined entry point and convert it to an integer. If it is not a valid integer, an exception occurs and the exception block handles it. We then check if the page number is between 0 or the number of pages, since this is the only valid page range we can display. Then using the helper function we defined earlier, we get the PIL image of the user-specified page. We then set up the frame, panel, and canvas to display the image correctly.
Next we add a button to display the page. We pass the function "show_image" as a command. So whenever the button is pressed, the "show_image" function is called.
# add button to display pages button = Button(root, text="Show Page", command=show_image)
Now we set the visual position of the various components defined previously -
# set visual locations label.pack(side=TOP, fill=None) entry.pack(side=TOP, fill=BOTH) button.pack(side=TOP, fill=None)
We also set the initial page to the first page of the PDF, as follows -
entry.insert(0, '1') show_image()
We configure the scroll bar
scrollbar.config(command = canvas.yview) root.mainloop()
Finally we close the PDF to avoid it being damaged by our computer.
doc.close()
After running the program we will see the following output!
This article teaches us how to use the PyMuPDF library with Pillow and Tkinter to display PDF files in the Tkinter GUI. We also learned how to count pages, convert PDF pages to images, make interactive buttons, and how to visually place the different elements that make up a GUI.
The above is the detailed content of How to add PDF in Tkinter GUI Python?. For more information, please follow other related articles on the PHP Chinese website!