使用PyPDF2加密和解密PDF

使用PyPDF2加密和解密PDF

使用PyPDF2加密和解密PDF

  PDF便携式文档格式)是用于存储和发送文档的最常用的文件格式之一。它们通常用于许多目的,例如电子书、简历、扫描文档等。但是当我们将 pdf 共享给许多人时,其数据有可能被泄露或被盗。因此,有必要对我们的 PDF 文件进行密码保护,以便只有经过授权的人才能访问它。

使用PyPDF2加密和解密PDF

  在本文中,我们将了解如何设置密码来保护 PDF 文件。我们晓得博客将使用PyPDF2加密和解密PDF。PyPDF2是一个作为 PDF 工具包构建的 Python 库。它能够:

  • 提取文档信息(标题、作者……)
  • 拆分和合并文档
  • 裁剪页面
  • 加密和解密PDF文件

安装

  PyPDF2 不是内置库,因此我们必须安装它。

pip3 install PyPDF2

  现在,我们已准备好编写脚本来加密 PDF 文件。

  推荐:使用Python将文本和txt文件转换为PDF

加密PDF文件

  首先, 我们将使用 reader 对象打开我们的 PDF 文件。然后,我们将创建原始文件的副本,这样如果出现问题,就不会影响我们的原始文件。要创建副本,我们必须遍历文件的每一页并将其添加到我们的新 PDF 文件中。然后,我们可以简单地加密我们的新 PDF 文件。

使用的 PDF 文件:

加密PDF文件
  • Python 3
from PyPDF2 import PdfFileWriter, PdfFileReader

out = PdfFileWriter()

file = PdfFileReader("BeautifulSoup-tutorial.pdf")

# Get number of pages in original file
num = file.numPages

for idx in range(num):
	
	# Get the page at index idx
	page = file.getPage(idx)
	
	# Add it to the output file
	out.addPage(page)


# Create a variable password and store our password in it.
password = "pythonthree.com"

# Encrypt the new file with the entered password
out.encrypt(password)

with open("my_new_file.pdf.pdf", "wb") as f:
	
	# Write our encrypted PDF to this file
	out.write(f)

输出:

加密PDF文件密码

  这将创建原始文件的副本并使用输入的密码对其进行加密。PDF一旦加密,不输入正确密码就无法打开。

解密PDF文件

  但是如果我们想解密加密的PDF文件呢?我们也可以用这个 库来做到这一点。过程几乎相同。我们将使用正确的密码打开加密文件,并通过遍历它的每一页并将其添加到我们的新 PDF 文件中来创建它的副本。

  这是Python 3代码:

from PyPDF2 import PdfFileWriter, PdfFileReader

# Create a PdfFileWriter object
out = PdfFileWriter()

file = PdfFileReader("my_new_file.pdf")

# Store correct password in a variable password.
password = "pythonthree.com"

# Check if the opened file is actually Encrypted
if file.isEncrypted:

	# If encrypted, decrypt it with the password
	file.decrypt(password)

	for idx in range(file.numPages):
		page = file.getPage(idx)
		out.addPage(page)
	
	with open("my_new_file.pdf", "wb") as f:
		
		# Write our decrypted PDF to this file
		out.write(f)

	# Print success message when Done
	print("File decrypted Successfully.")
else:
	
	print("File already decrypted.")

  这将创建不需要密码即可打开的加密文件的副本。这是加密和解密 PDF 文件的基本脚本。

总结

  以上是晓得博客为你介绍的使用PyPDF2加密和解密PDF文件的全部内容,您可以创建一个GUI 工具来执行此操作或开发一个加密 PDF 文件的Web 应用程序。您还可以使用PyPDF2库创建一个完整的PDF 管理器

  推荐:零基础如何开始学习Python

给文章评分

晓得博客,版权所有丨如未注明,均为原创
晓得博客 » 使用PyPDF2加密和解密PDF

转载请保留链接:https://www.pythonthree.com/encrypt-and-decrypt-pdf-using-pypdf2/

Claude、Netflix、Midjourney、ChatGPT Plus、PS、Disney、Youtube、Office 365、多邻国Plus账号购买,ChatGPT API购买,优惠码XDBK,用户购买的时候输入优惠码可以打95折

Chatgpt-Plus注册购买共享账号
滚动至顶部