Some test text!

Search
Hamburger Icon

Digitally sign PDF files in VB

More languages

More languages
JavaScript
Java (Android)
C++
C#
C# (.NET Core)
Go
Java
Kotlin
Obj-C
JS (Node.js)
PHP
Python
Ruby
Swift
C# (UWP)
VB
C# (Xamarin)

Sample VB code to use PDFTron SDK's high-level digital signature API for digitally signing and/or certifying PDF files. Learn more about our VB PDF Library and PDF Digital Signature Library.

Get Started Samples Download

To run this sample, get started with a free trial of Apryse SDK.

'
' Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
'

''----------------------------------------------------------------------------------------------------------------------
'' This sample demonstrates the basic usage of the high-level digital signatures API in PDFNet.
''
'' The following steps reflect typical intended usage of the digital signatures API:
''
''	0.	Start with a PDF with or without form fields in it that one would like to lock (or, one can add a field, see (1)).
''	
''	1.	EITHER: 
''		(a) Call doc.CreateDigitalSignatureField, optionally providing a name. You receive a DigitalSignatureField.
''		-OR-
''		(b) If you didn't just create the digital signature field that you want to sign/certify, find the existing one within the 
''		document by using PDFDoc.DigitalSignatureFieldIterator or by using PDFDoc.GetField to get it by its fully qualified name.
''	
''	2.	Create a signature widget annotation, and pass the DigitalSignatureField that you just created or found. 
''		If you want it to be visible, provide a Rect argument with a non-zero width or height, and don't set the
''		NoView and Hidden flags. [Optionally, add an appearance to the annotation when you wish to sign/certify.]
''		
''	[3. (OPTIONAL) Add digital signature restrictions to the document using the field modification permissions (SetFieldPermissions) 
''		or document modification permissions functions (SetDocumentPermissions) of DigitalSignatureField. These features disallow 
''		certain types of changes to be made to the document without invalidating the cryptographic digital signature once it
''		is signed.]
''		
''	4. 	Call either CertifyOnNextSave or SignOnNextSave. There are three overloads for each one (six total):
''		a.	Taking a PKCS #12 keyfile path and its password
''		b.	Taking a buffer containing a PKCS #12 private keyfile and its password
''		c.	Taking a unique identifier of a signature handler registered with the PDFDoc. This overload is to be used
''			in the following fashion: 
''			i)		Extend and implement a new SignatureHandler. The SignatureHandler will be used to add or 
''					validate/check a digital signature.
''			ii)		Create an instance of the implemented SignatureHandler and register it with PDFDoc with 
''					pdfdoc.AddSignatureHandler(). The method returns a SignatureHandlerId.
''			iii)	Call SignOnNextSaveWithCustomHandler/CertifyOnNextSaveWithCustomHandler with the SignatureHandlerId.
''		NOTE: It is only possible to sign/certify one signature per call to the Save function.
''	
''	5.	Call pdfdoc.Save(). This will also create the digital signature dictionary and write a cryptographic signature to it.
''		IMPORTANT: If there are already signed/certified digital signature(s) in the document, you must save incrementally
''		so as to not invalidate the other signature(s). 
''
'' Additional processing can be done before document is signed. For example, UseSignatureHandler() returns an instance
'' of SDF dictionary which represents the signature dictionary (or the /V entry of the form field). This can be used to
'' add additional information to the signature dictionary (e.g. Name, Reason, Location, etc.).
''
'' Although the steps above describes extending the SignatureHandler class, this sample demonstrates the use of
'' StdSignatureHandler (a built-in SignatureHandler in PDFNet) to sign a PDF file.
''----------------------------------------------------------------------------------------------------------------------

'' In order to use .NET Framework's Cryptography library, define "USE_DOTNET_CRYPTO" and then add System.Security to
'' references list.

Imports System
Imports System.Collections.Generic
Imports System.IO
#If USE_DOTNET_CRYPTO Then
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Pkcs
Imports System.Security.Cryptography.X509Certificates
#End If ' USE_DOTNET_CRYPTO

Imports pdftron
Imports pdftron.Crypto
Imports pdftron.PDF
Imports pdftron.PDF.Annots
Imports pdftron.SDF

'''''''''''''''''''' Here follows an example of how to implement a custom signature handler. ''''''''''
#If USE_DOTNET_CRYPTO Then
Class DotNetCryptoSignatureHandler
	Inherits SignatureHandler
	Private m_data As List(Of Byte)
	Private m_signingCert As String
	Private m_certPassword As String

	Public Sub New(ByVal signingCert As String, ByVal password As String)
		m_signingCert = signingCert
		m_certPassword = password
		m_data = New List(Of Byte)()
	End Sub

	Public Overrides Sub AppendData(ByVal data As Byte())
		m_data.AddRange(data)
	End Sub

	Public Overrides Function Reset() As Boolean
		m_data.Clear()
		Return (True)
	End Function

	Public Overrides Function CreateSignature() As Byte()
		Try
			Dim ci As New ContentInfo(m_data.ToArray())
			Dim sc As New SignedCms(ci, True)
			Dim cert As New X509Certificate2(m_signingCert, m_certPassword)
			Dim cs As New CmsSigner()
			cs.Certificate = cert
			cs.DigestAlgorithm = New Oid("2.16.840.1.101.3.4.2.1") ' SHA-256
			sc.ComputeSignature(cs)
			Dim sig As Byte() = sc.Encode()
			Return (sig)
		Catch e As Exception
			Console.[Error].WriteLine(e)
		End Try
		Return (Nothing)
	End Function

	Public Overrides Function GetName() As String
		Return ("Adobe.PPKLite")
	End Function

	Protected Overrides Sub Finalize()
		Try
			Console.Out.WriteLine("DotNetCryptoSignatureHandler Destructor.")
		Finally
			MyBase.Finalize()
		End Try
	End Sub
End Class
#End If ' USE_DOTNET_CRYPTO
'''''''''' End of the DotNetCryptoSignatureHandler custom handler code. ''''''''''''''''''''

Module Module1
	Dim input_path As String = "../../../../TestFiles/"
	Dim output_path As String = "../../../../TestFiles/Output/"

	Public Function VerifySimple(ByVal in_docpath As String, ByVal in_public_key_file_path As String) As Boolean
		Using doc As PDFDoc = New PDFDoc(in_docpath)
			Console.WriteLine("==========")
			Dim opts As VerificationOptions = New VerificationOptions(VerificationOptions.SignatureVerificationSecurityLevel.e_compatibility_and_archiving)

			'Add trust root to store of trusted certificates contained in VerificationOptions.
			opts.AddTrustedCertificate(in_public_key_file_path, System.Convert.ToInt32(VerificationOptions.CertificateTrustFlag.e_default_trust) Or System.Convert.ToInt32(VerificationOptions.CertificateTrustFlag.e_certification_trust))

			Dim result As PDFDoc.SignaturesVerificationStatus = doc.VerifySignedDigitalSignatures(opts)
			Select Case result

				Case PDFDoc.SignaturesVerificationStatus.e_unsigned
					Console.WriteLine("Document has no signed signature fields.")
					Return False
				' e_failure == bad doc status, digest status, or permissions status
				' (i.e. does not include trust issues, because those are flaky due to being network/config-related) 
				Case PDFDoc.SignaturesVerificationStatus.e_failure
					Console.WriteLine("Hard failure in verification on at least one signature.")
					Return False
				Case PDFDoc.SignaturesVerificationStatus.e_untrusted
					Console.WriteLine("Could not verify trust for at least one signature.")
					Return False
				Case PDFDoc.SignaturesVerificationStatus.e_unsupported
					'If necessary, call GetUnsupportedFeatures on VerificationResult to check which
					' unsupported features were encountered (requires verification using 'detailed' APIs)
					Console.WriteLine("At least one signature contains unsupported features.")
					Return False
				'unsigned sigs skipped; parts of document may be unsigned (check GetByteRanges on signed sigs to find out)
				Case PDFDoc.SignaturesVerificationStatus.e_verified
					Console.WriteLine("All signed signatures in document verified.")
					Return True
				Case Else
					Throw New Exception("unrecognized document verification status")
			End Select
		End Using
	End Function

	Public Function VerifyAllAndPrint(ByVal in_docpath As String, ByVal in_public_key_file_path As String) As Boolean
		Using doc As PDFDoc = New PDFDoc(in_docpath)
			Console.WriteLine("==========")
			Dim opts As VerificationOptions = New VerificationOptions(VerificationOptions.SignatureVerificationSecurityLevel.e_compatibility_and_archiving)

			' Trust the public certificate we use for signing.
			Dim trusted_cert_buf As Byte() = File.ReadAllBytes(in_public_key_file_path)
			opts.AddTrustedCertificate(trusted_cert_buf, System.Convert.ToInt32(VerificationOptions.CertificateTrustFlag.e_default_trust) Or System.Convert.ToInt32(VerificationOptions.CertificateTrustFlag.e_certification_trust))

			' Iterate over the signatures and verify all of them.
			Dim digsig_fitr As DigitalSignatureFieldIterator = doc.GetDigitalSignatureFieldIterator()
			Dim verification_status As Boolean = True
			While digsig_fitr.HasNext()
				Dim curr As DigitalSignatureField = digsig_fitr.Current()
				Dim result As VerificationResult = curr.Verify(opts)

				If result.GetVerificationStatus() Then
					Console.Write("Signature verified, ")
				Else
					Console.Write("Signature verification failed, ")
					verification_status = False
				End If

				Console.WriteLine("objnum: {0}", curr.GetSDFObj().GetObjNum())

				Select Case result.GetDigestAlgorithm()
					Case DigestAlgorithm.Type.e_sha1:
						Console.WriteLine("Digest algorithm: SHA-1")
					Case DigestAlgorithm.Type.e_sha256:
						Console.WriteLine("Digest algorithm: SHA-256")
					Case DigestAlgorithm.Type.e_sha384:
						Console.WriteLine("Digest algorithm: SHA-384")
					Case DigestAlgorithm.Type.e_sha512:
						Console.WriteLine("Digest algorithm: SHA-512")
					Case DigestAlgorithm.Type.e_ripemd160:
						Console.WriteLine("Digest algorithm: RIPEMD-160")
					Case DigestAlgorithm.Type.e_unknown_digest_algorithm:
						Console.WriteLine("Digest algorithm: unknown")
					Case Else
						Throw New Exception("unrecognized digest algorithm")
				End Select

				Console.WriteLine("Detailed verification result: " & vbLf & vbTab & "{0}" & vbLf & vbTab & "{1}" & vbLf & vbTab & "{2}" & vbLf & vbTab & "{3}", result.GetDocumentStatusAsString(), result.GetDigestStatusAsString(), result.GetTrustStatusAsString(), result.GetPermissionsStatusAsString())

				Dim changes As DisallowedChange() = result.GetDisallowedChanges()

				For Each it2 As DisallowedChange In changes
					Console.WriteLine(vbTab & "Disallowed change: {0}, objnum: {1}", it2.GetTypeAsString(), it2.GetObjNum())
				Next

				' Get and print all the detailed trust-related results, if they are available.
				If result.HasTrustVerificationResult() Then
					Dim trust_verification_result As TrustVerificationResult = result.GetTrustVerificationResult()
					Console.WriteLine(If(trust_verification_result.WasSuccessful(), "Trust verified.", "Trust not verifiable."))
					Console.WriteLine(trust_verification_result.GetResultString())
					Dim time_of_verification As ULong = trust_verification_result.GetTimeOfTrustVerification()

					Select Case trust_verification_result.GetTimeOfTrustVerificationEnum()
						Case VerificationOptions.TimeMode.e_current
							Console.WriteLine("Trust verification attempted with respect to current time (as epoch time): {0}", time_of_verification)
						Case VerificationOptions.TimeMode.e_signing
							Console.WriteLine("Trust verification attempted with respect to signing time (as epoch time): {0}", time_of_verification)
						Case VerificationOptions.TimeMode.e_timestamp
							Console.WriteLine("Trust verification attempted with respect to secure embedded timestamp (as epoch time): {0}", time_of_verification)
						Case Else
							Throw New Exception("unrecognized time enum value")
					End Select

					If trust_verification_result.GetCertPath().Length = 0 Then
						Console.WriteLine("Could not print certificate path.")
					Else
						Console.WriteLine("Certificate path:")
						Dim cert_path As X509Certificate() = trust_verification_result.GetCertPath()

						For j As Integer = 0 To cert_path.Length - 1
							Console.WriteLine(vbTab & "Certificate:")
							Dim full_cert As X509Certificate = cert_path(j)
							Console.WriteLine(vbTab & vbTab & "Issuer names:")
							Dim issuer_dn As X501AttributeTypeAndValue() = full_cert.GetIssuerField().GetAllAttributesAndValues()

							For i As Integer = 0 To issuer_dn.Length - 1
								Console.WriteLine(vbTab & vbTab & vbTab & issuer_dn(i).GetStringValue())
							Next

							Console.WriteLine(vbTab & vbTab & "Subject names:")
							Dim subject_dn As X501AttributeTypeAndValue() = full_cert.GetSubjectField().GetAllAttributesAndValues()

							For i As Integer = 0 To subject_dn.Length - 1
								Console.WriteLine(vbTab & vbTab & vbTab & subject_dn(i).GetStringValue())
							Next

							Console.WriteLine(vbTab & vbTab & "Extensions:")

							For i As Integer = 0 To full_cert.GetExtensions().Length - 1
								Console.WriteLine(vbTab & vbTab & vbTab & full_cert.GetExtensions()(i).ToString())
							Next
						Next
					End If
				Else
					Console.WriteLine("No detailed trust verification result available.")
				End If

				Dim unsupported_features As String() = result.GetUnsupportedFeatures()

				If unsupported_features.Length > 0 Then
					Console.WriteLine("Unsupported features:")

					For i As Integer = 0 To unsupported_features.Length - 1
						Console.WriteLine(vbTab & unsupported_features(i))
					Next
				End If

				Console.WriteLine("==========")
				digsig_fitr.[Next]()
			End While

			Return verification_status
		End Using
	End Function



	Sub CertifyPDF(ByVal in_docpath As String, ByVal in_cert_field_name As String, ByVal in_private_key_file_path As String, ByVal in_keyfile_password As String, ByVal in_appearance_image_path As String, ByVal in_outpath As String)
		Console.Out.WriteLine("================================================================================")
		Console.Out.WriteLine("Certifying PDF document")

		' Open an existing PDF
		Using doc As PDFDoc = New PDFDoc(in_docpath)
			Console.Out.WriteLine("PDFDoc has " & (If(doc.HasSignatures(), "signatures", "no signatures")))

			Dim page1 As Page = doc.GetPage(1)

			' Create a text field that we can lock using the field permissions feature.
			Dim annot1 As TextWidget = TextWidget.Create(doc, New Rect(143, 440, 350, 460), "asdf_test_field")
			page1.AnnotPushBack(annot1)

			' Create a new signature form field in the PDFDoc. The name argument is optional;
			' leaving it empty causes it to be auto-generated. However, you may need the name for later.
			' Acrobat doesn't show digsigfield in side panel if it's without a widget. Using a
			' Rect with 0 width and 0 height, or setting the NoPrint/Invisible flags makes it invisible.
			Dim certification_sig_field As DigitalSignatureField = doc.CreateDigitalSignatureField(in_cert_field_name)
			Dim widgetAnnot As SignatureWidget = SignatureWidget.Create(doc, New Rect(143, 287, 219, 306), certification_sig_field)
			page1.AnnotPushBack(widgetAnnot)

			' (OPTIONAL) Add an appearance to the signature field.
			Dim img As Image = Image.Create(doc, in_appearance_image_path)
			widgetAnnot.CreateSignatureAppearance(img)

			' Add permissions. Lock the random text field.
			Console.Out.WriteLine("Adding document permissions.")
			certification_sig_field.SetDocumentPermissions(DigitalSignatureField.DocumentPermissions.e_annotating_formfilling_signing_allowed)

			' Prepare to lock the text field that we created earlier.
			Console.Out.WriteLine("Adding field permissions.")
			Dim fields_to_lock As String() = New String(0) {}
			fields_to_lock(0) = "asdf_test_field"
			certification_sig_field.SetFieldPermissions(DigitalSignatureField.FieldPermissions.e_include, fields_to_lock)

#If USE_DOTNET_CRYPTO Then
			Dim sigHandler As DotNetCryptoSignatureHandler = New DotNetCryptoSignatureHandler(in_private_key_file_path, in_keyfile_password)
			Dim sigHandlerId As SignatureHandlerId = doc.AddSignatureHandler(sigHandler)
			certification_sig_field.CertifyOnNextSaveWithCustomHandler(sigHandlerId)
			' Add to the digital signature dictionary a SubFilter name that uniquely identifies the signature format 
			' for verification tools. As an example, the custom handler defined in this file uses the CMS/PKCS #7 detached format, 
			' so we embed one of the standard predefined SubFilter values: "adbe.pkcs7.detached". It is not necessary to do this 
			' when using the StdSignatureHandler.
			Dim f_obj As Obj = certification_sig_field.GetSDFObj()
			f_obj.FindObj("V").PutName("SubFilter", "adbe.pkcs7.detached")
#Else
			certification_sig_field.CertifyOnNextSave(in_private_key_file_path, in_keyfile_password)
#End If ' USE_DOTNET_CRYPTO

			' (OPTIONAL) Add more information to the signature dictionary.
			certification_sig_field.SetLocation("Vancouver, BC")
			certification_sig_field.SetReason("Document certification.")
			certification_sig_field.SetContactInfo("www.pdftron.com")

			' Save the PDFDoc. Once the method below is called, PDFNet will also sign the document using the information provided.
			doc.Save(in_outpath, 0)
		End Using

		Console.Out.WriteLine("================================================================================")
	End Sub

	Sub SignPDF(ByVal in_docpath As String, ByVal in_approval_field_name As String, ByVal in_private_key_file_path As String, ByVal in_keyfile_password As String, ByVal in_appearance_img_path As String, ByVal in_outpath As String)
		Console.Out.WriteLine("================================================================================")
		Console.Out.WriteLine("Signing PDF document")

		' Open an existing PDF
		Using doc As PDFDoc = New PDFDoc(in_docpath)
			' Retrieve the unsigned approval signature field.
			Dim found_approval_field As Field = doc.GetField(in_approval_field_name)
			Dim found_approval_signature_digsig_field As DigitalSignatureField = New DigitalSignatureField(found_approval_field)

			' (OPTIONAL) Add an appearance to the signature field.
			Dim img As Image = Image.Create(doc, in_appearance_img_path)
			Dim found_approval_signature_widget As SignatureWidget = New SignatureWidget(found_approval_field.GetSDFObj())
			found_approval_signature_widget.CreateSignatureAppearance(img)

			' Prepare the signature and signature handler for signing.
#If USE_DOTNET_CRYPTO Then
			Dim sigHandler As DotNetCryptoSignatureHandler = New DotNetCryptoSignatureHandler(in_private_key_file_path, in_keyfile_password)
			Dim sigHandlerId As SignatureHandlerId = doc.AddSignatureHandler(sigHandler)
			found_approval_signature_digsig_field.SignOnNextSaveWithCustomHandler(sigHandlerId)
#Else
			found_approval_signature_digsig_field.SignOnNextSave(in_private_key_file_path, in_keyfile_password)
			' Add a SubFilter name that uniquely identifies the signature format for verification tools. As an 
			' example, the custom handler defined in this file uses the CMS/PKCS #7 detached format, so we embed 
			' one of the standard predefined SubFilter values: "adbe.pkcs7.detached". It is not necessary to do this 
			' when using the StdSignatureHandler.
			Dim f_obj As Obj = found_approval_signature_digsig_field.GetSDFObj()
			f_obj.FindObj("V").PutName("SubFilter", "adbe.pkcs7.detached")
#End If ' USE_DOTNET_CRYPTO

			' The actual approval signing will be done during the following incremental save operation.
			doc.Save(in_outpath, SDFDoc.SaveOptions.e_incremental)
		End Using

		Console.Out.WriteLine("================================================================================")
	End Sub

	Sub ClearSignature(ByVal in_docpath As String, ByVal in_digsig_field_name As String, ByVal in_outpath As String)
		Console.Out.WriteLine("================================================================================")
		Console.Out.WriteLine("Clearing certification signature")

		Using doc As PDFDoc = New PDFDoc(in_docpath)
			Dim digsig As DigitalSignatureField = New DigitalSignatureField(doc.GetField(in_digsig_field_name))

			Console.Out.WriteLine("Clearing signature: " & in_digsig_field_name)
			digsig.ClearSignature()

			If Not digsig.HasCryptographicSignature() Then
				Console.Out.WriteLine("Cryptographic signature cleared properly.")
			End If

			' Save incrementally so as to not invalidate other signatures from previous saves.
			doc.Save(in_outpath, SDFDoc.SaveOptions.e_incremental)
		End Using

		Console.Out.WriteLine("================================================================================")
	End Sub

	Sub PrintSignaturesInfo(ByVal in_docpath As String)
		Console.Out.WriteLine("================================================================================")
		Console.Out.WriteLine("Reading and printing digital signature information")

		Using doc As PDFDoc = New PDFDoc(in_docpath)

			If Not doc.HasSignatures() Then
				Console.Out.WriteLine("Doc has no signatures.")
				Console.Out.WriteLine("================================================================================")
				Return
			Else
				Console.Out.WriteLine("Doc has signatures.")
			End If

			Dim fitr As FieldIterator = doc.GetFieldIterator()

			While fitr.HasNext()
				If fitr.Current().IsLockedByDigitalSignature() Then
					Console.Out.WriteLine("==========" & vbLf & "Field locked by a digital signature")
				Else
					Console.Out.WriteLine("==========" & vbLf & "Field not locked by a digital signature")
				End If

				Console.Out.WriteLine("Field name: " & fitr.Current().GetName())
				Console.Out.WriteLine("==========")
				fitr.Next()
			End While

			Console.Out.WriteLine("====================" & vbLf & "Now iterating over digital signatures only." & vbLf & "====================")

			Dim digsig_fitr As DigitalSignatureFieldIterator = doc.GetDigitalSignatureFieldIterator()
			While digsig_fitr.HasNext()
				Console.Out.WriteLine("==========")
				Console.Out.WriteLine("Field name of digital signature: " & New Field(digsig_fitr.Current().GetSDFObj()).GetName())
				Dim digsigfield As DigitalSignatureField = digsig_fitr.Current()

				If Not digsigfield.HasCryptographicSignature() Then
					Console.Out.WriteLine("Either digital signature field lacks a digital signature dictionary, " &
					"or digital signature dictionary lacks a cryptographic Contents entry. " &
					"Digital signature field is not presently considered signed." &
					vbLf & "==========")
					digsig_fitr.Next()
					Continue While
				End If

				Dim cert_count As Integer = digsigfield.GetCertCount()
				Console.Out.WriteLine("Cert count: " & cert_count)
				For i As Integer = 0 To cert_count - 1
					Dim cert As Byte() = digsigfield.GetCert(i)
					Console.Out.WriteLine("Cert #" & i & " size: " & cert.Length)
				Next

				Dim subfilter As DigitalSignatureField.SubFilterType = digsigfield.GetSubFilter()
				Console.Out.WriteLine("Subfilter type: " & CInt(subfilter))

				If subfilter <> DigitalSignatureField.SubFilterType.e_ETSI_RFC3161 Then
					Console.Out.WriteLine("Signature's signer: " & digsigfield.GetSignatureName())
					Dim signing_time As pdftron.PDF.Date = digsigfield.GetSigningTime()
					If signing_time.IsValid() Then
						Console.Out.WriteLine("Signing time is valid.")
					End If
					Console.Out.WriteLine("Location: " & digsigfield.GetLocation())
					Console.Out.WriteLine("Reason: " & digsigfield.GetReason())
					Console.Out.WriteLine("Contact info: " & digsigfield.GetContactInfo())
				Else
					Console.Out.WriteLine("SubFilter == e_ETSI_RFC3161 (DocTimeStamp; no signing info)" & vbLf)
				End If

				Console.Out.WriteLine((If((digsigfield.HasVisibleAppearance()), "Visible", "Not visible")))

				Dim digsig_doc_perms As DigitalSignatureField.DocumentPermissions = digsigfield.GetDocumentPermissions()
				Dim locked_fields As String() = digsigfield.GetLockedFields()
				For Each field_name As String In locked_fields
					Console.Out.WriteLine("This digital signature locks a field named: " & field_name)
				Next

				Select Case digsig_doc_perms
					Case DigitalSignatureField.DocumentPermissions.e_no_changes_allowed
						Console.Out.WriteLine("No changes to the document can be made without invalidating this digital signature.")
					Case DigitalSignatureField.DocumentPermissions.e_formfilling_signing_allowed
						Console.Out.WriteLine("Page template instantiation, form filling, and signing digital signatures are allowed without invalidating this digital signature.")
					Case DigitalSignatureField.DocumentPermissions.e_annotating_formfilling_signing_allowed
						Console.Out.WriteLine("Annotating, page template instantiation, form filling, and signing digital signatures are allowed without invalidating this digital signature.")
					Case DigitalSignatureField.DocumentPermissions.e_unrestricted
						Console.Out.WriteLine("Document not restricted by this digital signature.")
					Case Else
						Throw New Exception("Unrecognized digital signature document permission level.")
				End Select

				Console.Out.WriteLine("==========")
				digsig_fitr.Next()
			End While
		End Using

		Console.Out.WriteLine("================================================================================")
	End Sub

	Public Function TimestampAndEnableLTV(ByVal in_docpath As String, ByVal in_trusted_cert_path As String, ByVal in_appearance_img_path As String, ByVal in_outpath As String) As Boolean
		Using doc As PDFDoc = New PDFDoc(in_docpath)
			Dim doctimestamp_signature_field As DigitalSignatureField = doc.CreateDigitalSignatureField()
			Dim tst_config As TimestampingConfiguration = New TimestampingConfiguration("http://rfc3161timestamp.globalsign.com/advanced")
			Dim opts As VerificationOptions = New VerificationOptions(VerificationOptions.SignatureVerificationSecurityLevel.e_compatibility_and_archiving)
			opts.AddTrustedCertificate(in_trusted_cert_path)
			opts.EnableOnlineCRLRevocationChecking(True)
			Dim widgetAnnot As SignatureWidget = SignatureWidget.Create(doc, New Rect(0, 100, 200, 150), doctimestamp_signature_field)
			doc.GetPage(1).AnnotPushBack(widgetAnnot)
			Dim widgetObj As Obj = widgetAnnot.GetSDFObj()
			Dim img As Image = Image.Create(doc, in_appearance_img_path)
			widgetAnnot.CreateSignatureAppearance(img)
			Console.WriteLine("Testing timestamping configuration.")
			Dim config_result As TimestampingResult = tst_config.TestConfiguration(opts)

			If config_result.GetStatus() Then
				Console.WriteLine("Success: timestamping configuration usable. Attempting to timestamp.")
			Else
				Console.WriteLine(config_result.GetString())

				If config_result.HasResponseVerificationResult() Then
					Dim tst_result As EmbeddedTimestampVerificationResult = config_result.GetResponseVerificationResult()
					Console.WriteLine("CMS digest status: {0}" & vbLf, tst_result.GetCMSDigestStatusAsString())
					Console.WriteLine("Message digest status: {0}" & vbLf, tst_result.GetMessageImprintDigestStatusAsString())
					Console.WriteLine("Trust status: {0}" & vbLf, tst_result.GetTrustStatusAsString())
				End If

				Return False
			End If

			doctimestamp_signature_field.TimestampOnNextSave(tst_config, opts)
			doc.Save(in_outpath, SDFDoc.SaveOptions.e_incremental)
			Console.WriteLine("Timestamping successful. Adding LTV information for DocTimeStamp signature.")
			Dim timestamp_verification_result As VerificationResult = doctimestamp_signature_field.Verify(opts)

			If Not doctimestamp_signature_field.EnableLTVOfflineVerification(timestamp_verification_result) Then
				Console.WriteLine("Could not enable LTV for DocTimeStamp.")
				Return False
			End If

			doc.Save(in_outpath, SDFDoc.SaveOptions.e_incremental)
			Console.WriteLine("Added LTV information for DocTimeStamp signature successfully.")
			Return True
		End Using
	End Function

	Dim pdfNetLoader As PDFNetLoader
	Sub New()
		pdfNetLoader = pdftron.PDFNetLoader.Instance()
	End Sub

	Sub Main()
		' Initialize PDFNet
		PDFNet.Initialize(PDFTronLicense.Key)

		Dim result As Boolean = True

		'''''''''''''''''''' TEST 0: 
		' Create an approval signature field that we can sign after certifying.
		' (Must be done before calling CertifyOnNextSave/SignOnNextSave/WithCustomHandler.)
		Try
			Using doc As PDFDoc = New PDFDoc(input_path & "waiver.pdf")
				Dim approval_signature_field As DigitalSignatureField = doc.CreateDigitalSignatureField("PDFTronApprovalSig")
				Dim widgetAnnotApproval As SignatureWidget = SignatureWidget.Create(doc, New Rect(300, 287, 376, 306), approval_signature_field)
				Dim page1 As Page = doc.GetPage(1)
				page1.AnnotPushBack(widgetAnnotApproval)
				doc.Save(output_path & "waiver_withApprovalField_output.pdf", SDFDoc.SaveOptions.e_remove_unused)
			End Using
		Catch e As Exception
			Console.[Error].WriteLine(e)
			result = False
		End Try

		'''''''''''''''''''' TEST 1: certify a PDF.
		Try
			CertifyPDF(input_path & "waiver_withApprovalField.pdf", "PDFTronCertificationSig", input_path & "pdftron.pfx", "password", input_path & "pdftron.bmp", output_path & "waiver_withApprovalField_certified_output.pdf")
			PrintSignaturesInfo(output_path & "waiver_withApprovalField_certified_output.pdf")
		Catch e As Exception
			Console.[Error].WriteLine(e)
			result = False
		End Try

		'''''''''''''''''''' TEST 2: approval-sign an existing, unsigned signature field in a PDF that already has a certified signature field.
		Try
			SignPDF(input_path & "waiver_withApprovalField_certified.pdf", "PDFTronApprovalSig", input_path & "pdftron.pfx", "password", input_path & "signature.jpg", output_path & "waiver_withApprovalField_certified_approved_output.pdf")
			PrintSignaturesInfo(output_path & "waiver_withApprovalField_certified_approved_output.pdf")
		Catch e As Exception
			Console.[Error].WriteLine(e)
			result = False
		End Try

		'''''''''''''''''''' TEST 3: Clear a certification from a document that is certified and has an approval signature.
		Try
			ClearSignature(input_path & "waiver_withApprovalField_certified_approved.pdf", "PDFTronCertificationSig", output_path & "waiver_withApprovalField_certified_approved_certcleared_output.pdf")
			PrintSignaturesInfo(output_path & "waiver_withApprovalField_certified_approved_certcleared_output.pdf")
		Catch e As Exception
			Console.[Error].WriteLine(e)
			result = False
		End Try

		'''''''''''''''''''' TEST 4: Verify a document's digital signatures.
		Try
					If Not VerifyAllAndPrint(input_path & "waiver_withApprovalField_certified_approved.pdf", input_path & "pdftron.cer") Then
						result = False
					End If
		Catch e As Exception
			Console.[Error].WriteLine(e)
			result = False
		End Try

		'''''''''''''''''''' TEST 5: Verify a document's digital signatures in a simple fashion using the document API.
		Try
			If Not VerifySimple(input_path + "waiver_withApprovalField_certified_approved.pdf", input_path + "pdftron.cer") Then
				result = False
			End If
		Catch e As Exception
			Console.[Error].WriteLine(e)
			result = False
		End Try
		'''''''''''''''''''' TEST 6: Timestamp a document, then add Long Term Validation (LTV) information for the DocTimeStamp.
		'Try
		'
		'	If Not TimestampAndEnableLTV(input_path + "waiver.pdf",
		'			input_path + "GlobalSignRootForTST.cer",
		'			input_path + "signature.jpg",
		'			output_path + "waiver_DocTimeStamp_LTV.pdf") Then
		'		result = False
		'	End If
		'
		'Catch e As Exception
		'	Console.[Error].WriteLine(e)
		'	result = False
		'End Try

		'''''''''''''''''''' End of tests. ''''''''''''''''''''
		PDFNet.Terminate()
		If result Then
			Console.Out.WriteLine("Tests successful." & vbLf & "==========")
		Else
			Console.Out.WriteLine("Tests FAILED!!!" & vbLf & "==========")
		End If
	End Sub
End Module