PDF加密和解密
from ironpdf import *

# Open an Encrypted File, alternatively create a new PDF from Html
pdf = PdfDocument.FromFile("encrypted.pdf", "password")
 
# Edit file metadata
pdf.MetaData.Author = "Satoshi Nakamoto"
pdf.MetaData.Keywords = "SEO, Friendly"
pdf.MetaData.ModifiedDate = Now()
 
# Edit file security settings
# The following code makes a PDF read only and will disallow copy & paste and printing
pdf.SecuritySettings.RemovePasswordsAndEncryption()
pdf.SecuritySettings.MakePdfDocumentReadOnly("secret-key")
pdf.SecuritySettings.AllowUserAnnotations = False
pdf.SecuritySettings.AllowUserCopyPasteContent = False
pdf.SecuritySettings.AllowUserFormData = False
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights
 
# Change or set the document encryption password
pdf.Password = "my-password"
pdf.SaveAs("secured.pdf")
pip install ironpdf
PDF加密和解密

PDF加密和解密

IronPDF for Python 可以打开受密码保护的PDF文件,修改其元数据和安全设置,并用新密码重新保存,使完整的加密和解密工作流程可以用几行代码实现。

开始

将文件路径和现有密码传递给PdfDocument.FromFile以打开加密的PDF。 根据需要修改安全设置和元数据,然后将新密码分配给SaveAs保存。

理解代码

  • PdfDocument.FromFile(path, password):使用提供的密码打开加密PDF文件进行解密。 如果密码不正确,则引发异常。
  • MetaData.Author / Keywords / ModifiedDate:解密后可以读取或更新的元数据字段。
  • SecuritySettings.RemovePasswordsAndEncryption():从内存中的文档中删除当前加密,允许重新配置安全设置。
  • SecuritySettings.MakePdfDocumentReadOnly(key):以一个新的内部密钥重新应用只读保护。
  • False以限制特定操作。
  • pdf.Password = "my-password":设置一个新密码,要求打开保存的PDF时使用。
  • SaveAs("secured.pdf"):以应用所有新设置保存再加密的文档。

解密无需重新加密

要生成受密码保护PDF的未加密副本,调用Password的情况下保存。

学习使用IronPDF for Python 保护PDF文档!

准备开始了吗?

版本:2026.11刚刚发布