How to View PDF File in Python

PDF (Portable Document Format)

PDF is a popular file format for sharing documents. It is a versatile format for document information that can be viewed on a variety of devices, and it can also be protected with security permissions.

In Python, there are a number of libraries that can be used to read and manipulate PDF documents. One of these libraries is IronPDF. IronPDF is a powerful library that provides a wide range of features for working with PDF documents.

In this article, we will learn how to view PDF files in Python using the IronPDF library.

IronPDF - Python Library

IronPDF is a powerful Python library that enables developers to work with PDF files programmatically. With IronPDF, you can easily generate, manipulate, and extract data from PDF documents, making it a versatile tool for various PDF-related tasks. Whether you need to create PDFs from scratch, modify existing PDFs, or extract content from PDFs, IronPDF provides a comprehensive set of features to simplify your workflow.

Some features of the IronPDF Python library include:

  • Create new PDF file from scratch using HTML or URL
  • Edit existing PDF files
  • Rotate PDF pages
  • Extract text, metadata and images from PDF files
  • Convert PDF files to other formats
  • Secure PDF files with passwords and restrictions
  • Split and merge PDFs

Note: IronPDF produces a watermarked PDF data file. To remove the watermark, you need to license IronPDF. If you wish to use a licensed version of IronPDF, visit the IronPDF website to obtain a license key.

Prerequisites

Before working with IronPDF in Python, there are a few prerequisites we should have in place:

  1. Python Installation: Ensure that you have Python installed on your system. IronPDF is compatible with Python 3.x versions, so make sure you have a compatible Python installation.
  2. IronPDF Library: Install the IronPDF library to access its functionality. You can install it using the Python package manager (pip) by executing the following command in your command-line interface:

    pip install ironpdf
  3. Tkinter Library: Tkinter is the standard GUI toolkit for Python. It is used for creating the graphical user interface for the PDF viewer in the provided code snippet. Tkinter usually comes pre-installed with Python, but if you encounter any issues, you can install it using the package manager:

    pip install tkinter
  4. Pillow Library: The Pillow library is a fork of the Python Imaging Library (PIL) and provides additional image processing capabilities. It is used in the code snippet to load and display the images extracted from the PDF. Install Pillow using the package manager:

    pip install pillow
  5. Integrated Development Environment (IDE): Using an IDE to handle Python projects, can greatly enhance your development experience. It provides features like code completion, debugging, and a more streamlined workflow. One popular IDE for Python development is PyCharm. You can download and install PyCharm from the JetBrains website (https://www.jetbrains.com/pycharm/).
  6. Text Editor: Alternatively, if you prefer to work with a lightweight text editor, you can use any text editor of your choice, such as Visual Studio Code, Sublime Text, or Atom. These editors provide syntax highlighting and other useful features for Python development. You can also use python's own IDLE App for creating Python scripts.

Creating a PDF Viewer Project using PyCharm

After installing PyCharm IDE, create a PyCharm python project by following the below steps:

  1. Launch PyCharm: Open PyCharm from your system's application launcher or desktop shortcut.
  2. Create a New Project: Click on "Create New Project" or Open an existing Python project.

    How to Convert PDF to Text in Python (Tutorial): Figure 1

  3. Configure Project Settings: Provide a name for your project and choose the location to create the project directory. Select the Python interpreter for your project. Then click "Create".

    How to Convert PDF to Text in Python (Tutorial): Figure 2

  4. Create Source Files: PyCharm will create the project structure, including a main Python file and a directory for additional source files. Start writing code and click the run button or press Shift+F10 to execute the script.

Steps to View PDF Files in Python using IronPDF

Import the required libraries

To begin, we need to import the necessary libraries. In this case, we need the os, shutil, ironpdf, tkinter, and PIL libraries. The os and shutil libraries are used for file and folder operations, ironpdf is the library for working with PDF files, tkinter is used for creating the graphical user interface (GUI), and PIL is used for image manipulation.

import os, shutil, ironpdf
from tkinter import *
from PIL import Image, ImageTk
PYTHON

Convert PDF Document to Images

Next, we define a function called convert_pdf_to_images. This function takes the path of the PDF file as input. Inside the function, we use the IronPDF library to load the PDF document from the file. We then specify a folder path to store the extracted image files. IronPDF's pdf.RasterizeToImageFiles method is used to convert each PDF page of the PDF to an image file and save it in the specified folder. We also create a list to store the image paths. The complete code example is as follows:

def convert_pdf_to_images(pdf_file):
    pdf = ironpdf.PdfDocument.FromFile(pdf_file)
    # Extract all pages to a folder as image files
    folder_path = "images"
    pdf.RasterizeToImageFiles(os.path.join(folder_path, "*.png"))
    # List to store the image paths
    image_paths = []
    # Get the list of image files in the folder
    for filename in os.listdir(folder_path):
        if filename.lower().endswith((".png", ".jpg", ".jpeg", ".gif")):
            image_paths.append(os.path.join(folder_path, filename))
    return image_paths
PYTHON

To extract text from PDF documents, visit this code examples page link.

Handle Window Closure

In order to clean up the extracted image files when the application window is closed, we define a(n) on_closing function. Inside this function, we use the shutil.rmtree() method to delete the entire images folder. We also set this function as the protocol to be executed when the window is closed. The following code helps to achieve the task:

def on_closing():
    # Delete the images in the 'images' folder
    shutil.rmtree("images")
    window.destroy()

window.protocol("WM_DELETE_WINDOW", on_closing)
PYTHON

Create the GUI Window

Now, we create the main GUI window using the Tk() constructor. We set the window title to "Image Viewer" and set the on_closing() function as the protocol to handle window closure.

window = Tk()
window.title("Image Viewer")
window.protocol("WM_DELETE_WINDOW", on_closing)
PYTHON

Create a Scrollable Canvas

To display the images and enable scrolling, we create a Canvas widget. The Canvas widget is configured to fill the available space and expand in both directions using pack(side=LEFT, fill=BOTH, expand=True). We also create a Scrollbar widget and configure it to control the vertical scrolling of all the pages and canvas.

canvas = Canvas(window)
canvas.pack(side=LEFT, fill=BOTH, expand=True)
scrollbar = Scrollbar(window, command=canvas.yview)
scrollbar.pack(side=RIGHT, fill=Y)
canvas.configure(yscrollcommand=scrollbar.set)
canvas.bind("<Configure>", lambda e:canvas.configure(scrollregion=canvas.bbox("all")))
canvas.bind_all("<MouseWheel>", lambda e: canvas.yview_scroll(int(-1*(e.delta/120)), "units"))
PYTHON

Create a Frame for Images

Next, we create a Frame widget inside the canvas to hold the images. We use create_window() to place the frame within the canvas. The (0, 0) coordinates and anchor='nw' parameter ensure that the frame starts in the top left corner of the canvas.

frame = Frame(canvas)
canvas.create_window((0, 0), window=frame, anchor="nw")
PYTHON

Convert PDF file to Images and Display

We call the convert_pdf_to_images() function with the file path name of the input PDF file. This function extracts the PDF pages as images and returns a list of image paths. We iterate through the image paths and load each image using the Image.open() method from the PIL library. We then create a PhotoImage object using ImageTk.PhotoImage() and create a Label widget to display the image.

images = convert_pdf_to_images("input.pdf")
# Load and display the images in the Frame
for image_path in images:
    image = Image.open(image_path)
    photo = ImageTk.PhotoImage(image)
    label = Label(frame, image=photo)
    label.image = photo  # Store a reference to prevent garbage collection
    label.pack(pady=10)
PYTHON

Input File

How to Convert PDF to Text in Python (Tutorial): Figure 3

Run the GUI Main Loop

Finally, we run the main event loop using window.mainloop(). This ensures that the GUI window remains open and responsive until it is closed by the user.

window.mainloop()
PYTHON

Output

How to Convert PDF to Text in Python (Tutorial): Figure 4

Conclusion

In this tutorial, we learned how to view PDF documents in Python using the IronPDF library. We covered the steps required to open a PDF file and convert to a series of image files, and then display them in a scrollable canvas, and handle the cleanup of extracted images when the application is closed.

For more details on the IronPDF Python library, please refer to the documentation.

Download and install IronPDF Python library and also get a free trial to test out its complete functionality in commercial development.