Open Password-Protected PDFs in UWP

Opening password-protected documents might require some extra work depending on your specific use case. PSPDFKit for Windows provides two different ways of opening them: through the UI, or programmatically.

By default, PSPDFKit for Windows will prompt your user with a password dialog, asking to unlock the PDF if necessary. This guide will go over the second option, detailing how to open password-protected documents programmatically.

Programmatically Opening Password-Protected PDFs

If you want to programmatically supply a password, use the Password property of DocumentSource:

DocumentSource documentSource = ...

// Set the password in the document source.
documentSource.Password = "document-password";

await PDFView.Controller.ShowDocumentAsync(documentSource);

Handling Password Events

If you want to asynchronously provide the password whenever encountering a locked PDF, or if you want to implement your own password dialog, PDFView.Controller exposes the OnRequestPassword event, which is triggered whenever a password-protected PDF is opened without the correct password:

public async void OpenPDF(DocumentSource source)
{
    // Register the event handler that will asynchronously provide
    // the password for opening the encrypted PDF.
    PDFView.Controller.OnRequestPassword += Controller_OnRequestPassword;
    await PDFView.Controller.ShowDocumentAsync(documentSource);
}

/// <summary>
/// Event handler that's called every time PSPDFKit encounters a password-protected PDF.
/// </summary>
private async void Controller_OnRequestPassword(Controller sender, PasswordEventArgs args)
{
    // It's essential that you call `Complete()` on the `Deferral` at the end.
    var deferral = args.Deferral;

    try
    {
        // This can be synchronous or asynchronous (e.g. a user-facing dialog).
        var password = await GetPassword();
        args.Response = new PasswordRequestResponse(success: true, password: password, mayTryAgain: true);
    }
    finally
    {
        deferral.Complete();
    }
}

You can check our PasswordDialogViewModel example inside the UWP Catalog for an example of this API in action, including the implementation of a custom password dialog.

Checking if a PDF Is Protected

To achieve this, you must attempt to open the DocumentSource through the Document.OpenDocumentAsync method, catching the relevant exception as such:

try {
    var documentSource = DocumentSource.CreateFromStorageFile(file);
    await Document.OpenDocumentAsync(documentSource);
}
catch (COMException e)
{
    if (e.ErrorCode == PSPDFKit.ExceptionCodes.InvalidPassword)
    {
        isProtected = true;
    }
}