How to: Load and Save Password-Encrypted PDF Documents
- 6 minutes to read
The following example describes how to open and save password-encrypted PDF documents; it also lists supported encryption and operation restriction settings.
Open a Password-Encrypted Document
Handle the PdfViewer.PasswordRequested event to manage the password request when the PDF Viewer tries to open the protected document. You can specify the password as a PasswordString property. As a result, the password request dialog is not displayed.
The following code illustrates the use of the PdfViewer.PasswordRequested event.
using System.Windows.Forms;
using DevExpress.Pdf;
// ...
private void pdfViewer1_PasswordRequested(object sender, PdfPasswordRequestedEventArgs e)
{
e.PasswordString = "password"
}
Specify the PdfViewer.PasswordAttemptsLimit property to limit the number of attempts to enter a password. This property is ignored if the PasswordRequested event is not handled. When the users reaches the limit of attempts, the document is not opened.
The code sample below handles the PasswordRequested event to show a custom password dialog, and display a message when the user reaches the limit of password input attempts:
// Create a password form:
public class PasswordUserControl : XtraUserControl
{
public PasswordUserControl()
{
LayoutControl lc = new LayoutControl();
lc.Dock = DockStyle.Fill;
TextEdit tePassword = new TextEdit();
tePassword.Properties.UseSystemPasswordChar = true;
lc.AddItem(String.Empty, tePassword).TextVisible = false;
this.Controls.Add(lc);
this.Height = 100;
this.Dock = DockStyle.Top;
}
}
public partial class Form1 : RibbonForm
{
public Form1()
{
InitializeComponent();
pdfViewer.PasswordAttemptsLimit = 3;
pdfViewer.PasswordRequested += PdfViewer_PasswordRequested;
}
private void PdfViewer_PasswordRequested(object sender, PdfPasswordRequestedEventArgs e)
{
// Show a password form when the PDF viewer
// attempts to open an encrypted document:
PasswordUserControl myControl = new PasswordUserControl();
if (XtraDialog.Show(myControl, "Enter a password:", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
{
e.PasswordString = null;
}
else
{
e.PasswordString = myControl.Controls[0].Text;
}
if (e.PasswordRequestsCount == pdfViewer.PasswordAttemptsLimit)
{
// Show a message when the user reached the limit of attempts:
MessageBox.Show("The document is not opened because you have reached the maximum number of invalid password attempts.", "Invalid Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
e.PasswordString = null;
}
}
}
Encrypt a Document with a Password
Call the PdfViewerExtensions.SaveDocument extension method to encrypt a document and save it. Use the PdfSaveOptions class properties to specify the encryption algorithm, operation restriction settings, and passwords.
Important
The PdfViewerExtensions class is defined in the DevExpress.Docs.v24.2.dll assembly. Add this assembly to your project to use extensions. You need an active license for the DevExpress Office File API Subscription or DevExpress Universal Subscription to use this assembly in production code.
The code sample below specifies encryption settings and saves the document:
pdfViewer.LoadDocument("Document.pdf");
PdfEncryptionOptions encryptionOptions = new PdfEncryptionOptions();
// Specify the encryption algorithm:
encryptionOptions.Algorithm = PdfEncryptionAlgorithm.AES256;
// Set the owner and user passwords:
encryptionOptions.OwnerPasswordString = "123";
encryptionOptions.UserPasswordString = "456";
// Save the document:
pdfViewer.SaveDocument("Protected.pdf", new PdfSaveOptions
{ EncryptionOptions = encryptionOptions });
Encryption Passwords
You can encrypt a document with two passwords: user and owner. The user password prevents unauthorized access to a document. If a document is opened with a user password or without a password (if the user password is not specified), you can perform only permitted operations with a document. The owner password opens the document without restrictions.
Use the OwnerPasswordString and UserPasswordString properties to specify passwords. Take into account the following when you set passwords:
- If the owner and user passwords match, or only the user password is specified, a user should only specify the password to get unrestricted access to the document.
- The specified operation restrictions have no effect without the owner password.
Note
The PDF Viewer ignores the operation restrictions, so you can enter any of the two passwords to get full access to the document. However, the OwnerPasswordString and UserPasswordString properties are saved in a document, so that the restrictions are applied when the document is opened in other PDF viewer applications.
Restrict Document Operations
You can encrypt a document with a password and restrict data extraction, data modification, interactive, or printing operations.
The table below lists properties used to specify operation restrictions, and supported values:
Restriction | Property | Values |
---|---|---|
Printing Restrictions | PrintingPermissions | Allowed – allows users to print the document. LowQuality – allows users to print the document at the low quality level. NotAllowed – prohibits document print operation. |
Data Extraction Restrictions | DataExtractionPermissions | Allowed – allows users access all data extraction operations (copy content, extract text, or graphics from a document), including access to software that uses assistive technologies. Accessibility – allows users to access document content only through assistive technologies. NotAllowed – prohibits all data extraction operations. |
Modification Restrictions | ModificationPermissions | Allowed – allows users to modify and assemble a document: insert, rotate, and delete pages; create bookmarks and thumbnails. DocumentAssembling – allows users to only assemble a document. NotAllowed – prohibits document modification. |
Interactivity Restrictions | InteractivityPermissions | Allowed – allows users access to all interactive operations: to add or modify text annotations, fill in interactive form fields, and create or modify interactive form fields. FormFillingAndSigning – allows users to only fill in existing form fields and sign the document. NotAllowed – prohibits all interactive operations. |
Note
The PDF Viewer ignores all permission properties. However, these settings are saved in a document, so that the restrictions are applied when the document is opened in other PDF viewer applications.
The code sample below applies operation restrictions and encrypts the document:
pdfViewer.LoadDocument("Document.pdf");
PdfEncryptionOptions encryptionOptions = new PdfEncryptionOptions();
// Specify the encryption algorithm:
encryptionOptions.Algorithm = PdfEncryptionAlgorithm.AES256;
// Set the operation restrictions:
encryptionOptions.ModificationPermissions = PdfDocumentModificationPermissions.NotAllowed;
encryptionOptions.DataExtractionPermissions = PdfDocumentDataExtractionPermissions.NotAllowed;
encryptionOptions.InteractivityPermissions = PdfDocumentInteractivityPermissions.FormFillingAndSigning;
// Set the passwords:
encryptionOptions.OwnerPasswordString = "123";
encryptionOptions.UserPasswordString = "456";
// Save the result:
pdfViewer.SaveDocument("Protected.pdf", new PdfSaveOptions
{ EncryptionOptions = encryptionOptions });