How to encode a PDF to a binary in Flutter - sqlite

I am trying to make an document scanner app in flutter where whenever a user clicks a button the PDF that is already created should be added to an SQLite database .For uploading a PDF into a SQLite database in flutter we need to convert the file to a binary.But I don't know how to do that please help me.The code for converting a image to a pdf
String _status = "Not created";
File pdfFile;
FileStat _pdfStat;
bool _generating = false;
Future<File> _assetFromBundle(String name) async {
final tempDir = await getApplicationDocumentsDirectory();
final output = File(path.join(tempDir.path, name));
if (!await output.exists()) {
final data = await rootBundle.load('assets/$name');
final buffer = data.buffer;
output.writeAsBytes(
buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
}
return output;
}
Future<void> _createPdf() async {
try {
this.setState(() => _generating = true);
final tempDir = await getApplicationDocumentsDirectory();
final output = File(path.join(tempDir.path, 'example.pdf'));
this.setState(() => _status = 'Preparing images...');
final images = [ff.image];
this.setState(() => _status = 'Generating PDF');
await ImagesToPdf.createPdf(
pages: images
.map(
(file) => PdfPage(
imageFile: file,
compressionQuality: 0.5,
) ,
)
.toList(),
output: output,
);
_pdfStat = await output.stat();
this.setState(() {
pdfFile = output;
_status = 'PDF Generated (${_pdfStat.size ~/ 1024}kb)';
});
} catch (e) {
this.setState(() => _status = 'Failed to generate pdf: $e".');
} finally {
this.setState(() => _generating = false);
}
}
Future<void> _openPdf() async {
if (pdfFile != null) {
try {
final bytes = await pdfFile.readAsBytes();
await Printing.sharePdf(
bytes: bytes, filename: path.basename(pdfFile.path));
} catch (e) {
_status = 'Failed to open pdf: $e".';
}
}
}

I guess what you are looking for is bytes, use File class to read as bytes,
var f = File('file/path.pdf');
List<int> binaries = await f.readAsBytes();
use the bytes as is or by encoding it to Base64 String
var asString = Base64Codec().encode(binaries);

Related

Is there any way to save flutter_tts file to firebase storage?

I am working on a flutter project in which user is supposed to create some scripts and by typing them in text and then flutter_tts library is supposed to convert them to audio file which works fine for that time being but I want to save that file into firebase storage for later user. I have tried the following code but it just saves blank audio file in the firebase storage. Any kind of help will be appreciated.
The code I have tried is:
final FlutterTts _flutterTts = FlutterTts();
late var fileName;
/// creation of audio script
Future createAudioScript(
String name,
String script,
String firebasepath,
) async {
await _flutterTts.setLanguage("en-US");
await _flutterTts.setSpeechRate(1.0);
await _flutterTts.setVolume(1.0);
await _flutterTts.setPitch(1.0);
await _flutterTts.setVoice(
{"name": "en-us-x-tpf-local", "locale": "en-US"},
);
await _flutterTts.speak(script);
fileName = GetPlatform.isAndroid ? '$name.wav' : '$name.caf';
print('FileName: $fileName');
var directoryPath =
"${(await getApplicationDocumentsDirectory()).path}/audio/";
var directory = Directory(directoryPath);
if (!await directory.exists()) {
await directory.create();
print('[INFO] Created the directory');
}
var path =
"${(await getApplicationDocumentsDirectory()).path}/audio/$fileName";
print('[INFO] path: $path');
var file = File(path);
if (!await file.exists()) {
await file.create();
print('[INFO] Created the file');
}
await _flutterTts.synthesizeToFile(script, fileName).then((value) async {
if (value == 1) {
print('generated');
var file = File(
'/storage/emulated/0/Android/data/com.solution.thriving/files/$fileName',
);
print(file);
moveFile(file, path, '$firebasepath/$fileName').then((value) {
print('move file: $value');
_app.link.value = value;
print('link: ${_app.link.value}');
});
}
});
}
/// move file from temporary to local storage and save to firebase
Future<String> moveFile(
File sourceFile,
String newPath,
String firebasePath,
) async {
String audioLink = '';
print('moved');
await sourceFile.copy(newPath).then((value) async {
print('value: $value');
await appStorage.uploadAudio(value, fileName, firebasePath).then((audio) {
print(audio);
audioLink = audio;
return audioLink;
});
}).whenComplete(() async {
customToast(message: 'Audio has been generated successfully.');
});
return audioLink;
}
After spending whole day and with the help of a friend, I finally managed to figure out the issue which was being caused because I was using synthesizeToFile() and speak() functions at the same time, which I managed to resolved the issue by changing my code to the following code snippet.
final FlutterTts _flutterTts = FlutterTts();
late var fileName;
/// converting text to speech
Future createAudioScript(
String name,
String script,
String firebasepath,
) async {
await _flutterTts.setLanguage("en-US");
await _flutterTts.setSpeechRate(1.0);
await _flutterTts.setVolume(1.0);
await _flutterTts.setPitch(1.0);
await _flutterTts.setVoice(
{"name": "en-us-x-tpf-local", "locale": "en-US"},
);
if (GetPlatform.isIOS) _flutterTts.setSharedInstance(true);
// await _flutterTts.speak(script);
fileName = GetPlatform.isAndroid ? '$name.wav' : '$name.caf';
log('FileName: $fileName');
await _flutterTts.synthesizeToFile(script, fileName).then((value) async {
if (value == 1) {
log('Value $value');
log('generated');
}
});
final externalDirectory = await getExternalStorageDirectory();
var path = '${externalDirectory!.path}/$fileName';
log(path);
saveToFirebase(path, fileName, firebasPath: '$firebasepath/$name')
.then((value) => {log('Received Audio Link: $value')});
}
/// saving converted audio file to firebase
Future<String> saveToFirebase(String path, String name,
{required String firebasPath}) async {
final firebaseStorage = FirebaseStorage.instance;
SettableMetadata metadata = SettableMetadata(
contentType: 'audio/mpeg',
customMetadata: <String, String>{
'userid': _app.userid.value,
'name': _app.name.value,
'filename': name,
},
);
var snapshot = await firebaseStorage
.ref()
.child(firebasPath)
.putFile(File(path), metadata);
var downloadUrl = await snapshot.ref.getDownloadURL();
print(downloadUrl + " saved url");
return downloadUrl;
}

how can i send Thumbnail from a video to firebase storage

i am developing flutter app and i need to send Thumbnail from a video to firebase storage
i am trying to do somthing like this
Uint8List VideoThumbnail ;
onPressed: () async {
final result = await FilePicker.platform.pickFiles(allowMultiple: false, );
final path = result.files.single.path;
setState(() => file = File(path));
if (file == null) {
return;
}
final img = await VideoCompress.getByteThumbnail(file.path) ;
// setState(() => this.VideoThumbnail = img );
if (file == null) return;
final fileName = basename(file.path);
final destination = 'files/$fileName';
task = FirebaseApi.uploadFile( destination,file); // here wont accept VideoThumbnail variable
setState(() {});

how can I get access to a document in firebase?

in my project im trying to get the id of the video and then open the video in my video but im struggling in 3 points
how can I can save real id into firebase?
this is how im doing it right know
uploadVideo() async {
setState(() {
isuploading = true;
});
try {
var firebaseuseruid = FirebaseAuth.instance.currentUser.uid;
DocumentSnapshot userdoc = await FirebaseFirestore.instance
.collection('meinprofilsettings')
.doc(firebaseuseruid)
.get();
var alldocs = await FirebaseFirestore.instance.collection('videos').get();
int length = alldocs.docs.length;
String videourl = await uploadvideotostorage("Video $length");
String previewimage = await uploadimagetostorage("Video $length");
FirebaseFirestore.instance.collection('videos').doc("Video $length").set({
'username': userdoc.data()['username'],
'uid': firebaseuseruid,
'profilepic': userdoc.data()['url'],
'id':"Video $length",
'likes': [],
'commentcount': 0,
'sharecount': 0,
'hashtag1': hashtagcontroller.text,
'hashtag2': hashtagcontroller2.text,
'hashtag3': hashtagcontroller3.text,
'videourl': videourl,
'previewimage': previewimage,
'ratings': [],
});
Navigator.pop(context);
} catch (e) {
print(e.toString());
}
}
}
what I want is the real id of the video instead of "Video $length"
2. how can I get access to the id when its created like how can I call it ? ?
3. How can I create a new collection with this id and then like saving some data but like this
new collection=> videoed => new field with some data , new field with some data
Heres how I upload it
the picture is for preview picture
getpreviewimage() async {
final previewimage = await flutterVideoCompress.getThumbnailWithFile(
widget.videopath_asstring,
);
return previewimage;
}
compressvideo() async {
if (widget.imageSource == ImageSource.gallery) {
return widget.videofile;
} else {
final compressvideo = await flutterVideoCompress.compressVideo(
widget.videopath_asstring,
quality: VideoQuality.MediumQuality);
return File(compressvideo.path);
}
}
uploadvideotostorage(String id) async {
final video = await allvideos.child(id).putFile(await compressvideo());
String url = await video.ref.getDownloadURL();
return url;
}
uploadimagetostorage(String id) async {
final video = await allimages.child(id).putFile(await getpreviewimage());
String url = await video.ref.getDownloadURL();
id=url;
return url;
}
If I understood correctly, change them to look like this:
Future<String> uploadvideotostorage(String id) async {
final video = await allvideos.child(id).putFile(await compressvideo());
String url = await video.ref.getDownloadURL();
return url;
}
Future<String> uploadimagetostorage(String id) async {
final video = await allimages.child(id).putFile(await getpreviewimage());
String url = await video.ref.getDownloadURL();
return url;
}
and this:
String videourl = await uploadvideotostorage(firebaseuseruid);
'id':videourl,
This is assuming that compressvideo() is working correctly.

How to download the PDF file after uploading to the Firebase storage, and show in the Flutter application and keep it always static

How to download the pdf after uploading to the firebase storage, and show in the flutter application and keep it always static.
I mean when ever user visits that flutter page or screen in the application, the pdf file downloaded should be opened on a click eventon a icon or image etc. It should not disappear after closing the application, when we open the application for the second time.
User should be able to download and view or open the PDF whenever he wish.
This is my code I have tried as below:
uploadToFirebase() {
if (_multiPick) {
_paths.forEach((fileName, filePath) => {upload(fileName, filePath)});
} else {
String fileName = _path.split('/').last;
String filePath = _path;
upload(fileName, filePath);
}
}
upload(fileName, filePath) {
_extension = fileName.toString().split('.').last;
StorageReference storageRef =
FirebaseStorage.instance.ref().child(fileName);
final StorageUploadTask uploadTask = storageRef.putFile(
File(filePath),
StorageMetadata(
contentType: '$_pickType/$_extension',
),
);
setState(() {
_tasks.add(uploadTask);
});
}
Future<void> downloadFile(StorageReference ref) async {
final String url = await ref.getDownloadURL();
final http.Response downloadData = await http.get(url);
final Directory systemTempDir = Directory.systemTemp;
final File tempFile = File('${systemTempDir.path}/tmp.jpg');
if (tempFile.existsSync()) {
await tempFile.delete();
}
await tempFile.create();
final StorageFileDownloadTask task = ref.writeToFile(tempFile);
final int byteCount = (await task.future).totalByteCount;
var bodyBytes = downloadData.bodyBytes;
final String name = await ref.getName();
final String path = await ref.getPath();
print(
'Success!\nDownloaded $name \nUrl: $url'
'\npath: $path \nBytes Count :: $byteCount',
);
_scaffoldKey.currentState.showSnackBar(
SnackBar(
backgroundColor: Colors.white,
content: Image.memory(
bodyBytes,
fit: BoxFit.fill,
),
),
);
}
This code only uploads pdf file but do not download and show pdf where as it is uploading image and downloading, showing image files
Yes Finally I have successfully downloaded the pdf file after uploading it to firebase storage in this way
`void filePicker(BuildContext context) async {
try {
PDfFile1 = await FilePicker.getFile(type: FileType.custom, allowedExtensions: ['pdf']);
fileName = p.basename(PDfFile1.path);
setState(() {
fileName = p.basename(PDfFile1.path);
isPDF_selected=true;
});
print(fileName);
// _uploadFile(PDfFile1, fileName);
} on PlatformException catch (e) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Sorry...'),
content: Text('Unsupported exception: $e'),
actions: <Widget>[
FlatButton(
child: Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
}
);
}
}
Future<void> _uploadFile(File PDFFile1, String filename) async {
if (FileType == 'pdf') {
PDfFile1 = await FilePicker.getFile(type: FileType.custom, allowedExtensions: ['pdf']);
fileName = p.basename(PDfFile1.path);
setState(() {
fileName = p.basename(PDfFile1.path);
isPDF_selected=true;
});
print(fileName);
// _uploadFile(PDfFile1, fileName);
}
final FirebaseStorage _storage4 =
FirebaseStorage(storageBucket: 'gs://flutter-cb66a.appspot.com');
//StorageUploadTask uploadTask4;
String PDFPath = 'DeviceDocs/DeviceDocs${DateTime.now()}.pdf';
final StorageReference _storagepdfreference = FirebaseStorage().ref().child(PDFPath);
StorageUploadTask uploadTask4 = _storagepdfreference.putFile(PDfFile1);
StorageTaskSnapshot downloadPDFUrl = (await uploadTask4.onComplete);
String url = (await downloadPDFUrl.ref.getDownloadURL());
print("URL is $url");
setState(() {
uploadTask4 = _storage4.ref().child('DeviceDocs/DeviceDocs${DateTime.now()}.pdf').putFile(PDfFile1);
_PDFUploaded= true;
});
}
Future downloadPDfFile1() async {
String downloadAddress= await _storagepdfreference.getDownloadURL();
setState(() {
_downloadPDFUrl= downloadAddress;
});
}
`
But Now I want to open the pdf directly from the pdfUrl. How to do so ?

Flutter http request upload mp3 file

Im using this api to upload a mp3 file
using this method
Future<void> uploadRecord(String matchId, String filePath) async {
Uri url = Uri.parse(
Urls.baseurl + EndPoints.uploadRecordEndPoint + '${auth.token}');
final request = http.MultipartRequest('POST', url)
..fields['match_id'] = matchId
..files.add(http.MultipartFile.fromBytes(
'file', await File.fromUri(Uri(path: filePath)).readAsBytes(),
contentType: MediaType('audio', 'mpeg')));
final response = await request.send();
final responseStr = await response.stream.bytesToString();
print(responseStr);
}
but it doesn't work, it seems that no file uploading, am i missing something ? or is there any better solution ?
Please use flutter_upload package for uploading file
Or use below code for uploading the file using multipart :
static Future<String> fileUploadMultipart(
{File file, OnUploadProgressCallback onUploadProgress}) async {
assert(file != null);
final url = '$baseUrl/api/file';
final httpClient = getHttpClient();
final request = await httpClient.postUrl(Uri.parse(url));
int byteCount = 0;
var multipart = await http.MultipartFile.fromPath(fileUtil.basename(file.path), file.path);
// final fileStreamFile = file.openRead();
// var multipart = MultipartFile("file", fileStreamFile, file.lengthSync(),
// filename: fileUtil.basename(file.path));
var requestMultipart = http.MultipartRequest("", Uri.parse("uri"));
requestMultipart.files.add(multipart);
var msStream = requestMultipart.finalize();
var totalByteLength = requestMultipart.contentLength;
request.contentLength = totalByteLength;
request.headers.set(
HttpHeaders.contentTypeHeader, requestMultipart.headers[HttpHeaders.contentTypeHeader]);
Stream<List<int>> streamUpload = msStream.transform(
new StreamTransformer.fromHandlers(
handleData: (data, sink) {
sink.add(data);
byteCount += data.length;
if (onUploadProgress != null) {
onUploadProgress(byteCount, totalByteLength);
// CALL STATUS CALLBACK;
}
},
handleError: (error, stack, sink) {
throw error;
},
handleDone: (sink) {
sink.close();
// UPLOAD DONE;
},
),
);
await request.addStream(streamUpload);
final httpResponse = await request.close();
//
var statusCode = httpResponse.statusCode;
if (statusCode ~/ 100 != 2) {
throw Exception('Error uploading file, Status code: ${httpResponse.statusCode}');
} else {
return await readResponseAsString(httpResponse);
}
}
Try to add filename to the
http.MultipartFile.fromBytes()

Resources