Table of Contents

Signing PDFs (VB.Net / Desktop / 25.Printing and Exporting)

Note

This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\vb\VS2026\Desktop\25.Printing and Exporting\35.Signing Pdfs and also at https:​//​github.​com/​tmssoftware/​TMS-​FlexCel.​NET-​demos/​tree/​master/​vb/​VS2026/​Desktop/​Modules/​25.​Printing and Exporting/35.Signing Pdfs

Overview

In this example we will show how to add a visible or invisible signature to a generated PDF file.

Concepts

  • FlexCel supports adbe.pkcs7.detached (the original Adobe format), PAdES baseline level B-B, and PAdES baseline level B-T. Being older, adbe.pkcs7.detached is the most extended and compatible, but PAdES is the standard required by the European Union to sign. It probably makes sense to sign your PDFs with PAdES.

  • In order to sign a PDF file you will need a certificate issued by a valid Certificate Authority, or one issued by yourself. In this example we will use a self signed certificate. This certificate will not validate by default when you open it in Acrobat, you need to add it to your trusted list.

  • The default algorithm for CmsSigner .NET class is SHA-1, which is known to have vulnerabilities and shouldn't be used anymore. So in this example we use SHA512 instead by changing the DigestAlgorithm.

  • In order to sign a file, FlexCel will write a requirement for Acrobat 8 or newer in the generated files. This is because only Acrobat 8 or newer support SHA512. Older versions of acrobat will still display the pages but will not validate the signature.

  • We provide a default signing implementation using standard .NET crypto classes**.** You can still create your own signature engine by using a third party cryptography library or by calling CryptoApi in windows via p/invoke. This is explained in the section Signing PDF Files in the PDF exporting guide.

  • By design, FlexCel never connects to the internet. So if you want to create a PAdES B-T signature, which includes a timestamp from a TSA server, you need to provide the code to actually connect the server in an anonymous method. This demo shows how to do it.

Files

mainForm.Designer.vb

Namespace SigningPdfs
	Partial Public Class mainForm
		''' <summary>
		''' Required designer variable.
		''' </summary>
		Private components As System.ComponentModel.IContainer = Nothing

		''' <summary>
		''' Clean up any resources being used.
		''' </summary>
		''' <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		Protected Overrides Sub Dispose(ByVal disposing As Boolean)
			If disposing AndAlso (components IsNot Nothing) Then
				components.Dispose()
			End If
			MyBase.Dispose(disposing)
		End Sub

		#Region "Windows Form Designer generated code"

		''' <summary>
		''' Required method for Designer support - do not modify
		''' the contents of this method with the code editor.
		''' </summary>
		Private Sub InitializeComponent()
			Me.btnCreateAndSign = New System.Windows.Forms.Button()
			Me.lblSignatureType = New System.Windows.Forms.Label()
			Me.cbSignatureType = New System.Windows.Forms.ComboBox()
			Me.cbCertify = New System.Windows.Forms.CheckBox()
			Me.cbVisibleSignature = New System.Windows.Forms.CheckBox()
			Me.OpenExcelDialog = New System.Windows.Forms.OpenFileDialog()
			Me.savePdfDialog = New System.Windows.Forms.SaveFileDialog()
			Me.SignaturePicture = New System.Windows.Forms.PictureBox()
			Me.OpenImageDialog = New System.Windows.Forms.OpenFileDialog()
			CType(Me.SignaturePicture, System.ComponentModel.ISupportInitialize).BeginInit()
			Me.SuspendLayout()
			' 
			' btnCreateAndSign
			' 
			Me.btnCreateAndSign.Image = My.Resources.acroread
			Me.btnCreateAndSign.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft
			Me.btnCreateAndSign.Location = New System.Drawing.Point(24, 118)
			Me.btnCreateAndSign.Name = "btnCreateAndSign"
			Me.btnCreateAndSign.Size = New System.Drawing.Size(155, 30)
			Me.btnCreateAndSign.TabIndex = 3
			Me.btnCreateAndSign.Text = "Create and Sign Pdf"
			Me.btnCreateAndSign.UseVisualStyleBackColor = True
'			Me.btnCreateAndSign.Click += New System.EventHandler(Me.btnCreateAndSign_Click)
			' 
			' lblSignatureType
			' 
			Me.lblSignatureType.AutoSize = True
			Me.lblSignatureType.Location = New System.Drawing.Point(21, 15)
			Me.lblSignatureType.Name = "lblSignatureType"
			Me.lblSignatureType.Size = New System.Drawing.Size(82, 13)
			Me.lblSignatureType.TabIndex = 5
			Me.lblSignatureType.Text = "Signature type:"
			' 
			' cbSignatureType
			' 
			Me.cbSignatureType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
			Me.cbSignatureType.FormattingEnabled = True
			Me.cbSignatureType.Items.AddRange(New Object() {"PKCS#7 (adbe.pkcs7.detached)", "PAdES B-B (ETSI.CAdES.detached)", "PAdES B-T (B-B + timestamp from a TSA)"})
			Me.cbSignatureType.Location = New System.Drawing.Point(24, 33)
			Me.cbSignatureType.Name = "cbSignatureType"
			Me.cbSignatureType.Size = New System.Drawing.Size(260, 21)
			Me.cbSignatureType.TabIndex = 0
			' 
			' cbCertify
			' 
			Me.cbCertify.AutoSize = True
			Me.cbCertify.Checked = True
			Me.cbCertify.CheckState = System.Windows.Forms.CheckState.Checked
			Me.cbCertify.Location = New System.Drawing.Point(24, 66)
			Me.cbCertify.Name = "cbCertify"
			Me.cbCertify.Size = New System.Drawing.Size(175, 17)
			Me.cbCertify.TabIndex = 1
			Me.cbCertify.Text = "Certify the document (DocMDP)"
			Me.cbCertify.UseVisualStyleBackColor = True
			' 
			' cbVisibleSignature
			' 
			Me.cbVisibleSignature.AutoSize = True
			Me.cbVisibleSignature.Location = New System.Drawing.Point(24, 89)
			Me.cbVisibleSignature.Name = "cbVisibleSignature"
			Me.cbVisibleSignature.Size = New System.Drawing.Size(167, 17)
			Me.cbVisibleSignature.TabIndex = 2
			Me.cbVisibleSignature.Text = "Visible Signature (in last page)"
			Me.cbVisibleSignature.UseVisualStyleBackColor = True
'			Me.cbVisibleSignature.CheckedChanged += New System.EventHandler(Me.cbVisibleSignature_CheckedChanged)
			' 
			' OpenExcelDialog
			' 
			Me.OpenExcelDialog.DefaultExt = "xls"
			Me.OpenExcelDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm|Excel 97/2003|*.xls|Excel 2007|*.xlsx;*.xlsm|All files|*.*"
			Me.OpenExcelDialog.Title = "Select Excel file to convert..."
			' 
			' savePdfDialog
			' 
			Me.savePdfDialog.DefaultExt = "pdf"
			Me.savePdfDialog.Filter = "Pdf Files|*.pdf"
			Me.savePdfDialog.Title = "Select where to save the file..."
			' 
			' SignaturePicture
			' 
			Me.SignaturePicture.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
			Me.SignaturePicture.Image = My.Resources.sign
			Me.SignaturePicture.Location = New System.Drawing.Point(24, 175)
			Me.SignaturePicture.Name = "SignaturePicture"
			Me.SignaturePicture.Size = New System.Drawing.Size(155, 100)
			Me.SignaturePicture.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
			Me.SignaturePicture.TabIndex = 4
			Me.SignaturePicture.TabStop = False
'			Me.SignaturePicture.Click += New System.EventHandler(Me.SignaturePicture_Click)
			' 
			' OpenImageDialog
			' 
			Me.OpenImageDialog.Filter = "Supported Images|*.png;*.bmp*.jpg|All files|*.*"
			' 
			' mainForm
			' 
			Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F)
			Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
			Me.ClientSize = New System.Drawing.Size(308, 165)
			Me.Controls.Add(Me.SignaturePicture)
			Me.Controls.Add(Me.cbVisibleSignature)
			Me.Controls.Add(Me.cbCertify)
			Me.Controls.Add(Me.cbSignatureType)
			Me.Controls.Add(Me.lblSignatureType)
			Me.Controls.Add(Me.btnCreateAndSign)
			Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D
			Me.Name = "mainForm"
			Me.Text = "Signing PDFs"
			CType(Me.SignaturePicture, System.ComponentModel.ISupportInitialize).EndInit()
			Me.ResumeLayout(False)
			Me.PerformLayout()

		End Sub

		#End Region

		Private WithEvents btnCreateAndSign As System.Windows.Forms.Button
		Private lblSignatureType As System.Windows.Forms.Label
		Private cbSignatureType As System.Windows.Forms.ComboBox
		Private cbCertify As System.Windows.Forms.CheckBox
		Private WithEvents cbVisibleSignature As System.Windows.Forms.CheckBox
		Private OpenExcelDialog As System.Windows.Forms.OpenFileDialog
		Private savePdfDialog As System.Windows.Forms.SaveFileDialog
		Private WithEvents SignaturePicture As System.Windows.Forms.PictureBox
		Private OpenImageDialog As System.Windows.Forms.OpenFileDialog
	End Class
End Namespace


mainForm.vb

Imports System.ComponentModel
Imports System.Text
Imports FlexCel.Render
Imports FlexCel.XlsAdapter
Imports FlexCel.Pdf
Imports System.IO
Imports System.Security.Cryptography.X509Certificates
Imports System.Security.Cryptography.Pkcs
Imports System.Drawing.Imaging
Imports System.Reflection

Namespace SigningPdfs
	Partial Public Class mainForm
		Inherits Form

		''' <summary>
		''' The entries of the "Signature type" combo box, in the same order as they are added in the designer.
		''' </summary>
		Private Enum TSignatureType
			''' <summary>
			''' "/adbe.pkcs7.detached": the original Adobe format. It is the most compatible, but it is not a
			''' CAdES signature, so it doesn't conform to the PAdES standard the European Union requires.
			''' </summary>
			Pkcs7

			''' <summary>
			''' "/ETSI.CAdES.detached" without a timestamp: PAdES baseline level B-B.
			''' </summary>
			PAdES_B_B

			''' <summary>
			''' PAdES baseline level B-T: a B-B signature plus a timestamp from a Time Stamping Authority, which
			''' proves the document was signed before a given date instead of trusting the clock of whoever signed.
			''' </summary>
			PAdES_B_T
		End Enum

		Public Sub New()
			Application.EnableVisualStyles()
			InitializeComponent()
			cbSignatureType.SelectedIndex = CInt(TSignatureType.PAdES_B_B)
		End Sub

		Private Sub cbVisibleSignature_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cbVisibleSignature.CheckedChanged
			SignaturePicture.Visible = cbVisibleSignature.Checked
			Dim delta As Integer = SignaturePicture.Height + 30
			If cbVisibleSignature.Checked Then
				Me.Height += delta
			Else
				Me.Height -= delta
			End If
		End Sub

		Private Sub SignaturePicture_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SignaturePicture.Click
			If OpenImageDialog.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then
				Return
			End If
			SignaturePicture.Load(OpenImageDialog.FileName)
		End Sub

		Private Sub btnCreateAndSign_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCreateAndSign.Click
			'Load the Excel file.
			If OpenExcelDialog.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then
				Return
			End If
			Dim xls As New XlsFile()
			xls.Open(OpenExcelDialog.FileName)

			Dim DataPath As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & "\..\..\"

			'Export it to pdf.
			Using pdf As New FlexCelPdfExport(xls, True)
				pdf.FontEmbed = TFontEmbed.Embed

				'Load the certificate and create a signer.
                'In this example we just have the password in clear. It should be kept in a SecureString.
                'Also make sure to set the flag X509KeyStorageFlags.EphemeralKeySet to avoid files created
                'on disk: https://snede.net/the-most-dangerous-constructor-in-net/
                'As X509KeyStorageFlags.EphemeralKeySet only exists in .NET 4.8 or newer, for older versions we will 
                'define it as (X509KeyStorageFlags)32. For .NET 4.8 or newer and  NET Core, you can use X509KeyStorageFlags.EphemeralKeySet
               Dim Cert As New X509Certificate2(DataPath & "flexcel.pfx", "password", X509KeyStorageFlags.EphemeralKeySet) 

				'Note that to use the CmsSigner class you need to add a reference to System.Security dll. 
				'It is *not* enough to add it to the using clauses, you need to add a reference to the dll.
				Dim Signer As New CmsSigner(Cert)

				'By default CmsSigner uses SHA1, but SHA1 has known vulnerabilities and it is deprecated. 
				'So we will use SHA512 instead.
				'"2.16.840.1.101.3.4.2.3" is the Oid for SHA512.
				Signer.DigestAlgorithm = New System.Security.Cryptography.Oid("2.16.840.1.101.3.4.2.3")

				'The format of the signature is decided by the factory, not by the signature itself.
				Dim SignerFactory As TPdfSignerFactory = CreateSignerFactory(Signer)
				If SignerFactory Is Nothing Then
					Return
				End If

				Dim sig As TPdfSignature
				If cbVisibleSignature.Checked Then
					Using fs As New MemoryStream()
						SignaturePicture.Image.Save(fs, ImageFormat.Png)
						Dim ImgData() As Byte = fs.ToArray()

						'The -1 as "page" parameter means the last page.
						sig = New TPdfVisibleSignature(SignerFactory, "Signature", "I have read the document and certify it is valid.", "Springfield", "adrian@tmssoftware.com", -1, New RectangleF(50, 50, 140, 70), ImgData)
					End Using
				Else
					sig = New TPdfSignature(SignerFactory, "Signature", "I have read the document and certify it is valid.", "Springfield", "adrian@tmssoftware.com")
				End If

				'A certifying signature (the default) says who is responsible for the document and which changes
				'are allowed in it afterwards, and only the first signature of a document can certify it.
				'An approval signature just says that whoever signed agrees with what the document says at that
				'moment, and many of them can be added to the same document.
				sig.Certify = cbCertify.Checked

				'You must sign the document *BEFORE* starting to write it.
				pdf.Sign(sig)

				If savePdfDialog.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then
					Return
				End If
				Using PdfStream As New FileStream(savePdfDialog.FileName, FileMode.Create)
					pdf.BeginExport(PdfStream)
					pdf.ExportAllVisibleSheets(False, "Signed Pdf")
					pdf.EndExport()
				End Using

			End Using

			If MessageBox.Show("Do you want to open the generated file?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) <> System.Windows.Forms.DialogResult.Yes Then
				Return
			End If
			Process.Start(savePdfDialog.FileName)

		End Sub

		''' <summary>
		''' Creates the factory that will sign the document in the format selected in the combo box.
		''' Returns Nothing when the selected format is not available, and so the document shouldn't be signed.
		''' </summary>
		Private Function CreateSignerFactory(ByVal Signer As CmsSigner) As TPdfSignerFactory
			Select Case CType(cbSignatureType.SelectedIndex, TSignatureType)
				Case TSignatureType.PAdES_B_B
					'Besides writing "/ETSI.CAdES.detached" in the pdf, this adds the ESS signing-certificate-v2
					'signed attribute that CAdES needs, so the signature says which certificate created it.
					Return New TBuiltInSignerFactory(Signer, TPdfSignatureSubFilter.EtsiCAdESDetached)

				Case TSignatureType.PAdES_B_T
					Return CreateTimestampedSignerFactory(Signer)

				Case Else
					Return New TBuiltInSignerFactory(Signer, TPdfSignatureSubFilter.AdbePkcs7Detached)
			End Select
		End Function

#If NET5_0_OR_GREATER Then
		''' <summary>
		''' The Time Stamping Authority we ask for the timestamps. Replace it with the one you use: the public ones
		''' are rate-limited, and a timestamp is only as trustworthy as the TSA that created it.
		''' </summary>
		Private Const TsaUrl As String = "http://timestamp.digicert.com"

		'HttpClient is meant to be reused. Creating one per request runs out of sockets when signing many files.
		Private Shared ReadOnly TsaClient As New System.Net.Http.HttpClient()

		''' <summary>
		''' <b>FlexCel never connects to the internet by itself.</b> It creates the RFC 3161 request and reads the
		''' answer, but the connection to the TSA is this method, which you write. That way you know that no part
		''' of FlexCel can reach the network unless you let it.
		''' </summary>
		Private Shared Function GetTimestamp(ByVal timeStampRequest() As Byte) As Byte()
			Using Content As New System.Net.Http.ByteArrayContent(timeStampRequest)
				Content.Headers.ContentType = New System.Net.Http.Headers.MediaTypeHeaderValue("application/timestamp-query")

				'This demo signs when you click a button, so we just wait for the answer here. In a server you
				'would normally make the whole export async instead of blocking a thread on the TSA.
				Using Response As System.Net.Http.HttpResponseMessage = TsaClient.PostAsync(TsaUrl, Content).Result
					Response.EnsureSuccessStatusCode()
					Return Response.Content.ReadAsByteArrayAsync().Result
				End Using
			End Using
		End Function

		Private Function CreateTimestampedSignerFactory(ByVal Signer As CmsSigner) As TPdfSignerFactory
			'FlexCel has to reserve the space for the signature before it knows how big the timestamp will be, so
			'it asks the TSA for one sample token the first time. Passing the url as the cache key means the size
			'is measured once for the whole application and shared by every factory using this TSA, which matters
			'because TSAs tend to rate-limit. If you already know the size, set TokenSizeHint instead and FlexCel
			'will not ask for the sample at all.
			Dim TimestampSettings As New TPdfTimestampSettings(AddressOf GetTimestamp, TsaUrl)
			Return New TBuiltInSignerFactory(Signer, TPdfSignatureSubFilter.EtsiCAdESDetached, TimestampSettings)
		End Function
#Else
		Private Function CreateTimestampedSignerFactory(ByVal Signer As CmsSigner) As TPdfSignerFactory
			'Creating the timestamp request needs Rfc3161TimestampRequest, which only exists in .NET 5 and newer,
			'so FlexCel can only create B-T signatures there. B-B signatures work everywhere.
			MessageBox.Show("PAdES B-T signatures need .NET 5 or newer. This demo is compiled for .NET Framework, " _
				& "so only PKCS#7 and PAdES B-B are available here.", "Not available", _
				MessageBoxButtons.OK, MessageBoxIcon.Information)
			Return Nothing
		End Function
#End If
	End Class
End Namespace

Program.vb

Namespace SigningPdfs
	Friend NotInheritable Class Program

		Private Sub New()
		End Sub

		''' <summary>
		''' The main entry point for the application.
		''' </summary>
		<STAThread> _
		Shared Sub Main()
			Application.EnableVisualStyles()
			Application.SetCompatibleTextRenderingDefault(False)
			Application.Run(New mainForm())
		End Sub
	End Class
End Namespace