User271624304 posted
Background
This article continues my previous one, to add watermark in PDF files, now we will go ahead and look how to add password in PDF File. Please check
Add WaterMark In PDF Files.
The code
Imports System
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Public Class Form1
Inherits System.Windows.Forms.Form
Private
Sub brnOpen_Click(ByVal sender
As System.Object,
ByVal e As System.EventArgs)
Handles brnOpen.Click
Dim FldBrow
As OpenFileDialog = New OpenFileDialog()
FldBrow.Title =
"Select PDF File To Add WaterMark"
FldBrow.InitialDirectory =
"c:\"
FldBrow.Filter =
"PDF Files (*.pdf)|*.pdf"
FldBrow.FilterIndex =
2
FldBrow.RestoreDirectory =
True
If FldBrow.ShowDialog() = Windows.Forms.DialogResult.OK
Then
txtPath.Text = FldBrow.FileName
End
If
End
Sub
Private
Sub breimgopen_Click(ByVal sender
As System.Object,
ByVal e As System.EventArgs)
Handles breimgopen.Click
MessageBox.Show(txtpass.Text)
End
Sub
Private
Sub btnoutput_Click(ByVal sender
As System.Object,
ByVal e As System.EventArgs)
Handles btnoutput.Click
Dim sfd1
As SaveFileDialog = New SaveFileDialog()
sfd1.Title =
"Save Output File"
sfd1.InitialDirectory =
"c:\"
sfd1.Filter =
"PDF files (*.pdf)|*.pdf"
sfd1.FilterIndex =
2
sfd1.RestoreDirectory =
True
If sfd1.ShowDialog() = Windows.Forms.DialogResult.OK
Then
txtoutpath.Text = sfd1.FileName
End
If
End
Sub
Private
Sub btnexit_Click(ByVal sender
As System.Object,
ByVal e As System.EventArgs)
Handles btnexit.Click
End
End
Sub
Private
Sub btnAddWaterMark_Click(ByVal sender
As System.Object,
ByVal e As System.EventArgs)
Handles btnAddWaterMark.Click
Dim
input As String =
""
Dim output
As String =
""
Dim password
As String =
""
input = txtPath.Text
password = txtpass.Text
output = txtoutpath.Text
AddPasswordToPDF(input, output, password)
End
Sub
Private
Sub AddPasswordToPDF(ByVal sourceFile
As String,
ByVal outputFile As
String, ByVal password
As String)
Dim pReader
As PdfReader = New PdfReader(sourceFile)
PdfEncryptor.Encrypt(pReader,
New FileStream(outputFile, FileMode.Open), PdfWriter.STRENGTH128BITS, password,
Nothing, PdfWriter.AllowScreenReaders)
End
Sub
End Class