使用 wxPython 和 pymupdf进行 PDF 加密

PDF 文件是一种常见的文档格式,但有时候我们希望对敏感信息进行保护,以防止未经授权的访问。在本文中,我们将使用 Python 和 wxPython 库创建一个简单的图形用户界面(GUI)应用程序,用于对 PDF 文件进行加密。

C:\pythoncode\new\PDFEncrypt.py

准备工作

在开始之前,请确保已经安装了以下库:

  • wxPython:在命令行中运行 pip install wxPython 进行安装
  • PyMuPDF(也称为 fitz):在命令行中运行 pip install PyMuPDF 进行安装

创建 GUI 应用程序

我们将使用 wxPython 库创建 GUI 应用程序。首先,导入必要的库:

python 复制代码
import wx
import fitz

接下来,创建一个主窗口类 MainFrame,继承自 wx.Frame 类:

python 复制代码
class MainFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="PDF Encryption", size=(400, 200))
        panel = wx.Panel(self)
        
        # 创建文件选择器
        self.file_picker = wx.FilePickerCtrl(panel, message="Select a PDF file", style=wx.FLP_USE_TEXTCTRL)
        
        # 创建密码输入框
        self.password_text = wx.TextCtrl(panel, style=wx.TE_PASSWORD)
        
        # 创建加密按钮
        encrypt_button = wx.Button(panel, label="Encrypt")
        encrypt_button.Bind(wx.EVT_BUTTON, self.on_encrypt_button)
        
        # 使用布局管理器设置组件的位置和大小
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(wx.StaticText(panel, label="PDF File:"), 0, wx.ALL, 5)
        sizer.Add(self.file_picker, 0, wx.EXPAND | wx.ALL, 5)
        sizer.Add(wx.StaticText(panel, label="Password:"), 0, wx.ALL, 5)
        sizer.Add(self.password_text, 0, wx.EXPAND | wx.ALL, 5)
        sizer.Add(encrypt_button, 0, wx.ALIGN_CENTER | wx.ALL, 5)
        panel.SetSizerAndFit(sizer)

以上代码创建了一个带有文件选择器、密码输入框和加密按钮的主窗口。

接下来,添加处理加密按钮点击事件的方法 on_encrypt_button

python 复制代码
class MainFrame(wx.Frame):
    # ...

    def on_encrypt_button(self, event):
        filepath = self.file_picker.GetPath()
        password = self.password_text.GetValue()

        if filepath and password:
            try:
                doc = fitz.open(filepath)
                doc.encrypt(password)

                encrypted_filepath = filepath.replace(".pdf", "_encrypted.pdf")
                doc.save(encrypted_filepath)
                doc.close()

                wx.MessageBox("PDF file encrypted successfully!", "Success", wx.OK | wx.ICON_INFORMATION)
            except Exception as e:
                wx.MessageBox(f"An error occurred: {str(e)}", "Error", wx.OK | wx.ICON_ERROR)
        else:
            wx.MessageBox("Please select a PDF file and enter a password.", "Error", wx.OK | wx.ICON_ERROR)

on_encrypt_button 方法中,我们获取用户选择的 PDF 文件路径和输入的密码。然后,使用 PyMuPDF 库打开 PDF 文件,对其进行加密并保存加密后的文件。

最后,创建一个应用程序类 App,并运行主循环:

python 复制代码
class App(wx.App):
    def OnInit(self):
        frame = MainFrame()
        frame.Show()
        return True

if __name__ == "__main__":
    app = App()
    app.MainLoop()

以上代码创建了一个应用程序类 App,并在 if __name__ == "__main__": 代码块中运行应用程序的主循环。

运行应用程序

保存上述代码为 pdf_encryption.py 文件,然后在命令行中运行 python pdf_encryption.py。应用程序窗口将打开,您可以选择一个 PDF 文件并输入密码来加密它。

全部代码

python 复制代码
import wx
import fitz


class MainFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="PDF Encryption", size=(400, 200))
        panel = wx.Panel(self)

        self.file_picker = wx.FilePickerCtrl(panel, message="Select a PDF file", style=wx.FLP_USE_TEXTCTRL)
        self.password_text = wx.TextCtrl(panel, style=wx.TE_PASSWORD)
        encrypt_button = wx.Button(panel, label="Encrypt")
        encrypt_button.Bind(wx.EVT_BUTTON, self.on_encrypt_button)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(wx.StaticText(panel, label="PDF File:"), 0, wx.ALL, 5)
        sizer.Add(self.file_picker, 0, wx.EXPAND | wx.ALL, 5)
        sizer.Add(wx.StaticText(panel, label="Password:"), 0, wx.ALL, 5)
        sizer.Add(self.password_text, 0, wx.EXPAND | wx.ALL, 5)
        sizer.Add(encrypt_button, 0, wx.ALIGN_CENTER | wx.ALL, 5)
        panel.SetSizerAndFit(sizer)

    def on_encrypt_button(self, event):
        filepath = self.file_picker.GetPath()
        password = self.password_text.GetValue()

        if filepath and password:
            try:
                doc = fitz.open(filepath)
                # doc.encrypt(password)

                perm = int(
                    fitz.PDF_PERM_ACCESSIBILITY # always use this
                            | fitz.PDF_PERM_PRINT # permit printing
                            | fitz.PDF_PERM_COPY # permit copying
                            | fitz.PDF_PERM_ANNOTATE # permit annotations
                ) # 可以打印,复制,添加注释                
                owner_pass = "owner" # owner password
                user_pass = password # "user" # user password
                encrypt_meth = fitz.PDF_ENCRYPT_AES_256 # strongest algorithm

                encrypted_filepath = filepath.replace(".pdf", "_encrypted.pdf")
                # doc.save(encrypted_filepath)
                doc.save(encrypted_filepath,encryption=encrypt_meth,owner_pw=owner_pass,permissions=perm,user_pw=user_pass) 
                # doc.save(encrypted_filepath)
                doc.close()

                wx.MessageBox("PDF file encrypted successfully!", "Success", wx.OK | wx.ICON_INFORMATION)
            except Exception as e:
                wx.MessageBox(f"An error occurred: {str(e)}", "Error", wx.OK | wx.ICON_ERROR)
        else:
            wx.MessageBox("Please select a PDF file and enter a password.", "Error", wx.OK | wx.ICON_ERROR)


class App(wx.App):
    def OnInit(self):
        frame = MainFrame()
        frame.Show()
        return True


if __name__ == "__main__":
    app = App()
    app.MainLoop()

总结

本文介绍了如何使用 Python 和 wxPython 库创建一个简单的图形用户界面应用程序,用于对 PDF 文件进行加密。通过选择 PDF 文件和输入密码,您可以加密 PDF 文件以保护其内容的安全性。

相关推荐
皓月盈江1 小时前
使用谷歌浏览器自带功能将网页转换为PDF文件
chrome·pdf·html·网页转pdf·谷歌浏览器打印功能
云只上3 小时前
PDF转excel+json ,vue3+SpringBoot在线演示+附带源码
前端·javascript·spring boot·后端·pdf·json·excel
令狐少侠20113 小时前
AI之pdf解析:Tesseract、PaddleOCR、RapidPaddle(可能为 RapidOCR)和 plumberpdf 的对比分析及使用建议
人工智能·python·pdf
usdoc文档预览4 小时前
Office文件内容提取 | 获取Word文件内容 |Javascript提取PDF文字内容 |PPT文档文字内容提取
javascript·pdf·word·ppt·office文件在线预览·word文档在线预览·ofd预览转pdf
安替-AnTi8 小时前
Google Colab测试部署Qwen大模型,实现PDF转MD场景OCR 识别(支持单机环境)
pdf·ocr·多模态·qwen 2.5·图片转文本
AI偶然10 小时前
AI智能体|扣子(Coze)搭建【一键转换为Word/pdf/Excel】工作流保姆级教学
人工智能·pdf·word
朴拙数科10 小时前
LangChain实现PDF中图表文本多模态数据向量化及RAG应用实战指南
langchain·pdf
青柠过敏10 小时前
Itext进行PDF的编辑开发
pdf
摸鱼仙人~1 天前
开源的 PDF 文件翻译软件
pdf
辣香牛肉面1 天前
PDF多功能转换编辑及扫描仪 iLovePDF 3.10.0
pdf·多功能转换·pdf编辑扫描