loadPdf method
Implementation
Future<void> loadPdf(String url) async {
try {
appState.isLoading = true;
/// Download PDF as bytes
final bytes = await fetchPdfAsBytes(url);
if (bytes.isEmpty) {
throw Exception("PDF file is empty or could not be downloaded.");
}
/// Validate PDF format by checking magic bytes
if (bytes.length < 4 ||
!(bytes[0] == 0x25 &&
bytes[1] == 0x50 &&
bytes[2] == 0x44 &&
bytes[3] == 0x46)) {
throw Exception(
"Invalid PDF format. File does not appear to be a valid PDF.");
}
/// Open PDF document
final document = await PdfDocument.openData(bytes);
if (document.pagesCount == 0) {
throw Exception("PDF document has no pages.");
}
/// Save in your app state
appState.document = document;
appState.totalPages = document.pagesCount;
appState.isLoading = false;
/// Load initial pages
await loadPages(0, null);
} catch (e) {
appState.isLoading = false;
throw Exception("Failed to load PDF: $e");
}
}