openPdf method
Implementation
@override
Future<String?> openPdf({
required String
filePath, // filePath is less relevant on web, we need the actual file bytes
required String password,
html.File? webFile, // This should be passed from file_picker on web
}) async {
if (webFile == null) {
throw PlatformException(
code: "MISSING_FILE_WEB",
message: "Web file data not provided for openPdf.",
);
}
print('[Web] openPdf called for ${webFile.name}');
final completer = Completer<String?>();
final reader = html.FileReader();
reader.readAsArrayBuffer(webFile); // Read file as ArrayBuffer
reader.onLoadEnd.listen((event) async {
if (reader.readyState == html.FileReader.DONE) {
final Uint8List fileBytes = reader.result as Uint8List;
print(
'[Web] openPdf: File read, ${fileBytes.lengthInBytes} bytes. Password: "$password"',
);
try {
// Call a JavaScript function that uses PDF.js
// This JS function will take fileBytes and password,
// and return a Blob URL of the (potentially decrypted) PDF.
final jsPromise = js_util.callMethod(
html.window,
'_webDecryptPdfToBlobUrl',
[fileBytes, password],
);
final String? blobUrl = await js_util.promiseToFuture(
jsPromise as Object,
);
if (blobUrl != null) {
print('[Web] openPdf: Success, Blob URL: $blobUrl');
completer.complete(blobUrl);
} else {
print('[Web] openPdf: Failed, JS returned null Blob URL.');
completer.completeError(
PlatformException(
code: 'WEB_DECRYPTION_FAILED',
message: 'PDF.js processing failed to return a Blob URL.',
),
);
}
} catch (e) {
print('[Web] openPdf: Error during JS call: ${e.toString()}');
completer.completeError(
PlatformException(
code: 'WEB_JS_CALL_ERROR',
message:
'Error calling PDF.js interop for openPdf: ${e.toString()}',
),
);
}
} else {
print('[Web] openPdf: FileReader not DONE.');
completer.completeError(
PlatformException(
code: 'WEB_FILE_READ_INCOMPLETE',
message: 'Web file reading was not completed.',
),
);
}
});
reader.onError.listen((event) {
print('[Web] openPdf: FileReader error.');
completer.completeError(
PlatformException(
code: 'WEB_FILE_READ_ERROR',
message: 'Error reading web file for openPdf.',
),
);
});
return completer.future;
}