Home Backend Development Python Tutorial How to Work With PDF Documents Using Python

How to Work With PDF Documents Using Python

Mar 02, 2025 am 09:54 AM

How to Work With PDF Documents Using Python

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images.

Luckily, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me.

Preparation

The core lies in using external module PyPDF2. First, install it using pip:

pip is a package management system for Python that installs and manages Python packages, and many packages are found in the Python Package Index (PyPI).

If you downloaded Python from python.org, pip is likely to be installed automatically. Enter the following command in the terminal to install PyPDF2:

pip install PyPDF2
Copy after login

To use all the features of PyPDF2 (including encryption, decryption and image processing), you can use the following command:

pip install PyPDF2[full]
Copy after login

If you only need AES encryption/decryption function, you can use:

pip install PyPDF2[crypto]
Copy after login

PyPDF2 supports RC4 encryption by default.

PyPDF2 Basics

PyPDF2 is a free open source library that supports the reading, writing, segmentation and merging of PDF files. This tutorial uses PyPDF2 version 2.11.1.

Read PDF file

We will use the Beauty and the Beast PDF version on Project Gutenberg as the sample file. You can download the file or use any other PDF file.

The following code demonstrates how to open and read a PDF file:

import PyPDF2

with open('beauty-and-the-beast.pdf', 'rb') as book:
    book_reader = PyPDF2.PdfReader(book)
Copy after login

The first line imports the PyPDF2 module. The PdfReader class is used to read a PDF file and represent its page as a Page object.

Get the number of pages:

import PyPDF2

with open('beauty-and-the-beast.pdf', 'rb') as book:
    book_reader = PyPDF2.PdfReader(book)
    number_of_pages = len(book_reader.pages)
    print(number_of_pages)  # 输出:48
Copy after login

Direct access to page number

get_page_number() Method to get the page number:

import random
from PyPDF2 import PdfReader

with open('beauty-and-the-beast.pdf', 'rb') as book:
    book_reader = PdfReader(book)
    page_list = book_reader.pages
    last_page = page_list[-1]
    print(book_reader.get_page_number(last_page))  # 输出:47 (实际为第48页)
    some_page = page_list[random.randint(15, 35)]
    print(book_reader.get_page_number(some_page))  # 输出:随机页码
Copy after login

Page mode and page layout

The

page_mode and page_layout properties return page mode and page layout information respectively:

from PyPDF2 import PdfReader

with open('beauty-and-the-beast.pdf', 'rb') as book:
    book_reader = PdfReader(book)
    print(book_reader.page_mode)  # 输出:None
    print(book_reader.page_layout)  # 输出:None
Copy after login

metadata Properties return metadata of PDF files, such as author, title, creation time, and generator, etc.:

from PyPDF2 import PdfReader

with open('beauty-and-the-beast.pdf', 'rb') as book:
    book_reader = PdfReader(book)
    book_metadata = book_reader.metadata
    print(book_metadata.title)       # 输出:Beauty and the Beast
    print(book_metadata.author)      # 输出:Anonymous
    print(book_metadata.creation_date) # 输出:例如 2006-11-30 01:13:00-08:00
    print(book_metadata.producer)    # 输出:例如 pdfeTeX-1.21a
Copy after login

Summary

Python simplifies the processing of PDF files through the PyPDF2 module. This article only introduces some of the functions of PyPDF2. For more details, please refer to the official PyPDF2 documentation.

The above is the detailed content of How to Work With PDF Documents Using Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: The Power of Versatile Programming Python: The Power of Versatile Programming Apr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

See all articles