Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
Signing PDF documents, including PDF files. A digital signature refers to a mathematical formula that is used to authenticate and ensure the integrity of an electronic document.
In this tutorial, we will show you how to add digital signature information to a PDF file in C# using the iTextSharp and IronPDF libraries.
Before we dive into the code, let's take a quick look at what a digital signature is and why it's important.
A digital signature refers to a mathematical formula that is used to authenticate and ensure the integrity of an electronic document.
It is an electronic signature that is used to digitally sign electronic documents. Digital signatures provide a high level of security, and they are legally binding in many countries.
When a document is digitally signed, a unique digital signature is created that is linked to the document.
This signature is created using a private key, which is known only to the signer. The signature key contains information about the signer, including their name, email address, and other details.
To verify the authenticity of a digitally signed document, the recipient must have access to the public key of the signer. The public keys are used to decrypt the signature and verify its authenticity.
Digital signatures are important because they provide a high level of security and ensure the integrity of digital documents.
They are commonly used in situations where documents need to be signed, such as contracts, agreements, and other legal documents.
Digital signatures provide several benefits over traditional signatures:
Now that we understand what a digital signature is and why it's important, let's take a look at how to add a digital signature to a PDF document in C# using iTextSharp and IronPDF.
Digital signatures are used to verify the authenticity of electronic documents, and PDFs are a popular data format for such documents.
In this tutorial, we will compare how to add digital signatures to PDF files using two C# libraries, iTextSharp and IronPDF.
iTextSharp is a popular open-source library for creating and manipulating PDF documents in C#.
It includes support for digital signatures and is widely used in .NET projects. On the other hand, IronPDF is a commercial library that provides similar features for PDF manipulation, including digital signatures.
In this tutorial, we will demonstrate how to use both libraries to add digital signatures to PDF documents, covering concepts such as creating a digital certificate, signing a PDF document using a private key, and verifying the signature. We will also provide examples of source code for each step.
Before we begin, you should have a basic understanding of C# programming and the .NET Framework.
Additionally, you will need to have the iTextSharp and IronPDF libraries installed in your project.
You can download iTextSharp from NuGet, and IronPDF can be downloaded from the IronPDF website.
IronPDF is a .NET library that allows you to create, edit, and sign PDF documents in C#. In this guide, we will walk through the process of signing a PDF using IronPDF and an X509Certificate2 object.
Here are the steps to sign a PDF using IronPDF:
Include the necessary namespaces.
using IronPdf; using IronPdf.Signing; using System.Security.Cryptography.X509Certificates;
using IronPdf; using IronPdf.Signing; using System.Security.Cryptography.X509Certificates;
Imports IronPdf
Imports IronPdf.Signing
Imports System.Security.Cryptography.X509Certificates
Render the PDF document using the ChromePdfRenderer
class.
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("foo");
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("foo");
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("foo")
In this example, we are rendering a simple HTML document with a single header element.
Load the X509Certificate2 object with the digital signature you want to use to sign the PDF.
X509Certificate2 cert = new X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable);
X509Certificate2 cert = new X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable);
Dim cert As New X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable)
In this example, we are loading the certificate from a PKCS#12 file named "IronSoftware.pfx" and providing the password "123456". We also set the X509KeyStorageFlags to Exportable so that we can use the certificate's private key to sign the PDF.
Create a PdfSignature object using the certificate.
var sig = new PdfSignature(cert);
var sig = new PdfSignature(cert);
Dim sig = New PdfSignature(cert)
In this example, we are creating a new PdfSignature
object using the certificate object we created in step 3.
Sign the PDF document using the PdfDocument.Sign()
method, passing in the PdfSignature
object you created in step 4.
pdf.Sign(sig);
pdf.Sign(sig);
pdf.Sign(sig)
Save the signed PDF document to a file.
pdf.SaveAs("signed.pdf");
pdf.SaveAs("signed.pdf");
pdf.SaveAs("signed.pdf")
Here's the complete code:
using IronPdf;
using IronPdf.Signing;
using System.Security.Cryptography.X509Certificates;
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("foo");
X509Certificate2 cert = new X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable);
var sig = new PdfSignature(cert);
pdf.Sign(sig);
pdf.SaveAs("signed.pdf");
using IronPdf;
using IronPdf.Signing;
using System.Security.Cryptography.X509Certificates;
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("foo");
X509Certificate2 cert = new X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable);
var sig = new PdfSignature(cert);
pdf.Sign(sig);
pdf.SaveAs("signed.pdf");
Imports IronPdf
Imports IronPdf.Signing
Imports System.Security.Cryptography.X509Certificates
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("foo")
Private cert As New X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable)
Private sig = New PdfSignature(cert)
pdf.Sign(sig)
pdf.SaveAs("signed.pdf")
Once we have created a digital certificate, we can use it to sign a PDF file.
To sign a PDF file, we need to create a new signature object and set its properties, such as the location of the new signature on the page and the reason for signing.
iTextSharp is a popular open-source library for working with PDF documents in C#. With iTextSharp, you can create and manipulate PDF documents, as well as add digital signatures to them. In this write-up, we will focus on how to sign PDF files using iTextSharp.
To get started, you will need to add a reference to the iTextSharp.dll file in your project. You can download the latest version of iTextSharp from their official website.
Once you have added the iTextSharp reference to your project, you can use the PDFSigner library to sign PDF documents. The PDFSigner library contains three classes: Cert
, MetaData
, and PDFSigner
.
The Cert class is used to hold a certificate and extract the needed information for the signature. The MetaData
class holds the PDF metadata, and the PDFSigner
class is used to create the signature and add it to the PDF document.
The processCert
method is used to read the digital certificates and extract the private key entry. It also constructs the digital certificates chain if available.
The Sign
method is used to create a new PDF document using PDFStamper and add the signature to it. You can configure the signature appearance and add a reason, contact, and location attribute to it. The SetCrypto
method is used to sign the document using the private key and chain certificate extracted from the certificate file. Finally, SetVisibleSignature
is used if you need to add a visible signature to the document.
Here is an example code snippet that shows how to sign a PDF file using iTextSharp:
using iTextSharp.text.pdf;
using System.IO;
public void SignPDF(string inputPDF, string outputPDF, string certPath, string certPassword, string reason, string contact, string location, bool visible) {
PdfReader reader = new PdfReader(inputPDF);
//Activate MultiSignatures
PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(outputPDF, FileMode.Create, FileAccess.Write), '\0', null, true);
//To disable Multi signatures uncomment this line:
//every new signature will invalidate older ones!
//PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(outputPDF, FileMode.Create, FileAccess.Write), '\0');
MetaData metadata = new MetaData();
metadata.setAuthor("John Doe");
metadata.setTitle("Signed PDF Document");
st.MoreInfo = metadata.getMetaData();
st.XmpMetadata = metadata.getStreamedMetaData();
PdfSignatureAppearance sap = st.SignatureAppearance;
//Read the certificate and extract the private key entry
Cert myCert = new Cert(certPath, certPassword);
sap.SetCrypto(myCert.Akp, myCert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED);
sap.Reason = reason;
sap.Contact = contact;
sap.Location = location;
//Add a visible signature to the document if (visible)
sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 250, 150), 1, null);
st.Close();
}
using iTextSharp.text.pdf;
using System.IO;
public void SignPDF(string inputPDF, string outputPDF, string certPath, string certPassword, string reason, string contact, string location, bool visible) {
PdfReader reader = new PdfReader(inputPDF);
//Activate MultiSignatures
PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(outputPDF, FileMode.Create, FileAccess.Write), '\0', null, true);
//To disable Multi signatures uncomment this line:
//every new signature will invalidate older ones!
//PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(outputPDF, FileMode.Create, FileAccess.Write), '\0');
MetaData metadata = new MetaData();
metadata.setAuthor("John Doe");
metadata.setTitle("Signed PDF Document");
st.MoreInfo = metadata.getMetaData();
st.XmpMetadata = metadata.getStreamedMetaData();
PdfSignatureAppearance sap = st.SignatureAppearance;
//Read the certificate and extract the private key entry
Cert myCert = new Cert(certPath, certPassword);
sap.SetCrypto(myCert.Akp, myCert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED);
sap.Reason = reason;
sap.Contact = contact;
sap.Location = location;
//Add a visible signature to the document if (visible)
sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 250, 150), 1, null);
st.Close();
}
Imports Microsoft.VisualBasic
Imports iTextSharp.text.pdf
Imports System.IO
Public Sub SignPDF(ByVal inputPDF As String, ByVal outputPDF As String, ByVal certPath As String, ByVal certPassword As String, ByVal reason As String, ByVal contact As String, ByVal location As String, ByVal visible As Boolean)
Dim reader As New PdfReader(inputPDF)
'Activate MultiSignatures
Dim st As PdfStamper = PdfStamper.CreateSignature(reader, New FileStream(outputPDF, FileMode.Create, FileAccess.Write), ControlChars.NullChar, Nothing, True)
'To disable Multi signatures uncomment this line:
'every new signature will invalidate older ones!
'PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(outputPDF, FileMode.Create, FileAccess.Write), '\0');
Dim metadata As New MetaData()
metadata.setAuthor("John Doe")
metadata.setTitle("Signed PDF Document")
st.MoreInfo = metadata.getMetaData()
st.XmpMetadata = metadata.getStreamedMetaData()
Dim sap As PdfSignatureAppearance = st.SignatureAppearance
'Read the certificate and extract the private key entry
Dim myCert As New Cert(certPath, certPassword)
sap.SetCrypto(myCert.Akp, myCert.Chain, Nothing, PdfSignatureAppearance.WINCER_SIGNED)
sap.Reason = reason
sap.Contact = contact
sap.Location = location
'Add a visible signature to the document if (visible)
sap.SetVisibleSignature(New iTextSharp.text.Rectangle(100, 100, 250, 150), 1, Nothing)
st.Close()
End Sub
To sign a PDF file, follow these steps:
Include the necessary namespace:
using IronPdf;
using IronPdf;
Imports IronPdf
Load the PDF file using the PdfDocument.FromFile() method:
PdfDocument pdf = PdfDocument.FromFile("annual_census.pdf");
PdfDocument pdf = PdfDocument.FromFile("annual_census.pdf");
Dim pdf As PdfDocument = PdfDocument.FromFile("annual_census.pdf")
In this example, we are loading a PDF file named "annual_census.pdf" from the current directory. This method returns a PdfDocument object that represents the loaded PDF file.
Make any necessary edits to the PDF file.
In this example, we assume that some edits have been made to the PDF file.
Sign the PDF file using the PdfDocument.SignWithFile() method:
pdf.SignWithFile("/assets/IronSignature.p12", "password", null, PdfDocument.SignaturePermissions.FormFillingAllowed);
pdf.SignWithFile("/assets/IronSignature.p12", "password", null, PdfDocument.SignaturePermissions.FormFillingAllowed);
pdf.SignWithFile("/assets/IronSignature.p12", "password", Nothing, PdfDocument.SignaturePermissions.FormFillingAllowed)
In this example, we are signing the PDF file using a PKCS#12 file named "IronSignature.p12" located in the "/assets" directory. We also provide the password for the PKCS#12 file as the second argument. The third argument specifies the reason for signing the PDF file, which we have left as null. The fourth argument specifies the signature permissions, which we have set to allow only form-filling.
Save the PDF file with the signature as a revision using the PdfDocument.SaveAsRevision() method:
PdfDocument pdfWithRevision = pdf.SaveAsRevision();
PdfDocument pdfWithRevision = pdf.SaveAsRevision();
Dim pdfWithRevision As PdfDocument = pdf.SaveAsRevision()
This method creates a new PdfDocument object that contains the original PDF file and the signature as a revision.
Save the signed PDF file to disk using the PdfDocument.SaveAs() method:
pdfWithRevision.SaveAs("annual\_census\_2.pdf");
pdfWithRevision.SaveAs("annual\_census\_2.pdf");
pdfWithRevision.SaveAs("annual\_census\_2.pdf")
In this example, we are saving the filename of the signed PDF file as "annual_census_2.pdf" in the current directory.
Here is the complete code:
using IronPdf; PdfDocument pdf = PdfDocument.FromFile("annual\_census.pdf");
// make any necessary edits
pdf.SignWithFile("/assets/IronSignature.p12", "password", null, PdfDocument.SignaturePermissions.FormFillingAllowed);
PdfDocument pdfWithRevision = pdf.SaveAsRevision();
pdfWithRevision.SaveAs("annual\_census_2.pdf");
using IronPdf; PdfDocument pdf = PdfDocument.FromFile("annual\_census.pdf");
// make any necessary edits
pdf.SignWithFile("/assets/IronSignature.p12", "password", null, PdfDocument.SignaturePermissions.FormFillingAllowed);
PdfDocument pdfWithRevision = pdf.SaveAsRevision();
pdfWithRevision.SaveAs("annual\_census_2.pdf");
Imports IronPdf
Private pdf As PdfDocument = PdfDocument.FromFile("annual\_census.pdf")
' make any necessary edits
pdf.SignWithFile("/assets/IronSignature.p12", "password", Nothing, PdfDocument.SignaturePermissions.FormFillingAllowed)
Dim pdfWithRevision As PdfDocument = pdf.SaveAsRevision()
pdfWithRevision.SaveAs("annual\_census_2.pdf")
Once a PDF document has been signed, it is important to be able to verify the signatures to ensure that the document has not been tampered with since it was signed.
To verify PDF digital signature using iTextSharp in C#, follow the steps below:
PdfReader
object by passing the path of the PDF document that you want to verify.GetAcroFields
method of the PdfReader
object.GetSignatureNames
method of the AcroFields
object.PdfPKCS7
object for each signature using the GetSignature
method of the AcroFields
object.Verify
method of the PdfPKCS7
object.Here's the code to verify the digital signature of a PDF document using iTextSharp in C#:
public static bool VerifyPdfDigitalSignature(string filePath)
{
bool isValid = false;
try
{
// Create a PdfReader object
PdfReader reader = new PdfReader(filePath);
// Get the AcroFields of the PDF document
AcroFields fields = reader.AcroFields;
// Get the signature names
List<string> names = fields.GetSignatureNames();
// Iterate through the signature names
foreach (string name in names)
{
// Get the PdfPKCS7 object for the signature
PdfPKCS7 pkcs7 = fields.VerifySignature(name);
// Verify the signature
if (pkcs7.Verify())
{
isValid = true;
}
else
{
isValid = false;
}
}
reader.Close();
}
catch (Exception ex)
{
// Handle exception
isValid = false;
}
return isValid;
}
public static bool VerifyPdfDigitalSignature(string filePath)
{
bool isValid = false;
try
{
// Create a PdfReader object
PdfReader reader = new PdfReader(filePath);
// Get the AcroFields of the PDF document
AcroFields fields = reader.AcroFields;
// Get the signature names
List<string> names = fields.GetSignatureNames();
// Iterate through the signature names
foreach (string name in names)
{
// Get the PdfPKCS7 object for the signature
PdfPKCS7 pkcs7 = fields.VerifySignature(name);
// Verify the signature
if (pkcs7.Verify())
{
isValid = true;
}
else
{
isValid = false;
}
}
reader.Close();
}
catch (Exception ex)
{
// Handle exception
isValid = false;
}
return isValid;
}
Public Shared Function VerifyPdfDigitalSignature(ByVal filePath As String) As Boolean
Dim isValid As Boolean = False
Try
' Create a PdfReader object
Dim reader As New PdfReader(filePath)
' Get the AcroFields of the PDF document
Dim fields As AcroFields = reader.AcroFields
' Get the signature names
Dim names As List(Of String) = fields.GetSignatureNames()
' Iterate through the signature names
For Each name As String In names
' Get the PdfPKCS7 object for the signature
Dim pkcs7 As PdfPKCS7 = fields.VerifySignature(name)
' Verify the signature
If pkcs7.Verify() Then
isValid = True
Else
isValid = False
End If
Next name
reader.Close()
Catch ex As Exception
' Handle exception
isValid = False
End Try
Return isValid
End Function
In the above code, the VerifyPdfDigitalSignature
function takes the path of the PDF document as a parameter and returns a boolean value indicating whether the digital signature is valid or not.
Note that the function verifies all the signatures in the PDF document. If you only want to verify a specific signature, you can pass the signature name as a parameter to the VerifySignature
method.
If you have a PDF document that contains one or more digital signatures, you can use IronPDF to verify the signature and ensure that the document has not been tampered with. Here's how you can do it using IronPDF's VerifyPdfSignatures
method:
Load the PDF document First, you need to load the PDF document using IronPDF's PdfDocument.FromFile method. This method takes the file path as a parameter and returns a PdfDocument object that represents the PDF document.
PdfDocument pdf = PdfDocument.FromFile("annual_census.pdf");
PdfDocument pdf = PdfDocument.FromFile("annual_census.pdf");
Dim pdf As PdfDocument = PdfDocument.FromFile("annual_census.pdf")
Verify the signatures Once you have the PdfDocument object, you can call the VerifyPdfSignatures method to verify all signatures in the document. This method returns a boolean value that indicates whether all signatures are valid or not.
bool isValid = pdf.VerifyPdfSignatures();
bool isValid = pdf.VerifyPdfSignatures();
Dim isValid As Boolean = pdf.VerifyPdfSignatures()
You can use this information to take appropriate action, such as showing a message to the user or preventing the document from being processed further.
Here's the complete code snippet that shows how to verify all signatures in a PDF document using IronPDF:
using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("annual_census.pdf");
bool isValid = pdf.VerifyPdfSignatures();
if (isValid)
{
Console.WriteLine("All signatures are valid");
}
else
{
Console.WriteLine("One or more signatures are invalid");
}
using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("annual_census.pdf");
bool isValid = pdf.VerifyPdfSignatures();
if (isValid)
{
Console.WriteLine("All signatures are valid");
}
else
{
Console.WriteLine("One or more signatures are invalid");
}
Imports IronPdf
Private pdf As PdfDocument = PdfDocument.FromFile("annual_census.pdf")
Private isValid As Boolean = pdf.VerifyPdfSignatures()
If isValid Then
Console.WriteLine("All signatures are valid")
Else
Console.WriteLine("One or more signatures are invalid")
End If
iTextSharp and IronPDF libraries have different licenses and pricing models, which may be a factor to consider when choosing between them for your project.
iTextSharp is licensed under the Affero General Public License (AGPL), which is a copyleft license that requires any software that uses iTextSharp to also be licensed under the AGPL.
However, there are also commercial licenses available for iTextSharp, which allow developers to use the library in proprietary software without having to release their source code.
The pricing for iTextSharp commercial licenses varies based on the number of developers and deployment instances.
On the other hand, IronPDF is a commercial library that requires a paid license to use. The pricing for IronPDF is based on the number of developers and deployment instances, similar to iTextSharp.
However, IronPDF also offers users a free trial version with limited functionality that can be used for non-commercial projects.
In terms of pricing, IronPDF may be a better option for smaller projects or projects with limited budgets, as the free trial version provides some functionality at no cost.
However, for larger projects or projects with specific licensing requirements, iTextSharp may be a better option due to its dual licensing model and support for the AGPL.
IronPDF and iTextSharp are two popular libraries for working with PDF files in C#. While both libraries offer similar functionality for working with PDF documents, there are some differences between them that developers should consider when choosing which library to use.
From a technical standpoint, IronPDF is a modern .NET library that offers a simple and intuitive API for working with PDF files. It supports a wide range of PDF features, including text, images, forms, and digital signatures. IronPDF also provides advanced features such as HTML-to-PDF conversion and PDF editing.
On the other hand, iTextSharp is a mature PDF library with a more complex API that may require more effort to learn. However, iTextSharp offers advanced features such as low-level PDF manipulation and support for a wide range of PDF standards.
In terms of licensing, IronPDF offers a simple commercial license model that allows developers to use the library in proprietary software without having to release their source code. This makes it easier for developers to use IronPDF in commercial projects without worrying about license compliance. iTextSharp, on the other hand, offers a dual licensing model with a free AGPL license and a commercial license for proprietary software. While this gives developers more flexibility, it can also be more complicated to navigate.
From a technical standpoint, IronPDF offers a more modern and intuitive API that may be easier for developers to work with. In addition, IronPDF offers advanced features such as HTML-to-PDF conversion and PDF editing, which may be useful for certain projects. However, iTextSharp offers more advanced features such as low-level PDF manipulation and support for a wide range of PDF standards.
IronPDF is available to users for a free trial and can be licensed for commercial use with its Lite package starting from $499 only.
Lastly, IronPDF offers a special promotion where developers can buy All 6 Iron Software products for the price of two Iron Software products. This can provide developers with access to a wide range of powerful .NET libraries at an affordable price.
9 .NET API products for your office documents