06/02/2018

Password Protect PDF document using windows Powershell script

By snorlaxprime

Password protect PDF document can be done using Windows Powershell script. I stumble across a powerful script which allow to password protect PDF document using the script. The requirement that I have is to password protect a list of batch PDF document with a specified password that are different between each document and then sending each password protected PDF document to different individual emails.

So after researching for a while I found the script that does the job, but then I come across another hurdle, how do I get the list of password and the list of pdf, so my solution is to put the list of pdf files along with the password in an excel document, and let the script open the excel find the first pdf document, then read the designated password next to it, and run the script to password protect the file and save the password protected file in a different location.

So hunting around for the powershell script to read excel proven to be fruitful, so I combine both of them into one script. Here are the step by step on what I had done and how to modify this to suit your need. This proven to speed up the manual work by a lot. Not to imagine the time and cost savings that comes along with it.

Step 1. Create the list with location of PDF document and the password that you want to protect the document with.

In picture below, we have the source of document in column B, and the target encrypted PDF file name will be located in the location specified in column C. The password for each document will be based on the information in column D. Save this Excel file in C:\temp\ location and lets call the file Book2.xlsx for this exercise.

Step 2. Open your favourite text editor and paste in the following code, you can also use the “Windows PowerShell ISE“:

[System.Reflection.Assembly]::LoadFrom("itextsharp.dll")

function PSUsing {
 param (
 [System.IDisposable] $inputObject = $(throw "The parameter -inputObject is required."),
 [ScriptBlock] $scriptBlock = $(throw "The parameter -scriptBlock is required.")
 )
 
 Try {
 &$scriptBlock
 }
 Finally {
 if ($inputObject.psbase -eq $null) {
 $inputObject.Dispose()
 } else {
 $inputObject.psbase.Dispose()
 }
 }
}

$xlCellTypeLastCell = 11 
$startRow,$col=2,1

$excel=new-object -com excel.application
$wb=$excel.workbooks.open("c:\temp\Book2.xlsx")

for ($i=1; $i -le $wb.sheets.count; $i++)
 {
 $j=0;
 $sh=$wb.Sheets.Item($i)
 $endRow=$sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row
 $rangeAddress=$sh.Cells.Item($startRow+1,$col).Address() + ":" +$sh.Cells.Item($endRow+1,$col).Address()
 $sh.Range($rangeAddress).Value2 | foreach {
 $contract=$sh.Cells.Item($startRow + $j,$col).Value2
 $filesource = $sh.Cells.Item($startRow + $j,$col+1).Value2
 $filedest = $sh.Cells.Item($startRow + $j,$col+2).Value2
 $dob=$sh.Cells.Item($startRow + $j,$col+3).Value2
 
 New-Object PSObject -Property @{Contract=$contract;Dob=$dob}
 
 $file = New-Object System.IO.FileInfo $filesource
 $fileWithPassword = New-Object System.IO.FileInfo $filedest
 $password = $dob
 PSUsing ( $fileStreamIn = $file.OpenRead() ) { 
 PSUsing ( $fileStreamOut = New-Object System.IO.FileStream($fileWithPassword.FullName,[System.IO.FileMode]::Create,[System.IO.FileAccess]::Write,[System.IO.FileShare]::None) ) { 
 PSUsing ( $reader = New-Object iTextSharp.text.pdf.PdfReader $fileStreamIn ) {
 [iTextSharp.text.pdf.PdfEncryptor]::Encrypt($reader, $fileStreamOut, $true, $password, $password, [iTextSharp.text.pdf.PdfWriter]::ALLOW_PRINTING)
 }
 }
 }
 
 $j++
 }
}
$excel.Workbooks.Close()

Step 3. Make sure you have the itextsharp.dll library located in the same location as the PowerShell Script.

In this example it should be located in C:\Temp\. You should have the folder structure that looks similar to the one below.

Step 4. Put the source PDF files as specified in the step 1. Execute the Powershell Script by clicking on the execute button if you are using Windows PowerShell ISE.

Step 5. If everything went well, you should be able to see the execution message as per the picture below.

Step 6. The destination folders specified in excel step 1. should contain all the password protected PDF, as shown below.

Now you can tested these Password Protected PDF files by opening it using the password that you had specified in Step 1.

Please leave me a comments if you like this post. Like it if this help you to save some time in automating some of the boring task.