C#: Check Whether a PDF is Password Protected and Determine the Correct Password
Password protection is a widely used security feature in PDFs to restrict access and prevent unauthorized modifications. Before working with a PDF, it is essential to determine whether it is password-protected. If protection is enabled, verifying the correct password allows you to unlock the document, ensuring smooth access for viewing, editing, or extracting its contents.
In this article, we will guide you through the process of checking whether a PDF is password-protected and how to verify the correct password using C# and the Spire.PDF for .NET library.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Check Whether a PDF is Password Protected in C#
Spire.PDF for .NET provides the PdfDocument.IsPasswordProtected(string fileName) method to determine whether a PDF file is password-protected. The detailed steps are as follows.
- Specify the input and output file paths.
- Use the PdfDocument.IsPasswordProtected(string fileName) method to check whether the PDF is password protected.
- Save the verification result to a text file.
- C#
using Spire.Pdf; using System.IO; namespace CheckIfPdfIsProtected { internal class Program { static void Main(string[] args) { // Specify the input and output file paths string pdfPath = "sample.pdf"; string resultFilePath = "verification_results.txt"; // Check whether the PDF file is password-protected bool isProtected = PdfDocument.IsPasswordProtected(pdfPath); // Create a StreamWriter to write the result to a text file using (StreamWriter writer = new StreamWriter(resultFilePath)) { // Write the verification result to the text file string resultMessage = isProtected ? "The PDF is password-protected." : "The PDF is not password-protected."; writer.WriteLine(resultMessage); } } } }
Determine the Correct Password of a PDF in C#
Spire.PDF for .NET does not have a direct method to verify if a password is correct, but this can be done by attempting to open the file with the given password. If the password is incorrect, an exception will be thrown. The detailed steps are as follows.
- Specify the input and output file paths.
- Check whether the PDF file is password-protected using the PdfDocument.IsPasswordProtected(string fileName) method.
- Create an array of potential passwords to test.
- Iterate through the array, and load the PDF with each password using the PdfDocument.LoadFromFile(string filename, string password) method.
- If no exception is thrown, the password is correct. Otherwise, the password is incorrect.
- Save the verification result to a text file.
- C#
using Spire.Pdf; using System; using System.IO; namespace DetermineTheCorrectPasswordOfPdf { internal class Program { static void Main(string[] args) { // Specify the input and output file paths string pdfPath = "sample.pdf"; string resultFilePath = "verification_results.txt"; // Check whether the PDF file is password-protected bool isProtected = PdfDocument.IsPasswordProtected(pdfPath); // Create an array of potential passwords to test string[] passwords = new string[5] { "password1", "password2", "password3", "admin123", "test" }; // Create a StreamWriter to write results to a text file using (StreamWriter writer = new StreamWriter(resultFilePath)) { // If the PDF is protected, start testing passwords if (isProtected) { // Iterate through each password in the array for (int passwordcount = 0; passwordcount < passwords.Length; passwordcount++) { try { // Create a new PdfDocument object and try loading the document with the current password PdfDocument doc = new PdfDocument(); doc.LoadFromFile(pdfPath, passwords[passwordcount]); // If successful, write that the password is correct to the text file writer.WriteLine("Password " + passwords[passwordcount] + " is correct"); } catch { // If an exception occurs, write that the password is not correct to the text file writer.WriteLine("Password " + passwords[passwordcount] + " is not correct"); } } } else { // If the PDF is not password protected, note this in the text file writer.WriteLine("The PDF is not password protected."); } } Console.WriteLine("Verification results have been saved to: " + resultFilePath); Console.ReadKey(); } } }
Get a Free License
To fully experience the capabilities of Spire.PDF for .NET without any evaluation limitations, you can request a free 30-day trial license.
Digitally Sign PDF with Timestamp Server in C#/VB.NET
Digital timestamps mark a PDF signature with the time and date as proof of integrity. A timestamp shows that the contents of the document existed at a point in time, and are unchanged. This article is going to introduce how to digitally sign a PDF document with a timestamp server by using Spire.PDF.
Code Snippets
using Spire.Pdf; using Spire.Pdf.Graphics; using Spire.Pdf.Security; using System.Drawing; namespace SignPDFwithTimestamp { class Program { static void Main(string[] args) { //create a PdfDocument object and load a PDF file PdfDocument doc = new PdfDocument(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Example.pdf"); //load the certificate .pfx file PdfCertificate cert = new PdfCertificate(@"C:\Users\Administrator\Desktop\gary.pfx", "e-iceblue"); //add a signature to the specified position PdfSignature signature = new PdfSignature(doc, doc.Pages[0], cert, "signature"); signature.Bounds = new RectangleF(new PointF(350, 700), new SizeF(180, 90)); //set the signature content signature.NameLabel = "Digitally signed by:Gary"; signature.LocationInfoLabel = "Location:"; signature.LocationInfo = "CN"; signature.ReasonLabel = "Reason: "; signature.Reason = "Ensure authenticity"; signature.ContactInfoLabel = "Contact Number: "; signature.ContactInfo = "028-81705109"; signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill | PdfCertificationFlags.ForbidChanges; signature.GraphicsMode = GraphicMode.SignImageAndSignDetail; signature.SignImageSource = PdfImage.FromFile(@"C:\Users\Administrator\Desktop\company-logo.jpg"); //configure a timestamp server string url = "http://timestamp.wosign.com/rfc3161"; signature.ConfigureTimestamp(url); //save to file doc.SaveToFile("output.pdf"); } } }
Imports Spire.Pdf Imports Spire.Pdf.Graphics Imports Spire.Pdf.Security Imports System.Drawing Namespace SignPDFwithTimestamp Class Program Private Shared Sub Main(args As String()) 'create a PdfDocument object and load a PDF file Dim doc As PdfDocument = New PdfDocument() doc.LoadFromFile("C:\Users\Administrator\Desktop\Example.pdf") 'load the certificate .pfx file Dim cert As PdfCertificate = New PdfCertificate("C:\Users\Administrator\Desktop\gary.pfx","e-iceblue") 'add a signature to the specified position Dim signature As PdfSignature = New PdfSignature(doc,doc.Pages(0),cert,"signature") signature.Bounds = New RectangleF(New PointF(350, 700), New SizeF(180, 90)) 'set the signature content signature.NameLabel = "Digitally signed by:Gary" signature.LocationInfoLabel = "Location:" signature.LocationInfo = "CN" signature.ReasonLabel = "Reason: " signature.Reason = "Ensure authenticity" signature.ContactInfoLabel = "Contact Number: " signature.ContactInfo = "028-81705109" signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill | PdfCertificationFlags.ForbidChanges signature.GraphicsMode = GraphicMode.SignImageAndSignDetail signature.SignImageSource = PdfImage.FromFile("C:\Users\Administrator\Desktop\company-logo.jpg") 'configure a timestamp server Dim url As String = "http://timestamp.wosign.com/rfc3161" signature.ConfigureTimestamp(url) 'save to file doc.SaveToFile("output.pdf") End Sub End Class End Namespace
Output
PDF Security: Encrypt or Decrypt PDF Files in C# .NET
In today's digital landscape, PDFs carry sensitive contracts, financial reports, and personal data. A single breach can lead to compliance violations or intellectual property theft. To protect your PDFs from unauthorized access, it’s necessary to encrypt them.
Spire.PDF for .NET provides enterprise-grade PDF security solution, enabling developers to easily implement PDF encryption/decryption workflows in .NET applications. This article will provide practical examples to show you how to use C# to encrypt PDF or decrypt PDF.
- .NET Library for PDF Security
- What is Involved in PDF Encryption?
- How to Encrypt a PDF in C# (Code Example)
- How to Decrypt a PDF in C# (Steps & Code)
- FAQs
.NET Library for PDF Security
Why Use Spire.PDF?
Spire.PDF is a robust, standalone .NET library designed to create, edit, convert and secure PDF documents without Adobe Acrobat. Speaking of its security features, it enables developers to:
- Apply AES/RC4 encryption with password protection
- Restrict printing/copying/editing permissions
- Support .NET Framework, ASP.NET Core, and .NET 5+
Installation Guide
Method 1: NuGet Package Manager (Recommended)
- Open your project in Visual Studio
- Go to “Tools -> NuGet Package Manager -> Package Manager Console”
- Run the following:
PM> Install-Package Spire.PDF
Method 2: Manual Installation
- Download DLL from Spire.PDF Official Site
- Right-click your project in Solution Explorer
- Go to “Add-> Reference -> Browse -> Select Spire.PDF.dll”.
What is Involved in PDF Encryption?
Spire.PDF allows developers to encrypt PDF with passwords, set encryption algorithm, and set permissions. Below is a comprehensive technical breakdown:
User & Owner Passwords
- User Password (Open Password): Required to open and view the PDF.
- Owner Password (Permissions Password): Controls security permissions (printing, copying, editing)
Critical Security Rule: The owner password overrides user password restrictions. If a PDF file is encrypted with both passwords, it can be opened with either one.
Example code:
PdfSecurityPolicy securityPolicy = new PdfPasswordSecurityPolicy(
"user123", // Open password
"e-iceblue" // Permission password
);
Encryption Algorithms (RC4 and AES Encrypt)
Spire.PDF supports industry-standard encryption methods with varying key strengths:
Algorithm | Key Length | Security Level | Use Case |
---|---|---|---|
AES | 128/256-bit | Military-grade | Sensitive documents (Default) |
RC4 | 40/128-bit | Legacy | Backward compatibility |
Example code:
securityPolicy.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES_256;
Permission Flags
Permission flags control user actions on encrypted PDF documents after opening. These flags are controlled via the properties of the PdfDocumentPrivilege class. Here are some common permission flags.
Properties | Description |
---|---|
AllowContentCopying | Gets or sets the permission which allow copy contents or not. |
AllowPrint | Gets or sets the permission which allow print or not. |
AllowModifyContents | Gets or sets the permission which allow modify contents or not. |
AllowFillFormFields | Gets or sets the permission which allow fill in form fields or not. |
AllowAll | All allowed. |
ForbidAll | All forbidden. |
Example code:
securityPolicy.DocumentPrivilege.AllowPrint = false; // Disable printing
securityPolicy.DocumentPrivilege.AllowContentCopying = false; // Disable copying
How to Encrypt a PDF in C# (Code Example)
The following C# code password protects a PDF file with AES-256 encryption and restrict permissions.
using Spire.Pdf;
namespace EncryptPDF
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
// Load a sample PDF file
pdf.LoadFromFile("sample.pdf");
// Specify the user and owner passwords
string userPassword = "user123";
string ownerPassword = "e-iceblue";
// Create a PdfSecurityPolicy object with the two passwords
PdfSecurityPolicy securityPolicy = new PdfPasswordSecurityPolicy(userPassword, ownerPassword);
// Set encryption algorithm
securityPolicy.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES_256;
// Set document permissions (If you do not set, the default is ForbidAll)
securityPolicy.DocumentPrivilege = PdfDocumentPrivilege.AllowAll;
// Restrict printing and content copying
securityPolicy.DocumentPrivilege.AllowPrint = false;
securityPolicy.DocumentPrivilege.AllowContentCopying = false;
// Encrypt the PDF file
pdf.Encrypt(securityPolicy);
// Save the result file
pdf.SaveToFile("EncryptPDF.pdf", FileFormat.PDF);
}
}
}
The encrypted PDF will:
- Require a password to open.
- Block printing and copying content. Retain all other permissions (editing, form filling, etc.).
How to Decrypt a PDF in C# (Steps & Code)
Decrypt PDF removes passwords and restrictions, allowing full access to the document. With Spire.PDF, you can decrypt a password-protected PDF file in C# with <5 lines of code.
Main Steps:
- Open Encrypted PDF: Load your encrypted PDF file with the owner password.
- Remove Encryption: Invoke the Decrypt() method to remove all security restrictions.
- Save Decrypted PDF: Call the SaveToFile() method to save the decrypted PDF to the specified file path.
Code Example:
The following C# code removes the PDF passwords and restores access.
using Spire.Pdf;
namespace DecryptPDF
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
// Load a sample PDF file with owner password
pdf.LoadFromFile("EncryptPDF.pdf", "e-iceblue");
// Decrypt the PDF file
pdf.Decrypt();
// Save the Decrypted PDF
pdf.SaveToFile("DecryptPDF.pdf");
}
}
}
Open the decrypted PDF:
Conclusion
Securing PDFs with encryption is essential for protecting sensitive data. With Spire.PDF for .NET, developers can effortlessly encrypt, decrypt, and manage permissions in PDF files using C#. The .NET PDF library’s comprehensive features and straightforward implementation make it an ideal choice for enhancing document security in enterprise applications.
Next Steps:
- Getting started with Spire.PDF and request a free 30-day trial license to fully evaluate it.
- Explore the Online Documentation for more PDF protection features such as adding digital signatures, adding watermarks, and more.
FAQs
Q1: Can I encrypt a PDF without a user password?
A: Yes. Set the user password to an empty string and use the owner password to control permissions.
Q2: What encryption standards are supported?
A: Spire.PDF supports:
- 40-bit RC4 (legacy)
- 128-bit RC4/AES (standard)
- 256-bit AES (highest security)
Recommend 256-bit AES for sensitive data compliance (e.g., HIPAA, GDPR).
Q3: How to handle incorrect passwords when decrypting?
A: Use try-catch blocks to handle exceptions:
try
{
pdf.LoadFromFile("EncryptPDF.pdf", " wrongPassword");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Q4. How to check if a PDF is encrypted?
A: Use the PdfDocument.IsPasswordProtected(string fileName) method. A comprehensive guide can be found at: Check Whether a PDF is Password Protected in C#
Remove password from the encrypted PDF document
With Spire.PDF for .NET, we can easily set the password to encrypt the PDF document by password. We can also use Spire.PDF to remove the password from the encrypted PDF document in C# and VB.NET. We need to load the encrypted PDF file with password by calling the method PdfDocument.LoadFromFile (string filename, string password) and then set the password as empty to remove the password.
Firstly, view the PDF with user password:
Step 1: Load the password protected PDF document.
PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("Sample.pdf", "e-iceblue");
Step 2: Set the password as empty to remove the user password.
pdf.Security.UserPassword = string.Empty;
Step 3: Save the document to file.
pdf.SaveToFile("Decrypted.pdf");
Effective screenshot after removing the password from the PDF document:
Full codes:
using Spire.Pdf; namespace RemovePassword { class Program { static void Main(string[] args) { PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("Sample.pdf", "e-iceblue"); pdf.Security.UserPassword = string.Empty; pdf.SaveToFile("Decrypted.pdf"); } } }
Imports Spire.Pdf Namespace RemovePassword Class Program Private Shared Sub Main(args As String()) Dim pdf As New PdfDocument() pdf.LoadFromFile("Sample.pdf", "e-iceblue") pdf.Security.UserPassword = String.Empty pdf.SaveToFile("Decrypted.pdf") End Sub End Class End Namespace
Add Expiry Date to PDF Files in C#/VB.NET
There is no concept of expiration date defined in the PDF specifications format, however, there is a workaround that we can apply expiration using JavaScript. Spire.PDF supports to add java script actions to PDF files as well. This article presents how to add a JavaScript expiration date to a PDF document using Spire.PDF in C# and VB.NET.
Step 1: Create an object of PdfDocument class and add a blank page to it.
PdfDocument doc = new PdfDocument(); doc.Pages.Add();
Step 2: Define the JavaScript code.
string javaScript = "var rightNow = new Date();" + "var endDate = new Date('October 20, 2016 23:59:59');" + "if(rightNow.getTime() > endDate)" + "app.alert('This Document has expired, please contact us for a new one.',1);" + "this.closeDoc();";
Step 3: Create a PdfJavaScriptAction object that performs the java script action in PDF document.
PdfJavaScriptAction js = new PdfJavaScriptAction(javaScript);
Step 4: Set the JavaScript as PDF open action.
doc.AfterOpenAction = js;
Step 5: Save the file.
doc.SaveToFile("ExpiryDate.pdf", FileFormat.PDF);
Output:
Full Code:
using Spire.Pdf; using Spire.Pdf.Actions; namespace AddExpiryDate { class Program { static void Main(string[] args) { PdfDocument doc = new PdfDocument(); doc.Pages.Add(); string javaScript = "var rightNow = new Date();" + "var endDate = new Date('October 20, 2016 23:59:59');" + "if(rightNow.getTime() > endDate)" + "app.alert('This Document has expired, please contact us for a new one.',1);" + "this.closeDoc();"; PdfJavaScriptAction js = new PdfJavaScriptAction(javaScript); doc.AfterOpenAction = js; doc.SaveToFile("ExpiryDate.pdf", FileFormat.PDF); } } }
Imports Spire.Pdf Imports Spire.Pdf.Actions Namespace AddExpiryDate Class Program Private Shared Sub Main(args As String()) Dim doc As PdfDocument = New PdfDocument() doc.Pages.Add() String javaScript = "var rightNow = new Date();" + "var endDate = new Date('October 20, 2016 23:59:59');" + "if(rightNow.getTime() > endDate)" + "app.alert('This Document has expired, please contact us for a new one.',1);" Dim "this.closeDoc();" As + Dim js As PdfJavaScriptAction = New PdfJavaScriptAction(javaScript) doc.AfterOpenAction = js doc.SaveToFile("ExpiryDate.pdf", FileFormat.PDF) End Sub End Class End Namespace
Get all certificates in a PDF signature
Spire.PDF allows getting and verifying a specific signature in a PDF file, now starts from version 3.8.82, Spire.PDF supports to get all certificates in a PDF signature. In this article, we will show you the steps of how to achieve this task by using Spire.PDF.
For demonstration, we used a template PDF file which contains two certificates:
Code snippets:
Step 1: Instantiate a PdfDocument object and load the PDF file.
PdfDocument doc = new PdfDocument(); doc.LoadFromFile("UPS.pdf");
Step 2: Create a List object.
List<PdfSignature> signatures = new List<PdfSignature>();
Step 3: Get all signatures from the PDF file and add them into the list object.
var form = (PdfFormWidget)doc.Form; for (int i = 0; i < form.FieldsWidget.Count; ++i) { var field = form.FieldsWidget[i] as PdfSignatureFieldWidget; if (field != null && field.Signature != null) { PdfSignature signature = field.Signature; signatures.Add(signature); } }
Step 4: Get the first signature from the list, and then get all the certificates from the signature.
PdfSignature signatureOne = signatures[0]; X509Certificate2Collection collection = signatureOne.Certificates;
Effective screenshot:
Full code:
using System; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using Spire.Pdf; using Spire.Pdf.Security; using Spire.Pdf.Widget; namespace Get_all_certificates_in_PDF_signature { class Program { static void Main(string[] args) { PdfDocument doc = new PdfDocument(); doc.LoadFromFile("UPS.pdf"); List<PdfSignature> signatures = new List<PdfSignature>(); var form = (PdfFormWidget)doc.Form; for (int i = 0; i < form.FieldsWidget.Count; ++i) { var field = form.FieldsWidget[i] as PdfSignatureFieldWidget; if (field != null && field.Signature != null) { PdfSignature signature = field.Signature; signatures.Add(signature); } } PdfSignature signatureOne = signatures[0]; X509Certificate2Collection collection = signatureOne.Certificates; foreach (var certificate in collection) { Console.WriteLine(certificate.Subject); } Console.ReadKey(); } } }
How to add signature field to PDF
Except for creating signature, Spire.PDF also allows us to add signature field to PDF using the PdfSignatureField class and the PdfFieldCollection.Add (PdfField field) method in Spire.Pdf.Fields namespace. Once added, we can click on the field to add signature manually to the PDF document.
This article explains how to add a signature field to the specified page of a PDF document using Spire.PDF.
Detail steps and code snippets:
Step 1: Create a new PDF document and add a page to it.
PdfDocument pdfdoc = new PdfDocument(); PdfPageBase page = pdfdoc.Pages.Add();
Step 2: Use PdfSignatureField class to add a named signature field to the specified page by passing two parameters: page and name of the signature field.
PdfSignatureField signaturefield = new PdfSignatureField(page, "Signature");
Step 3: Set border width, style, color, highlight mode and bounds for the signature field.
signaturefield.BorderWidth = 1.0f; signaturefield.BorderStyle = PdfBorderStyle.Solid; signaturefield.BorderColor = new PdfRGBColor(System.Drawing.Color.Black); signaturefield.HighlightMode = PdfHighlightMode.Outline; signaturefield.Bounds = new RectangleF(100, 100, 100, 100);
Step 4: Add the signature field to the document's root fields.
pdfdoc.Form.Fields.Add(signaturefield);
Step 5: Save the document.
pdfdoc.SaveToFile("AddSignField.pdf", FileFormat.PDF);
After running the code, we'll get the result PDF file with a signature field on the first page, effective screenshot as shown below:
Full codes:
using System.Drawing; using Spire.Pdf; using Spire.Pdf.Fields; using Spire.Pdf.Graphics; namespace Add_Signature_Filed_to_PDF { class Program { static void Main(string[] args) { PdfDocument pdfdoc = new PdfDocument(); PdfPageBase page = pdfdoc.Pages.Add(); PdfSignatureField signaturefield = new PdfSignatureField(page, "Signature"); signaturefield.BorderWidth = 1.0f; signaturefield.BorderStyle = PdfBorderStyle.Solid; signaturefield.BorderColor = new PdfRGBColor(System.Drawing.Color.Black); signaturefield.HighlightMode = PdfHighlightMode.Outline; signaturefield.Bounds = new RectangleF(100, 100, 100, 100); pdfdoc.Form.Fields.Add(signaturefield); pdfdoc.SaveToFile("AddSignField.pdf", FileFormat.PDF); } } }
Detect if a PDF document is password protected in C#/VB.NET
A PDF document encrypted with a user password legally cannot be opened without the password. We’d better detect if a document is password protected or not before we try to open it. This article presents how to determine if a PDF document is encrypted with password using Spire.PDF in C#, VB.NET.
Code Snippet:
Step 1: Initialize an instance of PdfDocument class.
PdfDocument doc = new PdfDocument();
Step 2: Load a sample PDF document.
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Encrypted.pdf");
Step 3: Detect whether the document is encrypted with password or not.
bool isEncrypted = doc.IsEncrypted; Console.WriteLine(isEncrypted);
Result:
Full Code:
using Spire.Pdf; using System; namespace Detect { class Program { static void Main(string[] args) { PdfDocument doc = new PdfDocument(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Encrypted.pdf"); bool isEncrypted = doc.IsEncrypted; Console.WriteLine(isEncrypted); Console.Read(); } } }
Imports Spire.Pdf Namespace Detect Class Program Private Shared Sub Main(args As String()) Dim doc As New PdfDocument() doc.LoadFromFile("C:\Users\Administrator\Desktop\Encrypted.pdf") Dim isEncrypted As Boolean = doc.IsEncrypted Console.WriteLine(isEncrypted) Console.Read() End Sub End Class End Namespace
Detect whether a signed PDF was modified or not using C#
After a PDF document is digitally signed with signature, the PDF has been locked to prevent changes or allow the detection of changes. In this article, we'll introduce how to detect if a signed PDF was modified using Spire.PDF.
In order to test this function, we created a PDF document and signed the PDF with digital signature, then changed the word 'PDF' in the sample document into 'Pdf' and saved it as another file. Here is what the modified PDF document looking like:
Code Snippet:
Step 1: Create a Window Forms Application and design form1 as following.
Step 2: Double click 'Load' button to write following code, which will allow us to find a PDF file from folder and return the file path in textBox1.Text.
private void btnLoad_Click(object sender, EventArgs e) { OpenFileDialog fileName = new OpenFileDialog(); fileName.InitialDirectory = Application.StartupPath; fileName.Filter = "All files|*.pdf"; if (fileName.ShowDialog() == DialogResult.OK) { string Path = fileName.FileName.ToString(); textBox1.Text = Path; } }
Step 3: Enter following code to the button of 'Check'. In this part, we get all signatures in the PDF document, and then call PdfSignature.VerifyDocModified() method to detect if the document was altered after signed. If it was modified return true, otherwise false.
private void btnCheck_Click(object sender, EventArgs e) { //get signatures from PDF List signatures = new List(); using (PdfDocument pdf = new PdfDocument(textBox1.Text)) { PdfFormWidget form = pdf.Form as PdfFormWidget; for (int i = 0; i < form.FieldsWidget.Count; i++) { PdfSignatureFieldWidget field = form.FieldsWidget[i] as PdfSignatureFieldWidget; if (field != null && field.Signature != null) { PdfSignature signature = field.Signature; signatures.Add(signature); } } PdfSignature signatureOne = signatures[0]; //detect if the PDF was modified bool modified = signatureOne.VerifyDocModified(); if (modified == true) { MessageBox.Show("The document was modified"); } } }
Run the program and load the modified document, you'll get following output after clicking 'Check' button.
Full Code:
private void btnLoad_Click(object sender, EventArgs e) { OpenFileDialog fileName = new OpenFileDialog(); fileName.InitialDirectory = Application.StartupPath; fileName.Filter = "All files|*.pdf"; if (fileName.ShowDialog() == DialogResult.OK) { string Path = fileName.FileName.ToString(); textBox1.Text = Path; } } private void btnCheck_Click(object sender, EventArgs e) { //get signatures from PDF List signatures = new List(); using (PdfDocument pdf = new PdfDocument(textBox1.Text)) { PdfFormWidget form = pdf.Form as PdfFormWidget; for (int i = 0; i < form.FieldsWidget.Count; i++) { PdfSignatureFieldWidget field = form.FieldsWidget[i] as PdfSignatureFieldWidget; if (field != null && field.Signature != null) { PdfSignature signature = field.Signature; signatures.Add(signature); } } PdfSignature signatureOne = signatures[0]; //detect if the PDF was modified bool modified = signatureOne.VerifyDocModified(); if (modified == true) { MessageBox.Show("The document was modified"); } } }
Remove Digital Signature Field from PDF in C#/VB.NET
As a comprehensive PDF component, Spire.PDF supports to sign a PDF digitally, embed certificate in PDF as well as delete signatures in existing PDF documents. In this article, you'll learn how to remove all digital signatures from a PDF with C#, VB.NET.
Test File:
Code Snippet:
Step 1: Create a new PdfDocument object and load the test file.
PdfDocument pdf = new PdfDocument("test.pdf");
Step 2: Get loaded form from PDF.
PdfFormWidget widgets = pdf.Form as PdfFormWidget;
Step 3: Get the list of filed collection, and judge if each filed is a signature filed. If yes, remove the signature field using PdfFieldCollection.RemoveAt(int index) method.
for (int i = 0; i < widgets.FieldsWidget.List.Count; i++) { PdfFieldWidget widget = widgets.FieldsWidget.List[i] as PdfFieldWidget; if (widget is PdfSignatureFieldWidget) { widgets.FieldsWidget.RemoveAt(i); } }
Step 4: Save and launch the result file.
pdf.SaveToFile("result.pdf"); System.Diagnostics.Process.Start("result.pdf");
Result:
Full Code:
using Spire.Pdf; using Spire.Pdf.Widget; namespace RemoveDigitalSignature { class Program { static void Main(string[] args) { PdfDocument pdf = new PdfDocument("test.pdf"); PdfFormWidget widgets = pdf.Form as PdfFormWidget; for (int i = 0; i < widgets.FieldsWidget.List.Count; i++) { PdfFieldWidget widget = widgets.FieldsWidget.List[i] as PdfFieldWidget; if (widget is PdfSignatureFieldWidget) { widgets.FieldsWidget.RemoveAt(i); } } pdf.SaveToFile("result.pdf"); System.Diagnostics.Process.Start("result.pdf"); } } }
Imports Spire.Pdf Imports Spire.Pdf.Widget Namespace RemoveDigitalSignature Class Program Private Shared Sub Main(args As String()) Dim pdf As New PdfDocument("test.pdf") Dim widgets As PdfFormWidget = TryCast(pdf.Form, PdfFormWidget) For i As Integer = 0 To widgets.FieldsWidget.List.Count - 1 Dim widget As PdfFieldWidget = TryCast(widgets.FieldsWidget.List(i), PdfFieldWidget) If TypeOf widget Is PdfSignatureFieldWidget Then widgets.FieldsWidget.RemoveAt(i) End If Next pdf.SaveToFile("result.pdf") System.Diagnostics.Process.Start("result.pdf") End Sub End Class End Namespace