Save PDFs while unloading in UWP

You may want to perform some operation such as saving while the PdfView is unloading. However, Unloaded events are fired too late to interact with the PdfView. What you can do is suspend unloading until you are finished performing any required operations. To achieve this, add an event handler for PdfView.OnOnSuspendUnloading.

Note that it is very important to finally call Deferral.Complete() or the unloading will be blocked:

{
    // Subscribe to the event handler.
    PdfView.OnSuspendUnloading += PdfView_OnOnSuspendUnloading;
}

private async void PdfView_OnOnSuspendUnloading(PdfView sender, Deferral deferral)
{
    try
    {
        // Save our PDF to a new file.
        var savePicker = new FileSavePicker {SuggestedStartLocation = PickerLocationId.DocumentsLibrary};
        savePicker.FileTypeChoices.Add("Portable Document Format", new List<string> {".pdf"});
        savePicker.SuggestedFileName = "New Document";

        var file = await savePicker.PickSaveFileAsync();
        if (file != null)
        {
            using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            using (var dataWriter = new DataWriter(stream))
            {
                await PdfView.Document.ExportToDataWriterAsync(dataWriter, new DocumentExportOptions());
            }
        }
    }
    finally
    {
        deferral.Complete();
    }
}