Click here to Skip to main content
Click here to Skip to main content
Go to top

Encrypt PDF

, 17 Oct 2009
Rate this:
Please Sign up or sign in to vote.
This Windows application lets you password protect PDF files in a given folder.

Introduction

This complete Windows application lets you password protect your PDF files in a given folder and its subfolders. It uses free iTextSharp library.

Using the code

To use this program, simply select the source and the destination folders. It the program experiences any problems, it will create a log file (Log.txt) in the source folder.

Here is the code:

Private Sub btnFrom_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnFrom.Click
    fldFrom.ShowDialog()
    txtFrom.Text = fldFrom.SelectedPath
End Sub

Private Sub btnTo_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnTo.Click
    fldTo.ShowDialog()
    txtTo.Text = fldTo.SelectedPath
End Sub

Private Sub btnProcess_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnProcess.Click

    If Trim(txtPassword.Text) = "" Then
        MsgBox("Password is missing.")
        Exit Sub
    End If

    Dim sFromPath As String = txtFrom.Text
    Dim sToPath As String = txtTo.Text

    If Not Directory.Exists(sFromPath) Then
        MsgBox("From folder does not exist")
        Exit Sub
    End If

    ProccessFolder(sFromPath, sToPath)

    MsgBox("Done!")
End Sub

Sub ProccessFolder(ByVal sFromPath As String, ByVal sToPath As String)

    If Not Directory.Exists(sToPath) Then
        Try
            Directory.CreateDirectory(sToPath)
        Catch ex As Exception
            MsgBox("To folder does not exist and could not be created.")
            Exit Sub
        End Try
    End If

    Dim oFiles As String() = Directory.GetFiles(sFromPath)
    ProgressBar1.Maximum = oFiles.Length

    btnProcess.Enabled = False
    For i As Integer = 0 To oFiles.Length - 1
        Dim sFromFilePath As String = oFiles(i)
        Dim oFileInfo As New FileInfo(sFromFilePath)
        Dim sToFileName As String = sToPath & "\" & oFileInfo.Name

        If UCase(oFileInfo.Extension) = ".PDF" Then
            Try
                EncryptPdf(sFromFilePath, sToFileName, txtPassword.Text)
            Catch ex As Exception
                Dim oStreamWriter As New StreamWriter(txtFrom.Text & "\Log.txt", True)
                oStreamWriter.WriteLine(sFromFilePath & " " & ex.Message)
                oStreamWriter.Close()
            End Try
        End If

        ProgressBar1.Value = i
    Next

    btnProcess.Enabled = True
    ProgressBar1.Value = 0

    Dim oFolders As String() = Directory.GetDirectories(sFromPath)
    For i As Integer = 0 To oFolders.Length - 1
        Dim sChildFolder As String = oFolders(i)
        Dim iPos As Integer = sChildFolder.LastIndexOf("\")
        Dim sFolderName As String = sChildFolder.Substring(iPos + 1)
        ProccessFolder(sChildFolder, sToPath & "\" & sFolderName)
    Next

End Sub

Sub EncryptPdf(ByVal sInFilePath As String, _
               ByVal sOutFilePath As String, ByVal sPassword As String)

    Dim oPdfReader As iTextSharp.text.pdf.PdfReader = _
                   New iTextSharp.text.pdf.PdfReader(sInFilePath)
    Dim oPdfDoc As New iTextSharp.text.Document()
    Dim oPdfWriter As PdfWriter = PdfWriter.GetInstance(oPdfDoc, _
                   New FileStream(sOutFilePath, FileMode.Create))
    oPdfWriter.SetEncryption(PdfWriter.STRENGTH40BITS, sPassword, _
                             sPassword, PdfWriter.AllowCopy)
    oPdfDoc.Open()

    oPdfDoc.SetPageSize(iTextSharp.text.PageSize.LEDGER.Rotate())

    Dim oDirectContent As iTextSharp.text.pdf.PdfContentByte = oPdfWriter.DirectContent
    Dim iNumberOfPages As Integer = oPdfReader.NumberOfPages
    Dim iPage As Integer = 0

    Do While (iPage < iNumberOfPages)
        iPage += 1
        oPdfDoc.SetPageSize(oPdfReader.GetPageSizeWithRotation(iPage))
        oPdfDoc.NewPage()

        Dim oPdfImportedPage As iTextSharp.text.pdf.PdfImportedPage = _
            oPdfWriter.GetImportedPage(oPdfReader, iPage)
        Dim iRotation As Integer = oPdfReader.GetPageRotation(iPage)
        If (iRotation = 90) Or (iRotation = 270) Then
            oDirectContent.AddTemplate(oPdfImportedPage, 0, -1.0F, 1.0F, _
                 0, 0, oPdfReader.GetPageSizeWithRotation(iPage).Height)
        Else
            oDirectContent.AddTemplate(oPdfImportedPage, 1.0F, 0, 0, 1.0F, 0, 0)
        End If
    Loop

    oPdfDoc.Close()

End Sub

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Igor Krupitsky
Web Developer
United States United States
Igor is a business intelligence consultant working in Tampa, Florida. He has a BS in Finance from University of South Carolina and Masters in Information Management System from University of South Florida. He also has following professional certifications: MCSD, MCDBA, MCAD.

Comments and Discussions

 
Question[My vote of 1] please complete your job PinmemberRayig28-Jan-13 20:23 
QuestionDecrypt Pdf file Pinmemberprogramadorvb814-Aug-11 5:12 
GeneralMy vote of 5 PinmemberGaurav Lal8-Jul-11 21:35 
QuestionQuestion PinmemberMenon Santosh18-Jan-11 19:49 
GeneralMy vote of 5 PinmemberDon_Hard11-Jul-10 4:22 
GeneralExcessive Code with no explanation PinmemberAbhishek Sur12-Nov-09 23:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 18 Oct 2009
Article Copyright 2009 by Igor Krupitsky
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid