
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PDF Viewer for Python Tkinter
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.
Example
#Import the required Libraries import PyPDF2 from tkinter import * from tkinter import filedialog #Create an instance of tkinter frame win= Tk() #Set the Geometry win.geometry("750x450") #Create a Text Box text= Text(win,width= 80,height=30) text.pack(pady=20) #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 content=page.extractText() #Add the content to TextBox text.insert(1.0,content) #Define function to Quit the window def quit_app(): win.destroy() #Create a Menu my_menu= Menu(win) win.config(menu=my_menu) #Add dropdown to the Menus file_menu=Menu(my_menu,tearoff=False) my_menu.add_cascade(label="File",menu= file_menu) file_menu.add_command(label="Open",command=open_pdf) file_menu.add_command(label="Clear",command=clear_text) file_menu.add_command(label="Quit",command=quit_app) win.mainloop()
Output
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.