Detect if the PDF file is password protected in C#/VB.NET
This article demonstrates how to detect whether a PDF file is encrypted or not by using Spire.PDF for .NET. Spire.PDF offers a method named IsPasswordProtected(string fileName) which returns a boolean value. If the value is true, means the PDF is encrypted with password, otherwise it's not.
using Spire.Pdf; using System; namespace PdfDemo { class Program { static void Main(string[] args) { string fileName = "Sample.pdf"; bool value = PdfDocument.IsPasswordProtected(fileName); Console.WriteLine(value); Console.ReadKey(); } } }
Imports Spire.Pdf Imports System Namespace PdfDemo Class Program Private Shared Sub Main(ByVal args() As String) Dim fileName As String = "Sample.pdf" Dim value As Boolean = PdfDocument.IsPasswordProtected(fileName) Console.WriteLine(value) Console.ReadKey End Sub End Class End Namespace
After running the project, we get the Output that shows the PDF file is password protected:
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
C#/VB.NET: Encrypt or Decrypt PDF Files
PDF encryption is a crucial task when it comes to sharing confidential documents on the Internet. By encrypting PDF files with strong passwords, you can protect the file data from being accessed by unauthorized parties. In certain cases, it may also be necessary to remove the password to make the document public. In this article, you will learn how to programmatically encrypt or decrypt a PDF file using Spire.PDF for .NET.
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
Encrypt a PDF File with Password
There are two kinds of passwords for encrypting a PDF file - open password and permission password. The former is set to open the PDF file, while the latter is set to restrict printing, contents copying, commenting, etc. If a PDF file is secured with both types of passwords, it can be opened with either password.
The PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize) method offered by Spire.PDF for .NET allows you to set both open password and permission password to encrypt PDF files. The detailed steps are as follows.
- Create a PdfDocument object.
- Load a sample PDF file using PdfDocument.LoadFromFile() method.
- Gets the security parameters of the document using PdfDocument.Security property.
- Encrypt the PDF file with open password and permission password using PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize) method.
- Save the result file using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Security; namespace EncryptPDF { class Program { static void Main(string[] args) { //Create a PdfDocument object PdfDocument pdf = new PdfDocument(); //Load a sample PDF file pdf.LoadFromFile(@"E:\Files\sample.pdf"); //Encrypt the PDF file with password pdf.Security.Encrypt("open", "permission", PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent, PdfEncryptionKeySize.Key128Bit); //Save the result file pdf.SaveToFile("Encrypt.pdf", FileFormat.PDF); } } }
Remove Password to Decrypt a PDF File
When you need to remove the password from a PDF file, you can set the open password and permission password to empty while calling the PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize, string originalPermissionPassword) method. The detailed steps are as follows.
- Create a PdfDocument object.
- Load the encrypted PDF file with password using PdfDocument.LoadFromFile (string filename, string password) method.
- Gets the security parameters of the document using PdfDocument.Security property.
- Decrypt the PDF file by setting the open password and permission password to empty using PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize, string originalPermissionPassword) method.
- Save the result file using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Security; namespace DecryptPDF { class Program { static void Main(string[] args) { //Create a PdfDocument object PdfDocument pdf = new PdfDocument(); //Load the encrypted PDF file with password pdf.LoadFromFile("Encrypt.pdf", "open"); //Set the password as empty to decrypt PDF pdf.Security.Encrypt(string.Empty, string.Empty, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit, "permission"); //Save the result file pdf.SaveToFile("Decrypt.pdf", FileFormat.PDF); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
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