【问题标题】:Powershell GUI using PDF Sharp for password protectionPowershell GUI 使用 PDF Sharp 进行密码保护
【发布时间】:2021-02-11 20:44:21
【问题描述】:

我正在尝试创建一个简单的表单来执行以下操作

  1. 浏览已创建的 pdf
  2. 有一个文本框,可以接受用于创建密码的文本/数字/特殊字符
  3. 提示保存受密码保护的 pdf 文件的位置,并在末尾添加 _protected 或其他内容,以便我可以将其保存在同一个位置而不会覆盖。 我确实创建了一部分代码,但我遇到了诸如 - 如何创建一个按钮来帮助我找到目标位置? 我似乎无法使文本框充当密码输入,而且似乎当我单击浏览按钮时它没有正确加载文件? 仅使用带有参数的 set-pdf 密码运行代码本身效果很好(不是我的代码),但我似乎在为此创建表单时遇到问题。 谁能提供一些关于热门问题的提示?
#############################################Functions##################################################################
function Set-PdfPassword {
<#
.SYNOPSIS
Protects the PDF with a password
.PARAMETER SourceFile
Path to the SourceFile
.PARAMETER DestinationFile
Password for the file
.PARAMETER Password
Full path of the password protected PDF
.PARAMETER PdfSharpPath
Full path to the required PdfSharp library
.PARAMETER Force
Tries to force destination file and directory creation and deletion of source files, even when they are read-only
.PARAMETER
RemoveSourceFiles
Deletes the source files after PDF is merged
.EXAMPLE
Set-PdfPassword -SourceFile "C:\TEMP\test.pdf" -DestinationFile "C:\TEMP\protected_test.pdf" -Password "SECRET" -PdfSharpPath 'C:\ProgramData\coolOrange\powerJobs\Modules\PdfSharp-gdi.dll' -Force -RemoveSourceFiles
#>
param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[System.IO.FileInfo]$SourceFile=
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[System.IO.FileInfo]$DestinationFile,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$Password=
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
$PdfSharpPath,
[switch]$Force,
[switch]$RemoveSourceFiles
)

    Write-Host ">> $($MyInvocation.MyCommand.Name) >>"

    if((Test-Path $PdfSharpPath) -eq $false) {
        throw "Could not find pdfsharp assembly at $($PdfSharpPath)"
    }
    Add-Type -LiteralPath $PdfSharpPath

    if((Test-Path $DestinationFile.FullName) -and $DestinationFile.IsReadOnly -and -not $Force) {
        throw "Destination file '$($DestinationFile.FullName)' is read only"
    }

    $document = [PdfSharp.Pdf.IO.PdfReader]::Open($SourceFile.FullName)
    $securitySettings = $document.SecuritySettings;
    
    # Set Password
    $securitySettings.UserPassword = $Password

    # Restrict some permissions
    $securitySettings.PermitAccessibilityExtractContent = $false;
    $securitySettings.PermitAnnotations = $false;
    $securitySettings.PermitAssembleDocument = $false;
    $securitySettings.PermitExtractContent = $false;
    $securitySettings.PermitFormsFill = $true;
    $securitySettings.PermitFullQualityPrint = $false;
    $securitySettings.PermitModifyDocument = $true;
    $securitySettings.PermitPrint = $false;

    Write-Host "Saving PDF"
    if((Test-Path $DestinationFile.FullName) -and $Force) { 
        Remove-Item $DestinationFile.FullName -Force 
    }
    $document.Save($DestinationFile.FullName)
}

function Select-FolderDialog {
  param([String]$Description="Select Folder", 
        [String]$RootFolder="Desktop")   

  $objForm = New-Object System.Windows.Forms.FolderBrowserDialog
  $objForm.Rootfolder = $RootFolder
  $objForm.Description = $Description
  $Show = $objForm.ShowDialog()
  if ($Show -eq "OK")
  {
     return $objForm.SelectedPath
  }
}
Function Get-FileName($initialDirectory)
{   
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
    Out-Null

    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.initialDirectory = $initialDirectory
    $OpenFileDialog.filter = "PDF Files (*.pdf)| *.pdf|All files (*.*)|*.*"
    $OpenFileDialog.ShowDialog() | Out-Null
    $OpenFileDialog.filename
} 

###################### CREATING PS GUI TOOL #############################

    #### Form settings #################################################################
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")  
    $Form = New-Object System.Windows.Forms.Form
    $Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle #modifies the window border
    $Form.Text = "Powershell Password Generator"    
    $Form.Size = New-Object System.Drawing.Size(1010,400)  
    $Form.StartPosition = "CenterScreen" #loads the window in the center of the screen
    $Form.BackgroundImageLayout = "Zoom"
    $Form.MinimizeBox = $False
    $Form.MaximizeBox = $False
    $Form.WindowState = "Normal"
    $Form.SizeGripStyle = "Hide"
    $Icon = [system.drawing.icon]::ExtractAssociatedIcon($PSHOME + "\powershell.exe")
    $Form.Icon = $Icon
     #### Title - Powershell GUI Tool ###################################################
    $Label = New-Object System.Windows.Forms.Label
    $LabelFont = New-Object System.Drawing.Font("Calibri",18,[System.Drawing.FontStyle]::Bold)
    $Label.Font = $LabelFont
    $Label.Text = "PasswordProtector v.1"
    $Label.AutoSize = $True
    $Label.Location = New-Object System.Drawing.Size(415,40) 
    $Form.Controls.Add($Label)
        #### Input window with "Password For PDF" label ##########################################
    $InputBox = New-Object System.Windows.Forms.TextBox 
    $InputBox.Location = New-Object System.Drawing.Size(10,50) 
    $InputBox.Size = New-Object System.Drawing.Size(180,20) 
    $Form.Controls.Add($InputBox)
    $Label2 = New-Object System.Windows.Forms.Label
    $Label2.Text = "Enter Password for PDF"
    $Label2.AutoSize = $True
    $Label2.Location = New-Object System.Drawing.Size(15,30) 
    $Form.Controls.Add($Label2)
     #### Group boxes for buttons ########################################################
    $groupBox = New-Object System.Windows.Forms.GroupBox
    $groupBox.Location = New-Object System.Drawing.Size(10,95) 
    $groupBox.size = New-Object System.Drawing.Size(180,270)
    $groupBox.text = "Options" 
    
    $Form.Controls.Add($groupBox)
        #### Browse #################################################################
    $Browse = New-Object System.Windows.Forms.Button
    $Browse.Location = New-Object System.Drawing.Size(15,30)
    $Browse.Size = New-Object System.Drawing.Size(150,60)
    $Browse.Text = "Browse For PDF"
    $Browse.Add_Click({Get-FileName})
    $Browse.Cursor = [System.Windows.Forms.Cursors]::Hand
    $groupBox.Controls.Add($Browse)
            #### Output #################################################################
    $Password = New-Object System.Windows.Forms.Button
    $Password.Location = New-Object System.Drawing.Size(15,110)
    $Password.Size = New-Object System.Drawing.Size(150,60)
    $Password.Text = "Set PDF Password"
    $Password.Add_Click({Set-PdfPassword})
    $Password.Cursor = [System.Windows.Forms.Cursors]::Hand
    $groupBox.Controls.Add($Password)
    ###################### END BUTTONS ######################################################

    #### Output Box Field ###############################################################
    $outputBox = New-Object System.Windows.Forms.RichTextBox
    $outputBox.Location = New-Object System.Drawing.Size(200,100) 
    $outputBox.Size = New-Object System.Drawing.Size(780,265)
    $outputBox.Font = New-Object System.Drawing.Font("Consolas", 8 ,[System.Drawing.FontStyle]::Regular)
    $outputBox.MultiLine = $True
    $outputBox.ScrollBars = "Vertical"
    $outputBox.Text = " `
          Welcome to PDF Password Generator."
    $Form.Controls.Add($outputBox)

    ##############################################

    $Form.Add_Shown({$Form.Activate()})
    [void] $Form.ShowDialog()

【问题讨论】:

    标签: powershell user-interface powershell-4.0 pdfsharp


    【解决方案1】:

    我没有 PDF Sharp Library,所以无法完整测试,但我做了一些更改以检索选定的源文件,计算带有“_Protected”后缀的目标文件并将这些信息添加到输出富文本框中

    #Functions
    function Set-PdfPassword {
    <#
    .SYNOPSIS
    Protects the PDF with a password
    .PARAMETER SourceFile
    Path to the SourceFile
    .PARAMETER DestinationFile
    Password for the file
    .PARAMETER Password
    Full path of the password protected PDF
    .PARAMETER PdfSharpPath
    Full path to the required PdfSharp library
    .PARAMETER Force
    Tries to force destination file and directory creation and deletion of source files, even when they are read-only
    .PARAMETER
    RemoveSourceFiles
    Deletes the source files after PDF is merged
    .EXAMPLE
    Set-PdfPassword -SourceFile "C:\TEMP\test.pdf" -DestinationFile "C:\TEMP\protected_test.pdf" -Password "SECRET" -PdfSharpPath 'C:\ProgramData\coolOrange\powerJobs\Modules\PdfSharp-gdi.dll' -Force -RemoveSourceFiles
    #>
    param(
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [System.IO.FileInfo]$SourceFile=
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [System.IO.FileInfo]$DestinationFile,
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$Password=
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    $PdfSharpPath,
    [switch]$Force,
    [switch]$RemoveSourceFiles
    )
    
        Write-Host ">> $($MyInvocation.MyCommand.Name) >>"
    
        if((Test-Path $PdfSharpPath) -eq $false) {
            throw "Could not find pdfsharp assembly at $($PdfSharpPath)"
        }
        Add-Type -LiteralPath $PdfSharpPath
    
        if((Test-Path $DestinationFile.FullName) -and $DestinationFile.IsReadOnly -and -not $Force) {
            throw "Destination file '$($DestinationFile.FullName)' is read only"
        }
    
        $document = [PdfSharp.Pdf.IO.PdfReader]::Open($SourceFile.FullName)
        $securitySettings = $document.SecuritySettings;
    
        # Set Password
        $securitySettings.UserPassword = $Password
        
        # Restrict some permissions
        $securitySettings.PermitAccessibilityExtractContent = $false;
        $securitySettings.PermitAnnotations = $false;
        $securitySettings.PermitAssembleDocument = $false;
        $securitySettings.PermitExtractContent = $false;
        $securitySettings.PermitFormsFill = $true;
        $securitySettings.PermitFullQualityPrint = $false;
        $securitySettings.PermitModifyDocument = $true;
        $securitySettings.PermitPrint = $false;
    
        Write-Host "Saving PDF"
        if((Test-Path $DestinationFile.FullName) -and $Force) { 
            Remove-Item $DestinationFile.FullName -Force 
        }
        $document.Save($DestinationFile.FullName)
    }
    
    function Select-FolderDialog {
      param([String]$Description="Select Folder", 
            [String]$RootFolder="Desktop")   
    
      $objForm = New-Object System.Windows.Forms.FolderBrowserDialog
      $objForm.Rootfolder = $RootFolder
      $objForm.Description = $Description
      $Show = $objForm.ShowDialog()
      if ($Show -eq "OK")
      {
         return $objForm.SelectedPath
    
    
      }
    }
    Function Get-FileName($initialDirectory)
    {   
        [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
        Out-Null
    
        $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
        $OpenFileDialog.initialDirectory = $initialDirectory
        $OpenFileDialog.filter = "PDF Files (*.pdf)| *.pdf|All files (*.*)|*.*"
        $OpenFileDialog.ShowDialog() | Out-Null
        $OpenFileDialog.filename
    
        $Script:SourceFile = $OpenFileDialog.filename
    
        $Filename = [System.IO.Path]::GetFileNameWithoutExtension($OpenFileDialog.SafeFileName)
        $FileExtension = [System.IO.Path]::GetExtension($OpenFileDialog.SafeFileName)
        $FileFolder = split-path $SourceFile -Parent
        $Script:DestinationFile = $FileFolder + "\" + $Filename + "_Protected" + $FileExtension
    
        $outputBox.Appendtext("$([char]10)")
        $outputBox.Appendtext("$([char]10)")
        $outputBox.Appendtext("Selected File :")
        $outputBox.Appendtext("$([char]10)")
        $outputBox.Appendtext($SourceFile)
        $outputBox.Appendtext("$([char]10)")
        $outputBox.Appendtext("will be saved to :")
        $outputBox.Appendtext("$([char]10)")
        $outputBox.Appendtext($DestinationFile)
    } 
    
        # CREATING PS GUI TOOL
    
        #Form settings
        [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
        [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")  
        $Form = New-Object System.Windows.Forms.Form
        $Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle #modifies the window border
        $Form.Text = "Powershell Password Generator"    
        $Form.Size = New-Object System.Drawing.Size(1010,400)  
        $Form.StartPosition = "CenterScreen" #loads the window in the center of the screen
        $Form.BackgroundImageLayout = "Zoom"
        $Form.MinimizeBox = $False
        $Form.MaximizeBox = $False
        $Form.WindowState = "Normal"
        $Form.SizeGripStyle = "Hide"
        $Icon = [system.drawing.icon]::ExtractAssociatedIcon($PSHOME + "\powershell.exe")
        $Form.Icon = $Icon
        #Title - Powershell GUI Tool
        $Label = New-Object System.Windows.Forms.Label
        $LabelFont = New-Object System.Drawing.Font("Calibri",18,[System.Drawing.FontStyle]::Bold)
        $Label.Font = $LabelFont
        $Label.Text = "PasswordProtector v.1"
        $Label.AutoSize = $True
        $Label.Location = New-Object System.Drawing.Size(415,40) 
        $Form.Controls.Add($Label)
        #Input window with "Password For PDF" label
        $InputBox = New-Object System.Windows.Forms.TextBox 
        $InputBox.Location = New-Object System.Drawing.Size(10,50) 
        $InputBox.Size = New-Object System.Drawing.Size(180,20) 
        $Form.Controls.Add($InputBox)
    
        $Label2 = New-Object System.Windows.Forms.Label
        $Label2.Text = "Enter Password for PDF"
        $Label2.AutoSize = $True
        $Label2.Location = New-Object System.Drawing.Size(15,30) 
        $Form.Controls.Add($Label2)
        #Group boxes for buttons
        $groupBox = New-Object System.Windows.Forms.GroupBox
        $groupBox.Location = New-Object System.Drawing.Size(10,95) 
        $groupBox.size = New-Object System.Drawing.Size(180,270)
        $groupBox.text = "Options" 
    
        $Form.Controls.Add($groupBox)
        #Browse
        $Browse = New-Object System.Windows.Forms.Button
        $Browse.Location = New-Object System.Drawing.Size(15,30)
        $Browse.Size = New-Object System.Drawing.Size(150,60)
        $Browse.Text = "Browse For PDF"
        $Browse.Add_Click({Get-FileName})
        $Browse.Cursor = [System.Windows.Forms.Cursors]::Hand
        $groupBox.Controls.Add($Browse)
        #Output
        $PasswordButton = New-Object System.Windows.Forms.Button
        $PasswordButton.Location = New-Object System.Drawing.Size(15,110)
        $PasswordButton.Size = New-Object System.Drawing.Size(150,60)
        $PasswordButton.Text = "Set PDF Password"
        $PasswordButton.Add_Click({Set-PdfPassword -sourcefile $SourceFile -DestinationFile $DestinationFile -Password ($InputBox.Text)})
        $PasswordButton.Cursor = [System.Windows.Forms.Cursors]::Hand
        $groupBox.Controls.Add($PasswordButton)
        #END BUTTONS
    
        #Output Box Field
        $outputBox = New-Object System.Windows.Forms.RichTextBox
        $outputBox.Location = New-Object System.Drawing.Size(200,100) 
        $outputBox.Size = New-Object System.Drawing.Size(780,265)
        $outputBox.Font = New-Object System.Drawing.Font("Consolas", 8 ,[System.Drawing.FontStyle]::Regular)
        $outputBox.MultiLine = $True
        $outputBox.ScrollBars = "Vertical"
        $outputBox.Text = " `
              Welcome to PDF Password Generator."
        $Form.Controls.Add($outputBox)
    
        $Form.Add_Shown({$Form.Activate()})
        [void] $Form.ShowDialog()
    

    【讨论】:

    • Split-Path : Cannot bind argument to parameter 'Path' because it is an empty string. At line:103 char:30 + $FileFolder = split-path $SourceFile -Parent + ~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Split-Path], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.SplitPathCommand
    • Set-PdfPassword : A parameter cannot be found that matches parameter name 'DestinationFile'. At line:173 char:72 + ... ick({Set-PdfPassword -sourcefile $SourceFile -DestinationFile $Destin ... + ~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Set-PdfPassword], ParameterBindingException + FullyQualifiedErrorId : NamedParameterNotFound,Set-PdfPassword
    • 以上两个错误很可能是由于我在工作时在这台笔记本电脑上没有的 pdf sharp 库,当我进入我的个人电脑时会解决,因为这是一个个人迷你项目,感谢您的编辑/更改和帮助 - 今天晚些时候会回到这篇文章。
    • 第 25 行,请将等号改为逗号:“[System.IO.FileInfo]$SourceFile=" 必须为 :”[System.IO.FileInfo]$SourceFile,"
    • 运行此脚本并将 dll 添加到脚本运行的文件夹中似乎没有检测到它。 ` Test-Path : 无法将参数绑定到参数“路径”,因为它为空。在 C:\Users\lored\Downloads\powershell script\powershell\script.ps1:42 char:17 + if ((Test-Path $PdfSharpPath) -eq $false) + ~~~~~~~~~~~~ ~~ + CategoryInfo : InvalidData: (:) [Test-Path], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand `
    猜你喜欢
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 2020-07-18
    • 2016-09-19
    • 2010-09-27
    • 1970-01-01
    相关资源
    最近更新 更多