Как использовать 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
Установка производится быстро, так как 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
:
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:
You can also retrieve other information, such as the title and author, using the getDocumentInfo
method:
Remember to close the PDF file when you’re done:
Как поворачивать страницы 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:
Next, you’ll need to select the page you want to rotate. You can use the getPage
method and specify the 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:
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:
Remember to close the PDF files when you’re done:
Как объединять 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
:
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:
Once you have added all the PDF files, you can save the merged PDF to a new file using the write
method:
After merging the PDF files, remember to close the output file:
Как разделять 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:
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:
Remember to close the PDF file when you’re done:
Как добавлять водяные знаки в 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:
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:
Once you have the watermark page, you can iterate over the pages of the original PDF and add the watermark using the mergePage
method:
After merging the pages, you can save the watermarked PDF to a new file using the write
method:
Remember to close the PDF files when you’re done:
Как шифровать 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:
Next, you can create an instance of PdfFileWriter
and add the pages from the original PDF:
After adding the pages, you can encrypt the PDF with a password using the encrypt
method:
Finally, you can save the encrypted PDF to a new file using the write
method:
Remember to close the PDF file when you’re done:
Теперь у вас есть подробная информация о том, как работать с 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.