flutter get pdf files string data to variable - flutter

I want to take a pdf files string data in a fast way and the package which I use is giving some problems.
How can I get correctly and fast way a pdf file?
Thanks for your help.
this is the way ı using
PDFDoc? _pdfDoc;
String _text = "";
_getPdfFile() {
setState(() async {
_pdfDoc = await PDFDoc.fromPath(filePath!);
data = await _pdfDoc!.text;
});
}

this is the source of code. this code will take string data from the pdf page 3.
Instead, if you want all the data in pdf you can look at this link.https://help.syncfusion.com/flutter/pdf/working-with-text-extraction
final String data;
final PdfDocument document =
PdfDocument(inputBytes: myFile.readAsBytesSync());
setState(() {
data = PdfTextExtractor(document).extractText(startPageIndex: 3);
});
document.dispose();

Related

Why changes made to this class field disappear after leaving async method?

So, I'm trying to do something that seems simple, but I can't get why it is not working.
I wrote this code:
class HomepageModel {
List<dynamic> data = [];
String _url = '[...]'; //My URL is working
Future _comm() async {
data = await httpFetch(_url); //This 'httpFetch' just does some json decoding
print(data); //Shows data normally
}
HomepageModel() {
_comm();
print(data); //Shows empty list
}
}
I want to store data retrieved from an API in the field data. I was able to get the data in function _comm, and when I print the field, it shows normally. But, outside this method, the content of the data field seems to have disappeared! Both on the print in the constructor, and in other files, all the prints show just an empty list.
What should I do to be able to properly store data from the API in a class field?
class HomepageModel {
List<dynamic> data = [];
String _url = '[...]'; //My URL is working
Future _comm() async {
data = await httpFetch(_url); //This 'httpFetch' just does some json decoding
print(data); //Shows data normally
}
HomepageModel() {
_comm().then((_){
print(data);
});
}
}

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);
}
}
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));

What is the best way to work with files in Flutter?

I'm a junior working with flutter and hit a problem.
I need to open a file, read and compare some data everytime the app opens and then change some of that data as the app progress. We tried using .txt files to read and write some text, but when we had to look for something in the file was too complicated to change it and the file is not accessibe only on the device running the app. We also thought of using xml files but I don't know if is a good idea.
What would be a pratical solution for this situation, as the file needs to be opened all the time. Thanks.
Let's say our JSON looks like this:
{
title: 'some text',
values: [1,5,2,4,1,3],
}
And we want to make a UI that allows us to add values and to edit the title. First let's write a method to write and read from the JSON file:
Future<void> _write(Map<String, dynamic> value) async {
File f = File(_fileLocation);
String jsonStr = jsonEncode(value);
await f.writeAsString(jsonStr);
}
Future<Map<String, dynamic>> _read() async {
File f = File(_fileLocation); // maybe move this into a getter
final jsonStr = await f.readAsString();
return jsonDecode(jsonStr) as Map<String, dynamic>;
}
This way, the rest of the app should be trivial, but let's add a method to update the title and a method to add a new number:
Future<void> _updateTitle(String title) async {
var values = await _read();
values['title'] = title;
await _write(values);
}
Future<void> _addNumber(int number) async {
var values = await _read();
values['values'].push(number);
await _write(values);
}
Types with JSON and Dart can be a bit weird, so it is possible you need to use the as keyword when reading from the list:
Future<void> _addNumber(int number) async {
var values = await _read();
var valueList = (values['values'] as List<int>);
valueList.push(number);
values['values'] = valueList;
await _write(values);
}
Hopefully, this example helps

Printing Image with Bluetooth Printer in Flutter

I want to print the screenshot image of first page in Flutter. So far I have come up to the part where I need to parse that image into function that would print it, here is the code:
FIRST PAGE
_screenshot() {
screenshotController.capture().then((File image) {
//Capture Done
setState(() {
_screenshot = image;
});
print('Successful Screenshot => $_screenshot');
Navigator.push(
context, MaterialPageRoute(builder: (context) => Print(_screenshot)));}
So this is the page that screenshots that whole page and pushes that screenshot to the second screen. Here is the second screen:
SECOND PAGE
class Print extends StatefulWidget {
final File screenshot;
Print(this.screenshot);
#override
_PrintState createState() => _PrintState();
}
Here I initialize that image from the first page, and then I created the function for printing that should print the ticket, but I am getting an error:
Future<Ticket> _ticket(PaperSize paper) async {
final ticket = Ticket(paper);
//this is a working option, but I don't want to load from assets, but load screenshot file from first page
//final ByteData data = await rootBundle.load(assets/store.png');
final File img = await rootBundle.load(widget.screenshot); //here parse the image from first page **ERROR HERE**
final Uint8List bytes = data.buffer.asUint8List();
final Image image = decodeImage(bytes);
ticket.image(image);
return ticket;
}
I am getting an error that Byte data cannot be assigned to variable type File which I understand, but how would I go around making this work? I am using the esc_pos_bluetooth: ^0.2.8 library for bluetooth printing.
You don't need to load data from rootBundle instead, you can use readAsBytes() class method from File class which returns Uint8List.
Uint8List bytes = await widget.screenshot.readAsBytes();
Your final code should look like.
Future<Ticket> _ticket(PaperSize paper) async {
final ticket = Ticket(paper);
final Uint8List bytes = await widget.screenshot.readAsBytes();
final Image image = decodeImage(bytes);
ticket.image(image);
return ticket;
}

Flutter: How to encode and decode audio files in Base64 format?

I'm building a ChatBot app using Dialogflow and I want to implement Voice Recognition feature in my app. As you know Dialogflow provide us a feature to detect intent on the basis of audio but it only accepts audio in the form of base64. The problem for me is that I'm unable to encode the audio file into Base64. I'm new to Flutter Development so if in case I'm missing something or doing it in a wrong way then please let me know. Thanks!
I've tried this method but it's not giving me the proper output:
Future<String> makeBase64(String path) async {
try {
if (!await fileExists(path)) return null;
File file = File(path);
file.openRead();
var contents = await file.readAsBytes();
var base64File = base64.encode(contents);
return base64File;
} catch (e) {
print(e.toString());
return null;
}
}
You could do this:
List<int> fileBytes = await file.readAsBytes();
String base64String = base64Encode(fileBytes);
The converted string doesn't include mimetype, so you might need to include like this
final fileString = 'data:audio/mp3;base64,$base64String';