PDF Viewer for Python Tkinter

PythonTkinterServer Side ProgrammingProgramming

Python is well known for its large set of libraries and extensions, each for different features, properties and use-cases. To handle PDF files, Python provides PyPDF2 toolkit which is capable of processing, extracting, merging multiple pages, encrypting PDF files, and many more. It is a very useful Package for managing and manipulating the file streams such as PDFs. Using PyPDF2, we will create a Tkinter application that reads the PDF file by asking users to select and open a PDF file from the local directory.

To create the application, we will follow the steps given below −

  • Install the requirement by typing

    pip install PyPDF2

    in the command Shell. Once installed, import the library in the notebook using import Pypdf2 in Notebook.
  • Import filedialog to create a dialog box for selecting the file from the local directory.

  • Create a Text Widget and add some Menus to it like Open, Clear, and Quit.

  • Define a function for each Menu.

  • Define a function to open the file. In this function, first, we will read the file using PdfFileReader(file). Then, extract the pages from the file.

  • Insert the content in the Text Box.

  • Define the function for Quit Menu.


#Import the required Libraries
import PyPDF2
from tkinter import *
from tkinter import filedialog
#Create an instance of tkinter frame
win= Tk()
#Set the Geometry
#Create a Text Box
text= Text(win,width= 80,height=30)
#Define a function to clear the text
def clear_text():
   text.delete(1.0, END)
#Define a function to open the pdf file
def open_pdf():
   file= filedialog.askopenfilename(title="Select a PDF", filetype=(("PDF    Files","*.pdf"),("All Files","*.*")))
   if file:
      #Open the PDF File
      pdf_file= PyPDF2.PdfFileReader(file)
      #Select a Page to read
      page= pdf_file.getPage(0)
      #Get the content of the Page
      #Add the content to TextBox

#Define function to Quit the window
def quit_app():
#Create a Menu
my_menu= Menu(win)
#Add dropdown to the Menus
my_menu.add_cascade(label="File",menu= file_menu)


Running the above code will display a full-fledged tkinter application. It has functionalities of opening the file, clearing the file, and quit to terminate the application.

Click the "File" Menu on upper left corner of the application, open a new PDF File in the Text Box.

Published on 22-Apr-2021 11:11:12