wxPython と pymupdf を使用した PDF 暗号化

PDF ファイルは一般的なドキュメント形式ですが、機密情報を不正アクセスから保護したい場合があります。この記事では、Python と wxPython ライブラリを使用して、PDF ファイルを暗号化するための単純なグラフィカル ユーザー インターフェイス (GUI) アプリケーションを作成します。
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()

上記のコードはアプリケーション クラスを作成しAppif __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 ファイルを暗号化するための簡単な GUI アプリケーションを作成する方法について説明します。PDF ファイルを選択してパスワードを入力すると、PDF ファイルを暗号化して内容を安全に保つことができます。

おすすめ

転載: blog.csdn.net/winniezhang/article/details/132428860