Document Load Events in .NET MAUI PDF Viewer (SfPdfViewer)

14 Dec 20232 minutes to read

The SfPdfViewer supports the DocumentLoaded and DocumentLoadFailed events to notify whether the document has been opened and displayed in the view or not.

Document loaded event

The DocumentLoaded event triggers after the document is loaded in the SfPdfViewer. Refer to the following code example:

<syncfusion:SfPdfViewer 
		x:Name="PdfViewer" 
		DocumentLoaded="PdfViewer_DocumentLoaded"/>
private void PdfViewer_DocumentLoaded(object sender, EventArgs e)
	{
	   DisplayAlert("Info", "Document loaded successfully", "OK");
	}

If you want to perform any operation immediately after the document has loaded, you can handle the operations in this event. For example, if you want to initially open a document with a specific page number or zoom factor, then call the respective APIs in this event handler. The following code example explains opening a document with a specified page number of 4.

private void PdfViewer_DocumentLoaded(object sender, EventArgs e) 
{ 
	pdfViewer.GoToPage(4); 
}

Document load failures

When a document fails to load in the SfPdfViewer, the users will be notified with a default message prompt by the DocumentLoadFailedEvent.

Document load failed event

The DocumentLoadFailed event triggers when the document loading fails in the SfPdfViewer. That is,

  • When any corrupted document is loaded.
  • When any password-protected document is loaded with an invalid or empty password.
  • When any non-PDF document is loaded.
  • When a PDF containing XFA form is loaded.

The DocumentLoadFailedEventArgs will return the error Message and Exception details for the failure. The following code example explains the same.

<syncfusion:SfPdfViewer 
	x:Name="PdfViewer" 
	DocumentLoadFailed="PdfViewer_DocumentLoadFailed"/>
private void PdfViewer_DocumentLoadFailed(object sender, DocumentLoadFailedEventArgs e)
{
	DisplayAlert( e.Message, e.Exception.StackTrace, "OK");
}

Handling document load failures

The DocumentLoadFailed event allows you to handle the load failures at the application level in your own way. Set the Handled property of the DocumentFailedEventArgs to true to disable the control’s default error messages and handle your logic with the error information.

<syncfusion:SfPdfViewer 
	x:Name="PdfViewer"
	DocumentLoadFailed="PdfDocumentLoadFailed"/>
public MainPage()
{
	InitializeComponent();
	PdfViewer.DocumentLoadFailed += PdfDocumentLoadFailed;
}

private void PdfDocumentLoadFailed(object sender, DocumentLoadFailedEventArgs e)
{
	e.Handled = true;
	// Handle your logic here.
}