Protect PDF Documents with Passwords
- 2 minutes to read
The PDF Document API supports user and owner passwords for encrypted PDF documents.
- User password
- Protects access to the document. Use this password to restrict unauthorized access to document content.
- Owner password
- Controls permissions that restrict document operations, such as printing, editing, and content extraction. Users do not need the owner password to open the document, but restricted operations remain unavailable unless they provide it.
Note
If the owner and user passwords are identical, or if you specify only the user password, the document restricts only opening. After the document is opened, the user has full access to document operations.
The following code snippet assigns user and owner passwords, restricts document operations, and saves the result:
import com.devexpress.docs.pdf.*;
import java.io.*;
import java.nio.file.*;
public class Main {
public static void main(String[] args) throws Exception {
try (InputStream documentStream =
Files.newInputStream(Path.of("Document.pdf"));
PdfDocument pdfDocument =
new PdfDocument(documentStream)) {
// Create encryption settings and specify user and owner passwords.
EncryptionOptions encryptionOptions =
new EncryptionOptions("ownerPassword", "userPassword");
// Restrict content extraction.
encryptionOptions.setDataExtractionPermissions(
DocumentDataExtractionPermissions.NOT_ALLOWED);
// Allow low-quality printing only.
encryptionOptions.setPrintPermissions(
DocumentPrintPermissions.LOW_QUALITY);
// Prevent document modifications.
encryptionOptions.setModificationPermissions(
DocumentModificationPermissions.NOT_ALLOWED);
// Use the AES-256 encryption algorithm.
encryptionOptions.setAlgorithm(EncryptionAlgorithm.AES_256);
// Encrypt the document with the specified settings.
pdfDocument.encrypt(encryptionOptions);
// Save the encrypted document.
try (OutputStream outputStream =
Files.newOutputStream(Path.of("Document_encrypted.pdf"))) {
pdfDocument.save(outputStream);
}
}
}
}
See Also