2017-06-05 35 views
2
def EncryptPDFFiles(password, directory): 
    pdfFiles = [] 
    success = 0 

    # Get all PDF files from a directory 
    for folderName, subFolders, fileNames in os.walk(directory): 
     for fileName in fileNames: 
      if (fileName.endswith(".pdf")): 
       pdfFiles.append(os.path.join(folderName, fileName)) 
    print("%s PDF documents found." % str(len(pdfFiles))) 

    # Create an encrypted version for each document 
    for pdf in pdfFiles: 
     # Copy old PDF into a new PDF object 
     pdfFile = open(pdf,"rb") 
     pdfReader = PyPDF2.PdfFileReader(pdfFile) 
     pdfWriter = PyPDF2.PdfFileWriter() 
     for pageNum in range(pdfReader.numPages): 
      pdfWriter.addPage(pdfReader.getPage(pageNum)) 
     pdfFile.close() 

     # Encrypt the new PDF and save it 
     saveName = pdf.replace(".pdf",ENCRYPTION_TAG) 
     pdfWriter.encrypt(password) 
     newFile = open(saveName, "wb") 
     pdfWriter.write(newFile) 
     newFile.close() 
     print("%s saved to: %s" % (pdf, saveName)) 


     # Verify the the encrypted PDF encrypted properly 
     encryptedPdfFile = open(saveName,"rb") 
     encryptedPdfReader = PyPDF2.PdfFileReader(encryptedPdfFile) 
     canDecrypt = encryptedPdfReader.decrypt(password) 
     encryptedPdfFile.close() 
     if (canDecrypt): 
      print("%s successfully encrypted." % (pdf)) 
      send2trash.send2trash(pdf) 
      success += 1 

    print("%s of %s successfully encrypted." % (str(success),str(len(pdfFiles)))) 

我跟隨Pythons自動化鏜孔部分。我在爲PDF文檔製作副本時遇到了問題,但現在每次運行程序時,我的複製PDF都是空白頁。我新加密的PDF格式的頁面數量正確,但都是空白的(頁面上沒有內容)。我以前發生過這種情況,但無法重新創建。我已經嘗試在關閉文件之前投入睡眠。我不確定在Python中打開和關閉文件的最佳做法是什麼。爲了參考我正在使用Python3。PyPDF2複製後返回空白PDF

回答

2

嘗試將pdfFile.close移動到for循環的最後。

for pdf in pdfFiles: 
    # 
    # {stuff} 
    # 
    if (canDecrypt): 
     print("%s successfully encrypted." % (pdf)) 
     send2trash.send2trash(pdf) 
     success += 1 

    pdfFile.close() 

的想法是,pdfFile需要可供並打開時,pdfWriter終於寫出,否則就不能訪問頁面寫入新文件。

+1

謝謝,這似乎已經奏效(但在將其發送給垃圾箱之前,必須將其關閉)。您肯定似乎是正確的,因爲PDFReader需要保持打開狀態,直到pdfWriter寫入並關閉。我想我有一個錯誤的假設,即「getPage」函數創建了作者所需的所有信息。如果作者依賴於即使已經存儲了頁面對象仍然被打開的閱讀器,它似乎違反直覺。 再次感謝! – stryker14