Document Load Callbacks in Flutter PDF Viewer (SfPdfViewer)
5 Sep 20253 minutes to read
The SfPdfViewer widget supports the onDocumentLoaded and onDocumentLoadFailed callbacks to notify whether the document has been loaded completely or not.
Document Loaded Callback
The onDocumentLoaded callback triggers after the document is loaded in the SfPdfViewer. The document in the PdfDocumentLoadedDetails will return the loaded PdfDocument instance. The following code example explains the same.
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfPdfViewer.network(
'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
onDocumentLoaded: (PdfDocumentLoadedDetails details) {
print(details.document.pages.count);
},
));
}Document Load Failed Callback
The onDocumentLoadFailed callback 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 improper input source value like a wrong URL or file path is given.
- When any non-PDF document is loaded.
The PdfDocumentLoadFailedDetails will return the error title and description message for the failure reason. The following code example explains the same.
/// Displays the error message.
void showErrorDialog(BuildContext context, String error, String description) {
showDialog<dynamic>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(error),
content: Text(description),
actions: <Widget>[
TextButton(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SfPdfViewer.network(
'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
onDocumentLoadFailed: (PdfDocumentLoadFailedDetails details) {
showErrorDialog(context, details.error, details.description);
},
));
}