'How to save pdf file in flutter?
I have a pdf file. I want to write that file in phone memory? Below is the code. First I am scanning then I am converting the image to pdf, Now I want to save that pdf to phone memory. Please help me.
void onDocumentScanner(BuildContext context) async {
try {
File scannedDocumentFile;
var doc = await DocumentScannerFlutter.launchForPdf(context);
if (doc != null) {
refreshDownloadedFiles();
scannedDocumentFile = doc;
String fileName = basename(scannedDocumentFile.path);
final directory = (await getExternalStorageDirectory())!.path;
File saveFilePath = File('$directory/$fileName');
saveFilePath.openWrite(); //Here I want to save to the file
print("Path = $fileName");
Get.toNamed(AppRoutes.viewDownloadedFile,
arguments: [scannedDocumentFile.path, fileName, folderId])!
.whenComplete(() {
refreshFetchedData();
});
}
} catch (e) {
print(e);
}
}
Solution 1:[1]
I haven't seen the .openWrite()
method before, but the documentation says that it has 2 named arguments FileMode and encoding - try to specify them.
If it won't work, I can only share my solution, with .writeAsBytes
method.
Instead of saveFilePath.openWrite()
you can bundle the data first and then save it.
final byteData = await rootBundle.load(fileName);
await saveFilePath.writeAsBytes(byteData.buffer
.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wiktor |