使用 wxPython 和 pymupdf进行 PDF 加密

本文详细描述了如何利用Python和wxPython库开发一个简单的应用程序,通过图形用户界面允许用户选择PDF文件并输入密码进行加密,以保护文档内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

准备工作

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

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

创建 GUI 应用程序

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

import wx
import fitz

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

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

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,并运行主循环:

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 文件并输入密码来加密它。

全部代码

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 文件以保护其内容的安全性。

2016出版新书,2016.2.27重新上传,此pdf比我之前(2016.01.05)上传的那个版本更好。 Paperback: 304 pages Publisher: Packt Publishing - ebooks Account (January 6, 2016) Language: English ISBN-10: 1785287737 ISBN-13: 978-1785287732 Key Features This book empowers you to create rich cross-platform graphical user interfaces using Python It helps you develop applications that can be deployed on Windows, OSX, and Linux The recipes in the book involve real-world applications, giving you a first-hand experience of the practical scenarios Book Description wxPython is a GUI toolkit for the Python programming language built on top of the cross-platform wxWidgets GUI libraries. wxPython provides a powerful set of tools that allow you to quickly and efficiently building applications that can run on a variety of different platforms. Since wxWidgets provides a wrapper around each platform's native GUI toolkit, the applications built with wxPython will have a native look and feel wherever they are deployed. This book will provide you with the skills to build highly functional and native looking user interfaces for Python applications on multiple operating system environments. By working through the recipes, you will gain insights into and exposure to creating applications using wxPython. With a wide range of topics covered in the book, there are recipes to get the most basic of beginners started in GUI programming as well as tips to help experienced users get more out of their applications. The recipes will take you from the most basic application constructs all the way through to the deployment of complete applications. What you will learn Create full featured user interfaces Design and develop custom controls Deploy and distribute wxPython applications to Windows, Macintosh OS X, Linux, and other UNIX-like environments Handle and respond to application events Manage and display data using grids Interact with web services from your GUI Use Paint events to draw custom displays Support the display of user interfaces in multiple languages
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值