PyPDF 2 Decrypt Not Working

前端 未结 7 1262
悲哀的现实
悲哀的现实 2020-12-15 20:38

Currently I am using the PyPDF 2 as a dependency.

I have encountered some encrypted files and handled them as you normally would (in the following code):

<         


        
7条回答
  •  悲哀的现实
    2020-12-15 21:06

    It has nothing to do with whether the file has been decrypted or not when using the method getNumPages().

    If we take a look at the source code of getNumPages():

    def getNumPages(self):
        """
        Calculates the number of pages in this PDF file.
    
        :return: number of pages
        :rtype: int
        :raises PdfReadError: if file is encrypted and restrictions prevent
            this action.
        """
    
        # Flattened pages will not work on an Encrypted PDF;
        # the PDF file's page count is used in this case. Otherwise,
        # the original method (flattened page count) is used.
        if self.isEncrypted:
            try:
                self._override_encryption = True
                self.decrypt('')
                return self.trailer["/Root"]["/Pages"]["/Count"]
            except:
                raise utils.PdfReadError("File has not been decrypted")
            finally:
                self._override_encryption = False
        else:
            if self.flattenedPages == None:
                self._flatten()
            return len(self.flattenedPages)
    

    we will notice that it is the self.isEncrypted property controlling the flow. And as we all know the isEncrypted property is read-only and not changeable even when the pdf is decrypted.

    So, the easy way to handle the situation is just add the password as key-word argument with empty string as default value and pass your password when using the getNumPages() method and any other method build beyond it

提交回复
热议问题