Java: Add Security Permissions to a PDF Document
PDF documents can be secured in several ways. When PDFs are protected with a permission password, readers can open the document without needing to enter a password, but they may not have permission to further manipulate the document, such as printing or copying the content. In this article, you will learn how to set security permissions for a PDF document in Java using Spire.PDF for Java library.
Install Spire.PDF for Java
First, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.pdf</artifactId> <version>10.3.4</version> </dependency> </dependencies>
Add Security Permissions to a PDF Document in Java
Below are the steps to apply security permissions to a PDF document using Spire.PDF for Java.
- Create a PdfDocument object.
- Load a sample PDF file using PdfDocument.loadFileFile() method.
- Specify open password and permission password. The open password can be set to empty so that the generated document will not require a password to open.
- Encrypt the document with the open password and permission password, and set the security permissions using PdfDocument.getSecurity().encypt() method. This method takes PdfPermissionsFlags enumeration as a parameter, which defines user access permissions for an encrypted document.
- Save the document to another PDF file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.security.PdfEncryptionKeySize; import com.spire.pdf.security.PdfPermissionsFlags; import java.util.EnumSet; public class ChangeSecurityPermissions { public static void main(String[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Load a sample PDF file doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf"); //Specify open password String openPsd = ""; //Specify permission password String permissionPsd = "e-iceblue"; //Specify permissions EnumSet permissionsFlags = EnumSet.of(PdfPermissionsFlags.Print, PdfPermissionsFlags.Full_Quality_Print); //Encrypt the document with open password and permission password, and set the permissions and encryption key size doc.getSecurity().encrypt(openPsd, permissionPsd, permissionsFlags, PdfEncryptionKeySize.Key_128_Bit); //Save the document to another PDF file doc.saveToFile("output/SecurityPermissions.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.
Java: Detect if a PDF Document is Password Protected
When opening a password-protected PDF, we must enter the password. But sometimes we need to know whether a PDF is password-protected before opening it. Spire.PDF for Java offers a method PdfDocument.isPasswordProtected() to verify if a PDF document is password protected or not.
Install Spire.PDF for Java
First of all, you need to add the Spire.PDF.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.pdf</artifactId> <version>10.3.4</version> </dependency> </dependencies>
Detect if a PDF Document is Password Protected or Not
- Get the file path
- Detect whether the PDF is password protected or not by using PdfDocument.isPasswordProtected() method.
- Print results
- Java
import com.spire.pdf.PdfDocument; public class DetectIfPDFIsPasswordProtected { public static void main(String[] args) throws Exception { //Define the file path String filePath ="Sample.pdf"; //Detect if the PDF document is password protected boolean isProtected =PdfDocument.isPasswordProtected(filePath); //Print results if(isProtected) { System.out.println("The document is password protected."); } else { System.out.println("The document is not password protected."); } } }
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.
Digitally Sign a PDF with a Timestamp in Java
This article demonstrates how to embed a timestamp when digitally signing PDF documents using Spire.PDF for Java.
import com.spire.pdf.PdfDocument; import com.spire.pdf.graphics.*; import com.spire.pdf.security.GraphicMode; import com.spire.pdf.security.PdfCertificate; import com.spire.pdf.security.PdfCertificationFlags; import com.spire.pdf.security.PdfSignature; import java.awt.*; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; public class SignWithTimestamp { public static void main(String[] args) { //Load a pdf document PdfDocument doc = new PdfDocument(); doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Introduction.pdf"); //Load the certificate PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\gary.pfx", "e-iceblue"); //Create a PdfSignature object and specify its position and size PdfSignature signature = new PdfSignature(doc, doc.getPages().get(0), cert, "MySignature"); Rectangle2D rect = new Rectangle2D.Float(); rect.setFrame(new Point2D.Float((float) doc.getPages().get(0).getActualSize().getWidth() - 220, (float) doc.getPages().get(0).getActualSize().getHeight() - 140), new Dimension(200, 100)); signature.setBounds(rect); //Set the graphics mode signature.setGraphicMode(GraphicMode.Sign_Detail); //Set the signature content signature.setNameLabel("Signer:"); signature.setName("Gary"); signature.setContactInfoLabel("ContactInfo:"); signature.setContactInfo("02881705109"); signature.setLocationInfoLabel("Location:"); signature.setLocationInfo("Chengdu"); signature.setReasonLabel("Reason: "); signature.setReason("The certificate of this document"); //Set the signature font signature.setSignDetailsFont(new PdfFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Regular)); //Set the document permission signature.setDocumentPermissions(PdfCertificationFlags.Forbid_Changes); signature.setCertificated(true); //Configure a time stamp server String timestampServerUrl = "http://timestamp.digicert.com"; signature.configureTimestamp(timestampServerUrl); //Save to file doc.saveToFile("Timestamp.pdf"); doc.close(); } }
Remove Digital Signatures from PDF in Java
This article shows you how to remove digital signatures from a PDF document using Spire.PDF for Java.
import com.spire.pdf.PdfDocument; import com.spire.pdf.widget.PdfFieldWidget; import com.spire.pdf.widget.PdfFormWidget; import com.spire.pdf.widget.PdfSignatureFieldWidget; public class RemoveSignature { public static void main(String[] args) { //Create a PdfDocument object PdfDocument pdf = new PdfDocument(); //Load the sample PDF document pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\Signature.pdf"); //Get form widgets collection from the document PdfFormWidget widgets = (PdfFormWidget) pdf.getForm(); //Loop through the widgets collection for (int i = 0; i < widgets.getFieldsWidget().getList().size(); i++) { //Get the specific widget PdfFieldWidget widget = (PdfFieldWidget)widgets.getFieldsWidget().getList().get(i); //Check if the widget is a PdfSignatureFieldWidget if (widget instanceof PdfSignatureFieldWidget) { //Remove the signature widget widgets.getFieldsWidget().remove(widget);; } } //Save to file pdf.saveToFile("RemoveSignature.pdf"); } }
Verify digital signature in PDF in Java
This article will demonstrate how to use Spire.PDF for Java to verify the digital signature in PDF in Java applications.
import com.spire.pdf.PdfDocument; import com.spire.pdf.security.PdfSignature; import com.spire.pdf.widget.*; public class VerifySignature { public static void main(String[] args) { //Load a pdf document PdfDocument doc = new PdfDocument(); doc.loadFromFile("Sample.pdf"); //Get the collection of PDF fields PdfFormWidget pdfFormWidget = (PdfFormWidget) doc.getForm(); PdfFormFieldWidgetCollection pdfFormFieldWidgetCollection = pdfFormWidget.getFieldsWidget(); //Traverse all the PDF form field for (int i = 0; i < pdfFormFieldWidgetCollection.getCount(); i++) { //check whether it is PdfSignatureField if (pdfFormFieldWidgetCollection.get(i) instanceof PdfSignatureFieldWidget) { //get the signature field PdfSignatureFieldWidget signatureFieldWidget = (PdfSignatureFieldWidget) pdfFormFieldWidgetCollection.get(i); //get the PDF signature PdfSignature signature = signatureFieldWidget.getSignature(); //Verify the signature boolean result = signature.verifySignature(); if (result) { System.out.println("Valid signature"); } else { System.out.println("Invalid signature"); } } } } }
After run the project, we will get the verify signature results:
Java: Add or Delete Digital Signatures in PDF
With the rapid development of digital technologies, more and more companies create, store, and transmit information electronically. To ensure the credibility and authenticity of the electronic documents, digital signatures have been widely used. In this article, you will learn how to add an invisible or a visible digital signature to PDF and how to remove digital signatures from PDF by using Spire.PDF for Java.
- Add an Invisible Digital Signature to PDF
- Add a Visible Digital Signature to PDF
- Remove Digital Signatures from PDF
Install Spire.PDF for Java
First, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.pdf</artifactId> <version>10.3.4</version> </dependency> </dependencies>
Add an Invisible Digital Signature to PDF
The following are the steps to add an invisible digital signature to PDF using Spire.PDF for Java.
- Create a PdfDocument object.
- Load a sample PDF file using PdfDocument.loadFromFile() method.
- Load a pfx certificate file while initializing the PdfCertificate object.
- Create a PdfSignature object based on the certificate.
- Set the document permissions using PdfSignature. setDocumentPermissions() method.
- Save the document to another PDF file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.security.PdfCertificate; import com.spire.pdf.security.PdfCertificationFlags; import com.spire.pdf.security.PdfSignature; public class AddInvisibleSignature { public static void main(String[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Load a sample PDF file doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Java PDF.pdf"); //Load a pfx certificate PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue"); //Create a PdfSignature object PdfSignature signature = new PdfSignature(doc, doc.getPages().get(doc.getPages().getCount() - 1), cert, "MySignature"); //Set the document permission to forbid changes but allow form fill signature.setDocumentPermissions(PdfCertificationFlags.Forbid_Changes); signature.setDocumentPermissions(PdfCertificationFlags.Allow_Form_Fill); //Save to another PDF file doc.saveToFile("output/InvisibleSignature.pdf"); doc.close(); } }
Add a Visible Digital Signature to PDF
The following are the steps to add a visible digital signature to PDF using Spire.PDF for Java.
- Create a PdfDocument object.
- Load a sample PDF file using PdfDocument.LoadFromFile() method.
- Load a pfx certificate file while initializing the PdfCertificate object.
- Create a PdfSignature object and specify its position and size on the document.
- Set the signature details including date, name, location, reason, handwritten signature image, and document permissions.
- Save the document to another PDF file using PdfDocument.SaveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.graphics.PdfFont; import com.spire.pdf.graphics.PdfFontFamily; import com.spire.pdf.graphics.PdfFontStyle; import com.spire.pdf.graphics.PdfImage; import com.spire.pdf.security.GraphicMode; import com.spire.pdf.security.PdfCertificate; import com.spire.pdf.security.PdfCertificationFlags; import com.spire.pdf.security.PdfSignature; import java.awt.*; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; public class AddVisibleSignature { public static void main(String[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Load a sample PDF file doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Java PDF.pdf"); //Load a pfx certificate PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue"); //Create a PdfSignature object and specify its position and size PdfSignature signature = new PdfSignature(doc, doc.getPages().get(0), cert, "MySignature"); Rectangle2D rect = new Rectangle2D.Float(); rect.setFrame(new Point2D.Float((float) doc.getPages().get(0).getActualSize().getWidth() - 320, (float) doc.getPages().get(0).getActualSize().getHeight() - 140), new Dimension(270, 100)); signature.setBounds(rect); //Set the graphics mode signature.setGraphicMode(GraphicMode.Sign_Image_And_Sign_Detail); //Set the signature content signature.setNameLabel("Signer:"); signature.setName("Gary"); signature.setContactInfoLabel("ContactInfo:"); signature.setContactInfo("02881705109"); signature.setDateLabel("Date:"); signature.setDate(new java.util.Date()); signature.setLocationInfoLabel("Location:"); signature.setLocationInfo("Chengdu"); signature.setReasonLabel("Reason: "); signature.setReason("The certificate of this document"); signature.setDistinguishedNameLabel("DN: "); signature.setDistinguishedName(signature.getCertificate().get_IssuerName().getName()); signature.setSignImageSource(PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\handwrittenSignature.png")); //Set the signature font signature.setSignDetailsFont(new PdfFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Regular)); //Set the document permission signature.setDocumentPermissions(PdfCertificationFlags.Forbid_Changes); signature.setCertificated(true); //Save to file doc.saveToFile("output/VisibleSignature.pdf"); doc.close(); } }
Remove Digital Signatures from PDF
The following are the steps to remove digital signatures from PDF using Spire.PDF for Java.
- Create a PdfDocument object.
- Get form widgets from the document using PdfDocument.getForm() method.
- Loop through the widgets and determine if a specific widget is a PdfSignatureFieldWidget.
- Remove the signature widget using PdfFieldCollection.remove() method.
- Save the document to another PDF file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.widget.PdfFieldWidget; import com.spire.pdf.widget.PdfFormWidget; import com.spire.pdf.widget.PdfSignatureFieldWidget; public class DeleteSignatures { public static void main(String[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument("C:\\Users\\Administrator\\Desktop\\VisibleSignature.pdf"); //Get form widgets from the document PdfFormWidget widgets = (PdfFormWidget) doc.getForm(); //Loop through the widgets for (int i = 0; i < widgets.getFieldsWidget().getList().size(); i++) { //Get a specific widget PdfFieldWidget widget = (PdfFieldWidget)widgets.getFieldsWidget().getList().get(i); //Determine if the widget is a PdfSignatureFieldWidget if (widget instanceof PdfSignatureFieldWidget) { //Remove the signature widget widgets.getFieldsWidget().remove(widget);; } } //Save the document to another PDF file doc.saveToFile("output/DeleteSignatures.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.
Java: Encrypt or Decrypt PDF Files
For PDF documents that contain confidential or sensitive information, you may want to password protect these documents to ensure that only the designated person can access the information. This article will demonstrate how to programmatically encrypt a PDF document and decrypt a password-protected document using Spire.PDF for Java.
Install Spire.PDF for Java
First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.pdf</artifactId> <version>10.3.4</version> </dependency> </dependencies>
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 PdfDocument.getSecurity().encrypt(java.lang.String openPassword, java.lang.String permissionPassword, java.util.EnumSet<PdfPermissionsFlags> permissions, PdfEncryptionKeySize keySize) method offered by Spire.PDF for Java allows you to set both open password and permission password to encrypt PDF files. The detailed steps are as follows.
- Create a PdfDocument instance.
- Load a sample PDF file using PdfDocument.loadFromFile() method.
- Set open password, permission password, encryption key size and permissions.
- Encrypt the PDF file using PdfDocument.getSecurity().encrypt(java.lang.String openPassword, java.lang.String permissionPassword, java.util.EnumSet<PdfPermissionsFlags> permissions, PdfEncryptionKeySize keySize) method.
- Save the result file using PdfDocument.saveToFile () method.
- Java
import java.util.EnumSet; import com.spire.pdf.PdfDocument; import com.spire.pdf.security.PdfEncryptionKeySize; import com.spire.pdf.security.PdfPermissionsFlags; public class EncryptPDF { public static void main(String[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a sample PDF file pdf.loadFromFile("E:\\Files\\sample.pdf"); //Encrypt the file PdfEncryptionKeySize keySize = PdfEncryptionKeySize.Key_128_Bit; String openPassword = "e-iceblue"; String permissionPassword = "test"; EnumSet flags = EnumSet.of(PdfPermissionsFlags.Print, PdfPermissionsFlags.Fill_Fields); pdf.getSecurity().encrypt(openPassword, permissionPassword, flags, keySize); //Save and close pdf.saveToFile("Encrypt.pdf"); pdf.close(); } }
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 PdfDocument.getSecurity().encrypt(java.lang.String openPassword, java.lang.String permissionPassword, java.util.EnumSet<PdfPermissionsFlags> permissions, PdfEncryptionKeySize keySize, java.lang.String originalPermissionPassword) method. The detailed steps are as follows.
- Create a PdfDocument object.
- Load the encrypted PDF file with password using PdfDocument.loadFromFile(java.lang.String filename, java.lang.String password) method.
- Decrypt the PDF file by setting the open password and permission password to empty using PdfDocument.getSecurity().encrypt(java.lang.String openPassword, java.lang.String permissionPassword, java.util.EnumSet<PdfPermissionsFlags> permissions, PdfEncryptionKeySize keySize, java.lang.String originalPermissionPassword) method.
- Save the result file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.security.PdfEncryptionKeySize; import com.spire.pdf.security.PdfPermissionsFlags; public class DecryptPDF { public static void main(String[] args) throws Exception { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load the encrypted PDF file with password pdf.loadFromFile("Encrypt.pdf", "e-iceblue"); //Decrypt the file pdf.getSecurity().encrypt("", "", PdfPermissionsFlags.getDefaultPermissions(), PdfEncryptionKeySize.Key_256_Bit, "test"); //Save and close pdf.saveToFile("Decrypt.pdf"); pdf.close(); } }
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.