天天看點

python讀取帶密碼的pdf_Python從受密碼保護的pdf擷取頁面數

python讀取帶密碼的pdf_Python從受密碼保護的pdf擷取頁面數

I've been trying to figure out a way to get the number of pages from password protected pdf with python3. So far I have tried modules pypdf2 and pdfminer2.

Both are failing because the file is not decrypted.

#!/usr/bin/python3

from PyPDF2 import PdfFileReader

pdfFile = PdfFileReader(open("document.pdf", "rb"))

print(pdfFile.numPages)

This code will produce an Error:

PyPDF2.utils.PdfReadError: File has not been decrypted

Is there a way to get the number of pages without decrypting?

解決方案

You can use pdfrw

Example,

a.pdf and b.pdf are same pdf. Difference is b.pdf is password protected pdf and a.pdf is simple pdf without any protection and no of pages are 30

>>> from pdfrw import PdfReader

>>> print len(PdfReader('b.pdf').pages)

30

>>> print len(PdfReader('a.pdf').pages)

30

For install use following command

pip install pdfrw

For in detail