You no longer want to edit PDF files manually? You want to learn how to edit PDFs with Python be able to edit? Then PyPDF2 is just the thing for you. With this Python library you are able to create PDF files
- together,
- divide,
- to encrypt,
- to decode
and much more.
Topics of this tutorial
- Installing PyPDF2 and its dependencies
- Read, write and copy PDF files
- Merge multiple PDF files into one
- Splitting a PDF file into multiple files
- Encrypt and decrypt PDF files
- Extract text and images from PDFs
- Add watermarks and page numbers to PDFs
We also compare PyPDF2 with other PDF editing programs and discuss its advantages and limitations. With PyPDF2 you can automate your PDF workflows and save time on manual edits. Learn how to get started here:
PyPDF2 Installation
To use PyPDF2, this can be easily installed via pip:
- Make sure you have Python 2.7 or Python 3.x installed on your system.
- Install PyPDF2 with pip:
pip install PyPDF2
Read, write and copy PDF files
With PyPDF2 you can easily read, write and copy PDF files. Here is an example:
import PyPDF2
# Open the PDF file
pdf_file = open('example.pdf', 'rb')
# Read the PDF file
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
# Print the number of pages
print(pdf_reader.numPages)
# Get the first page
page = pdf_reader.getPage(0)
# Extract the text from the first page
text = page.extractText()
# Print the text
print(text)
# Close the PDF file
pdf_file.close()
Merge multiple PDF files into one
If you have multiple PDF files that you want to combine into one, PyPDF2 makes it easy. Here is an example:
import PyPDF2
# Open the first PDF file
pdf_file1 = open('example1.pdf', 'rb')
# Open the second PDF file
pdf_file2 = open('example2.pdf', 'rb')
# Create a PDF merger
pdf_merger = PyPDF2.PdfFileMerger()
# Add the first PDF file
pdf_merger.append(pdf_file1)
# Add the second PDF file
pdf_merger.append(pdf_file2)
# Merge the PDF files
pdf_merger.write('merged.pdf')
# Close the PDF files
pdf_file1.close()
pdf_file2.close()
Splitting a PDF file into multiple files
If you have a large PDF file that you want to split into smaller files, PyPDF2 can help. Here is an example:
import PyPDF2
# Open the PDF file
pdf_file = open('example.pdf', 'rb')
# Create a PDF reader
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
# Get the number of pages
num_pages = pdf_reader.numPages
# Split the PDF file into multiple files
for page_num in range(num_pages):
# Create a PDF writer
pdf_writer = PyPDF2.PdfFileWriter()
# Get the page
page = pdf_reader.getPage(page_num)
# Add the page to the PDF writer
pdf_writer.addPage(page)
# Create the new PDF file
new_file_name = 'page' + str(page_num) + '.pdf'
new_file = open(new_file_name, 'wb')
PyPDF2 also supports PDF file creation and editing. With PyPDF2, you can create a new PDF file from scratch or modify an existing file. You can add text, images, and other elements to a PDF file, and modify its structure, properties, and metadata.One of the most powerful features of PyPDF2 is the ability to merge and split PDF files. You can merge multiple PDFs into a single file, or split one large PDF into several smaller ones. This can be useful for organizing and archiving documents, and for creating reports and presentations.
In addition to these core features, PyPDF2 also provides a set of tools and utilities for working with PDF files. These include:
Encryption and decryption of PDFs
PyPDF2 allows you to encrypt and decrypt PDF files, supporting both user and owner passwords. Learn how to encrypt a PDF file with PyPDF2:
import PyPDF2
pdf_file = open('input.pdf', 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
pdf_writer = PyPDF2.PdfFileWriter()
pdf_writer.addPage(pdf_reader.getPage(0))
pdf_writer.encrypt('user_password', 'owner_password')
result_pdf = open('encrypted.pdf', 'wb')
pdf_writer.write(result_pdf)
result_pdf.close()
pdf_file.close()
In this code, we first open the PDF input file and create a PDF Reader object. Then we create a PDF Writer object and add the first page of the PDF input file to it. Finally, we encrypt the PDF file with a user password and an owner password and save the result as a new file.Decrypt PDF files with Python
To decrypt a PDF file, you can use the following code:
import PyPDF2
pdf_file = open('encrypted.pdf', 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
if pdf_reader.isEncrypted:
pdf_reader.decrypt('password')
page = pdf_reader.getPage(0)
text = page.extractText()
print(text)
pdf_file.close()
Here we first open the encrypted PDF file and create a PDF read object. Then we check if the PDF file is encrypted and decrypt it with the password if it is. We extract the text from the first page of the PDF file and output it to the console.
Extract text and images from PDFs
PyPDF2 allows you to extract text and images from PDF files, with options to filter and process the output if the text and images are embedded in the digital native PDF. If this is not the case, take a look at our pytesseract tutorial an. Here you can see how to extract text from a PDF file using PyPDF2:
import PyPDF2
pdf_file = open('input.pdf', 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
text = ''
for page in range(pdf_reader.getNumPages()):
text += pdf_reader.getPage(page).extractText()
print(text)
pdf_file.close()
In this code, we first open the PDF input file and create a PDF Reader object. Then we loop through each page of the PDF file and extract the text. We concatenate the text from each page and output it to the console.
To extract images from a PDF file, you can use the following code:
import PyPDF2
pdf_file = open('input.pdf', 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
for page in range(pdf_reader.getNumPages()):
xObject = pdf_reader.getPage(page).getObject()['/Resources']['/XObject'].getObject()
for obj in xObject:
if xObject[obj]['/Subtype'] == '/Image':
size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
data = xObject[obj]._data
print(size, len(data))
pdf_file.close()
Converting PDFs to other formats with PyPDF2
PyPDF2 is a powerful Python library that lets you convert PDFs to other formats such as HTML, XML, and plain text. This can be useful if you need to extract certain data from a PDF or display the contents of a PDF on a website. Here is an example of converting a PDF to plain text using PyPDF2:
import PyPDF2
# Open the PDF file
pdf_file = open('example.pdf', 'rb')
# Create a PDF reader object
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
# Get the first page of the PDF
page = pdf_reader.getPage(0)
# Extract the text from the page
text = page.extractText()
# Print the text
print(text)
# Close the PDF file
pdf_file.close()
In this example we open the PDF file in binary mode and create a PDF Reader object. Then we get the first page of the PDF file and extract the text from it using the method extractText(). Finally, the extracted text is printed.
Extract and modify bookmarks, annotations and form fields with PyPDF2
PyPDF2 lets you extract and modify various elements in a PDF file, including bookmarks, annotations, and form fields. This can be useful if you want to automate certain tasks or extract specific data from a PDF file. Here is an example of how to extract bookmarks from a PDF file using PyPDF2:
import PyPDF2
# Open the PDF file
pdf_file = open('example.pdf', 'rb')
# Create a PDF reader object
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
# Get the bookmarks from the PDF
bookmarks = pdf_reader.getOutlines()
# Print the bookmarks
for bookmark in bookmarks:
print(bookmark.title)
# Close the PDF file
pdf_file.close()
In this example we open the PDF file in binary mode and create a PDF Reader object. Then we use the method getOutlines()to extract the bookmarks from the PDF file. Finally, we print the titles of the bookmarks.
Working with PDF layers with PyPDF2
PDF layers, also known as optional content groups, allow you to control the visibility and appearance of various elements in a PDF. PyPDF2 provides a way to work with PDF layers so that you can modify or extract specific layers from a PDF. Here is an example of how to extract a specific layer from a PDF using PyPDF2:
import PyPDF2
# Open the PDF file
pdf_file = open('example.pdf', 'rb')
# Create a PDF reader object
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
# Get the first page of the PDF
page = pdf_reader.getPage(0)
# Get the layers from the page
layers = page['/OCProperties']['/OCGs']
# Print the layers
for layer in layers:
print(layer)
# Close the PDF file
pdf_file.close()
In this example we open the PDF file in binary mode and create a PDF Reader object. Then we get the first page of the PDF file and extract the layers from it using the syntax ['/OCProperties']['/OCGs']. Finally, we output the names of the layers.In this example, we open the PDF file in binary mode and create a PDF Reader object. Then we get the first page of the PDF file and extract the layers from it using the syntax ['/OCProperties']['/OCGs']. Finally, we output the names of the layers.
Conclusion
PyPDF2 is a powerful and flexible library for working with PDF files in Python. Whether you need to create, modify or extract information from a PDF, PyPDF2 offers a wide range of tools and utilities to help you get the job done. Whether you are a developer, a researcher or simply someone who needs to work with PDFs on a regular basis, PyPDF2 is definitely worth a look.
Discover our Python category with helpful articles around the topic.
