Back to Devexpress

How to: Load and Save Password-Encrypted PDF Documents

wpf-403378-controls-and-libraries-pdf-viewer-examples-security-how-to-load-and-save-password-encrypted-files.md

latest9.7 KB
Original Source

How to: Load and Save Password-Encrypted PDF Documents

  • Sep 03, 2021
  • 5 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 PdfViewerControl.GetDocumentPassword event to manage the password request when the PDF Viewer tries to open the protected document. You can specify the password as a GetDocumentPasswordEventArgs.Password property. As a result, the password request dialog is not displayed.

csharp
private void PdfViewer_GetDocumentPassword(DependencyObject d, GetDocumentPasswordEventArgs e)
{
    SecureString password = new SecureString();
    password.AppendChar('1');
    password.AppendChar('2');
    password.AppendChar('3');

    e.Password = password;
    e.Handled = true;
}
vb
Private Sub PdfViewer_GetDocumentPassword(ByVal d As DependencyObject, ByVal e As GetDocumentPasswordEventArgs)
    Dim password As New SecureString()
    password.AppendChar("1"c)
    password.AppendChar("2"c)
    password.AppendChar("3"c)

    e.Password = password
    e.Handled = True
End Sub

Specify the PdfViewerControl.PasswordAttemptsLimit property to limit the number of attempts to enter a password. Use the GetDocumentPasswordEventArgs.PasswordRequestsCount property to check the number of attempts. If the GetDocumentPassword event is handled and the user reaches the limit of attempts, the PDF Viewer shows an error message.

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.v25.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:

csharp
public MainWindow()
{
    pdfViewer.OpenDocument("Document.pdf");
    pdfViewer.DocumentLoaded += PdfViewer_DocumentLoaded;
}

private void PdfViewer_DocumentLoaded(object sender, RoutedEventArgs e)
{
    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 });
}
vb
Public Sub New()
    pdfViewer.OpenDocument("Document.pdf")
    AddHandler pdfViewer.DocumentLoaded, AddressOf PdfViewer_DocumentLoaded
End Sub

Private Sub PdfViewer_DocumentLoaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Dim encryptionOptions As 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 With {.EncryptionOptions = encryptionOptions})
End Sub

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:

RestrictionPropertyValues
Printing RestrictionsPrintingPermissionsAllowed – 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 RestrictionsDataExtractionPermissionsAllowed – 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 RestrictionsModificationPermissionsAllowed – 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 RestrictionsInteractivityPermissionsAllowed – 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:

csharp
private void PdfViewer_DocumentLoaded(object sender, RoutedEventArgs e)
{
    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 });
}
vb
Private Sub PdfViewer_DocumentLoaded(ByVal sender As Object, ByVal e As RoutedEventArgs)

    Dim encryptionOptions As PdfEncryptionOptions = 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 With {
        .EncryptionOptions = encryptionOptions
    })
End Sub