Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PDF Viewer for Python Tkinter
Python provides the PyPDF2 library for handling PDF files, which can process, extract, merge, and encrypt PDF documents. Combined with Tkinter's GUI capabilities, we can create a simple PDF viewer application that allows users to open and read PDF files through a graphical interface.
Installation and Setup
Before creating the application, install the required library ?
pip install PyPDF2
Note: PyPDF2's PdfFileReader is deprecated. Modern versions use PdfReader instead.
Building the PDF Viewer Application
The application consists of a text widget for displaying PDF content and a menu system for file operations ?
# Import the required libraries
import PyPDF2
from tkinter import *
from tkinter import filedialog, messagebox
# Create an instance of tkinter frame
win = Tk()
win.title("PDF Viewer")
win.geometry("800x600")
# Create a Text Box with scrollbar
text_frame = Frame(win)
text_frame.pack(fill=BOTH, expand=True, padx=10, pady=10)
text = Text(text_frame, width=80, height=30, wrap=WORD)
scrollbar = Scrollbar(text_frame, orient=VERTICAL, command=text.yview)
text.config(yscrollcommand=scrollbar.set)
text.pack(side=LEFT, fill=BOTH, expand=True)
scrollbar.pack(side=RIGHT, fill=Y)
# 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",
filetypes=(("PDF Files", "*.pdf"), ("All Files", "*.*"))
)
if file:
try:
# Clear existing content
clear_text()
# Open the PDF File (using modern PyPDF2 syntax)
with open(file, 'rb') as pdf_file:
pdf_reader = PyPDF2.PdfReader(pdf_file)
# Extract text from all pages
full_text = ""
for page_num in range(len(pdf_reader.pages)):
page = pdf_reader.pages[page_num]
full_text += f"--- Page {page_num + 1} ---\n"
full_text += page.extract_text() + "\n\n"
# Add the content to TextBox
text.insert(1.0, full_text)
except Exception as e:
messagebox.showerror("Error", f"Failed to open PDF: {str(e)}")
# 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_separator()
file_menu.add_command(label="Quit", command=quit_app)
# Start the application
win.mainloop()
Key Features
The PDF viewer application includes the following functionality ?
- File Dialog: Users can browse and select PDF files from their local directory
- Text Display: PDF content is extracted and displayed in a scrollable text widget
- Multi-page Support: All pages from the PDF are extracted and displayed with page markers
- Menu System: Clean menu interface with Open, Clear, and Quit options
- Error Handling: Displays error messages for corrupted or unreadable PDF files
How It Works
The application uses PyPDF2.PdfReader to read PDF files in binary mode. The extract_text() method retrieves text content from each page, which is then displayed in the Tkinter text widget. A scrollbar provides navigation for longer documents.
Output
Running the application displays a window with a text area and file menu. Users can open PDF files through the File menu, and the extracted text content will appear in the text widget with page separators.
Conclusion
This PDF viewer demonstrates how to combine PyPDF2 with Tkinter to create a functional document reader. The application provides basic PDF viewing capabilities with a clean interface, making it suitable for simple text extraction and display tasks.
