openPDFFromUrl method
Downloads a PDF from a URL and opens it using PDFKit on iOS
url
The URL of the PDF to download and open
title
The title to display in the viewer
initialPage
Optional parameter to specify which page to open first (defaults to 1)
existingQuotes
Optional list of quotes to highlight when opening the PDF
headers
Optional HTTP headers to use when downloading the PDF
progressCallback
Optional callback to track download progress
Returns a Future that completes with true
if the PDF was opened successfully
or throws an exception if there was an error.
Implementation
Future<bool> openPDFFromUrl(
String url,
String title, {
int initialPage = 1,
List<PDFQuote> existingQuotes = const [],
Map<String, String>? headers,
Function(double progress)? progressCallback,
}) async {
try {
// Get temporary directory
final directory = await getTemporaryDirectory();
// Create a unique filename from the URL
final filename = url.split('/').last;
final filePath = '${directory.path}/$filename';
// Check if file already exists
final file = File(filePath);
if (await file.exists()) {
return await openPDFWithOptions(
filePath,
title,
initialPage: initialPage,
existingQuotes: existingQuotes,
);
}
// Download the PDF file
final response = await http.get(Uri.parse(url), headers: headers);
if (response.statusCode == 200) {
await file.writeAsBytes(response.bodyBytes);
return await openPDFWithOptions(
filePath,
title,
initialPage: initialPage,
existingQuotes: existingQuotes,
);
} else {
throw Exception('Failed to download PDF: ${response.statusCode}');
}
} catch (e) {
throw Exception('Error opening PDF from URL: $e');
}
}