Пропустить до содержимого

Как использовать PyPDF без усилий?

[

Как работать с PDF в Python

Portable Document Format, или PDF, это формат файла, который можно использовать для надежного представления и обмена документами между операционными системами. В то время как PDF был изначально разработан компанией Adobe, сейчас это открытый стандарт, поддерживаемый Международной организацией по стандартизации (ISO). Вы можете работать с существующим PDF в Python, используя пакет PyPDF2.

PyPDF2 – это полностью написанный на чистом Python пакет, который вы можете использовать для выполнения различных операций с PDF.

By the end of this article, you ‘ll know how to do the following:

  • Извлекать информацию из документа PDF в Python
  • Поворачивать страницы
  • Объединять PDF-файлы
  • Разделять PDF-файлы
  • Добавлять водяные знаки
  • Шифровать PDF

Давайте начнем!

История pyPdf, PyPDF2 и PyPDF4

Оригинальный пакет pyPdf был выпущен давно, в 2005 году. Последний официальный релиз pyPdf был в 2010 году. После перерыва примерно на год, компания Phasit спонсировала форк pyPdf, который назвали PyPDF2. Код был написан с совместимостью с оригинальной версией и работал довольно хорошо несколько лет, последний релиз был в 2016 году.

Краткая серия релизов пакета PyPDF3 привела к переименованию проекта в PyPDF4. Все эти проекты делают практически одно и то же, однако самое большое отличие между pyPdf и PyPDF2+ заключается в том, что последние версии добавили поддержку Python 3. Есть отдельный форк pyPdf для Python 3 – pyPdf для Python 3, однако он не поддерживается уже много лет.

В то время как PyPDF2 был брошен в 2016 году, в 2022 он был возрожден и сейчас активно поддерживается. Новый пакет PyPDF4 не обладает полной обратной совместимостью с PyPDF2. Большая часть примеров в этой статье будет работать нормально с PyPDF4, но есть некоторые, которые не смогут, вот почему PyPDF4 не представлен здесь. Вы можете свободно поменять импорты PyPDF2 на PyPDF4 и посмотреть, как это работает для вас.

pdfrw: альтернатива

Патрик Мопин создал пакет pdfrw, который может делать то же самое, что и PyPDF2. Вы можете использовать pdfrw для всех тех же задач, с которыми вы познакомитесь в этой статье для PyPDF2, за исключением шифрования.

Наибольшее отличие pdfrw заключается в том, что он интегрируется с пакетом ReportLab, чтобы вы могли взять существующий PDF и создать новый с помощью ReportLab, используя часть или всю существующую PDF.

Установка

Установка PyPDF2 может быть выполнена с помощью pip или conda, если вы используете Anaconda вместо обычного Python.

Вот как вы можете установить PyPDF2 с помощью pip:

Shell

$ pip install pypdf2

Установка производится быстро, так как PyPDF2 не имеет зависимостей. Вы, скорее всего, потратите столько же времени на загрузку пакета, сколько и на установку.

Теперь, когда вы установили PyPDF2, давайте перейдем к изучению основных функций для работы с PDF в Python. Вот подробные инструкции и примеры кода для каждой операции.

Как извлекать информацию из документа PDF в Python

To extract information from a PDF document, such as its title, author, or number of pages, you can use the PdfFileReader class from the PyPDF2 module. First, you’ll need to open the PDF file and create an instance of PdfFileReader:

import PyPDF2
# Open the PDF file
pdf_file = open('document.pdf', 'rb')
# Create an instance of PdfFileReader
pdf_reader = PyPDF2.PdfFileReader(pdf_file)

Once you have the instance of PdfFileReader, you can easily access the information using its methods. For example, to get the number of pages in the PDF document, you can use the numPages property:

# Get the number of pages
num_pages = pdf_reader.numPages
print(f"Number of pages: {num_pages}")

You can also retrieve other information, such as the title and author, using the getDocumentInfo method:

# Get the document information
doc_info = pdf_reader.getDocumentInfo()
title = doc_info.title
author = doc_info.author
print(f"Title: {title}")
print(f"Author: {author}")

Remember to close the PDF file when you’re done:

# Close the PDF file
pdf_file.close()

Как поворачивать страницы PDF

To rotate pages in a PDF document, you can use the rotateClockwise or rotateCounterClockwise methods of the PageObject class. First, you’ll need to open the PDF file and create an instance of PdfFileReader, just like in the previous example:

import PyPDF2
# Open the PDF file
pdf_file = open('document.pdf', 'rb')
# Create an instance of PdfFileReader
pdf_reader = PyPDF2.PdfFileReader(pdf_file)

Next, you’ll need to select the page you want to rotate. You can use the getPage method and specify the page number:

# Select the page to rotate (page number starts from 0)
page_number = 0
page = pdf_reader.getPage(page_number)

Once you have the PageObject instance, you can rotate the page by a certain angle using the rotateClockwise or rotateCounterClockwise methods. For example, to rotate the page clockwise by 90 degrees:

# Rotate the page clockwise by 90 degrees
page.rotateClockwise(90)

After rotating the page, you may want to save the changes to a new PDF file. You can create an instance of PdfFileWriter, add the modified page to it, and save it to a new file:

# Create an instance of PdfFileWriter
pdf_writer = PyPDF2.PdfFileWriter()
# Add the modified page to PdfFileWriter
pdf_writer.addPage(page)
# Save the changes to a new PDF file
output_file = open('rotated_document.pdf', 'wb')
pdf_writer.write(output_file)
output_file.close()

Remember to close the PDF files when you’re done:

# Close the PDF files
pdf_file.close()

Как объединять PDF-файлы

To merge multiple PDF files into a single PDF, you can use the PdfFileMerger class from the PyPDF2 module. First, you’ll need to create an instance of PdfFileMerger:

import PyPDF2
# Create an instance of PdfFileMerger
pdf_merger = PyPDF2.PdfFileMerger()

Next, you can add the PDF files that you want to merge using the append method. You can specify multiple PDF files by passing their file names as arguments to the append method:

# Add the PDF files to merge
pdf_merger.append('file1.pdf')
pdf_merger.append('file2.pdf')
pdf_merger.append('file3.pdf')

Once you have added all the PDF files, you can save the merged PDF to a new file using the write method:

# Save the merged PDF to a new file
output_file = open('merged_document.pdf', 'wb')
pdf_merger.write(output_file)
output_file.close()

After merging the PDF files, remember to close the output file:

# Close the output file
output_file.close()

Как разделять PDF-файлы

To split a PDF file into multiple smaller PDF files, you can use the PdfFileWriter class from the PyPDF2 module. First, you’ll need to open the PDF file and create an instance of PdfFileReader, just like in the previous examples:

import PyPDF2
# Open the PDF file
pdf_file = open('document.pdf', 'rb')
# Create an instance of PdfFileReader
pdf_reader = PyPDF2.PdfFileReader(pdf_file)

Next, you can iterate over the pages of the PDF document and create a new PDF file for each page using the PdfFileWriter class. For example, to split the PDF file into multiple pages:

# Iterate over the pages
for page_number in range(pdf_reader.numPages):
# Create an instance of PdfFileWriter
pdf_writer = PyPDF2.PdfFileWriter()
# Add the current page to PdfFileWriter
page = pdf_reader.getPage(page_number)
pdf_writer.addPage(page)
# Save the current page as a new PDF file
output_file_name = f'page_{page_number + 1}.pdf'
output_file = open(output_file_name, 'wb')
pdf_writer.write(output_file)
output_file.close()

Remember to close the PDF file when you’re done:

# Close the PDF file
pdf_file.close()

Как добавлять водяные знаки в PDF

To add watermarks to a PDF document, such as a company logo or a draft watermark, you can use the PdfFileWriter and PdfFileReader classes from the PyPDF2 module. First, you’ll need to open the PDF files and create instances of PdfFileWriter and PdfFileReader, just like in the previous examples:

import PyPDF2
# Open the PDF files
pdf_file = open('document.pdf', 'rb')
watermark_file = open('watermark.pdf', 'rb')
# Create an instance of PdfFileWriter for the watermarked PDF
pdf_writer = PyPDF2.PdfFileWriter()
# Create an instance of PdfFileReader for the original PDF
pdf_reader = PyPDF2.PdfFileReader(pdf_file)

Next, you’ll need to select the watermark page that you want to add to each page of the original PDF. You can use the getPage method and specify the watermark page number:

# Select the watermark page (page number starts from 0)
watermark_page_number = 0
watermark_page = PyPDF2.PdfFileReader(watermark_file).getPage(watermark_page_number)

Once you have the watermark page, you can iterate over the pages of the original PDF and add the watermark using the mergePage method:

# Iterate over the pages of the original PDF
for page_number in range(pdf_reader.numPages):
# Get the current page
page = pdf_reader.getPage(page_number)
# Merge the watermark page with the current page
page.mergePage(watermark_page)
# Add the watermarked page to the PDF writer
pdf_writer.addPage(page)

After merging the pages, you can save the watermarked PDF to a new file using the write method:

# Save the watermarked PDF to a new file
output_file = open('watermarked_document.pdf', 'wb')
pdf_writer.write(output_file)
output_file.close()

Remember to close the PDF files when you’re done:

# Close the PDF files
pdf_file.close()
watermark_file.close()

Как шифровать PDF

To encrypt a PDF document with a password, you can use the encrypt method of the PdfFileWriter class from the PyPDF2 module. First, you’ll need to open the PDF file and create an instance of PdfFileReader, just like in the previous examples:

import PyPDF2
# Open the PDF file
pdf_file = open('document.pdf', 'rb')
# Create an instance of PdfFileReader
pdf_reader = PyPDF2.PdfFileReader(pdf_file)

Next, you can create an instance of PdfFileWriter and add the pages from the original PDF:

# Create an instance of PdfFileWriter
pdf_writer = PyPDF2.PdfFileWriter()
# Add the pages from the original PDF
for page_number in range(pdf_reader.numPages):
page = pdf_reader.getPage(page_number)
pdf_writer.addPage(page)

After adding the pages, you can encrypt the PDF with a password using the encrypt method:

# Encrypt the PDF with a password
password = "secret"
pdf_writer.encrypt(password)

Finally, you can save the encrypted PDF to a new file using the write method:

# Save the encrypted PDF to a new file
output_file = open('encrypted_document.pdf', 'wb')
pdf_writer.write(output_file)
output_file.close()

Remember to close the PDF file when you’re done:

# Close the PDF file
pdf_file.close()

Теперь у вас есть подробная информация о том, как работать с PDF в Python с помощью пакета PyPDF2. Вы можете использовать этот пакет для извлечения информации из PDF, поворота страниц, объединения и разделения PDF-файлов, добавления водяных знаков и шифрования PDF.

If you want to further explore working with PDF in Python, you can refer to the official PyPDF2 documentation.