How to print a PDF file in Flutter - flutter

Here is my code
Future<File> _downloadFile(String url, String filename) async {
http.Client _client = new http.Client();
var req = await _client.get(Uri.parse(url));
var bytes = req.bodyBytes;
// String dir = (await getApplicationDocumentsDirectory()).path;
String dir = await ExtStorage.getExternalStoragePublicDirectory(
ExtStorage.DIRECTORY_DOWNLOADS);
File file = new File('$dir/$filename');
await file.writeAsBytes(bytes);
return file;
}
/// Prints a sample pdf printer
void printPdfFile() async {
var file = await _downloadFile(
"http://www.africau.edu/images/default/sample.pdf", "test.pdf");
await FlutterPdfPrinter.printFile(file.path);
}
I am implementing print PDF files which is saved in my device. When trying to print the document I am getting error like "A problem occurred configuring project ':flutter_pdf_printer'."
I am using flutter_pdf_printer dependency to print PDF files.

Convert your string url to URI, please make sure you are adding http
http: ^0.13.4
import 'package:http/http.dart' as http;
Uri uri = Uri.parse('Your link here');
http.Response response = await http.get(uri);
var pdfData = response.bodyBytes;
await Printing.layoutPdf(onLayout: (PdfPageFormat
format) async => pdfData);

Related

Flutter App for encryption an audio for secure

I have a project with encrypt an audio for secure my data audio and when the user purchase they can play the audio, but until now didn't find how to do that. I found another way by converting the audio data into a string and then encrypting it, I found a code but it's incomplete so I'm still confused about using it.
import 'dart:io';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:path_provider/path_provider.dart';
class MediaFile {
Future<String> get docPath async {
Directory appDocDir = await getApplicationDocumentsDirectory();
return appDocDir.path;
}
Future<Uint8List> get audioFileData async {
final String path = await docPath;
final String theFilePath = '$path/test.mp3';
final File theFile = new File(theFilePath);
if (await theFile.exists()) {
return await theFile.readAsBytes();
} else {
File file = await FilePicker.getFile();
return await file.readAsBytes();
}
}
Future<String> dataToString() async {
Uint8List data = await audioFileData;
return new String.fromCharCodes(data);
}
Future<File> saveMediaAsString(String fileName, String fileContent) async {
String path = await docPath;
Directory dataDir = new Directory('$path/data');
if (await dataDir.exists()) {
File file = new File('$path/data/$fileName');
return file.writeAsString(fileContent);
}
await dataDir.create();
File file = new File('$path/data/$fileName');
return file.writeAsString(fileContent);
}
Future<String> readFromStringMediaFile(String fileName) async {
String path = await docPath;
File file = new File('$path/data/$fileName');
return file.readAsString();
}
Uint8List stringToData(dataStr) {
List<int> list = dataStr.codeUnits;
return new Uint8List.fromList(list);
}
Future<File> createAudioFile(String fileName, Uint8List bytes) async {
String path = await docPath;
File file = new File('$path/$fileName');
return await file.writeAsBytes(bytes);
}
//here you can see how to use them
Future<File> testFile() async {
String dataStr = await dataToString();
File savedFile = await saveMediaAsString('codedFile', dataStr);
String contentSavedFile = await readFromStringMediaFile('codedFile');
Uint8List bytes = stringToData(contentSavedFile);
return await createAudioFile('test.mp3', bytes);
}
}

how to open excel file from internet

I am trying to open a excel file from internet.
I am using open_file but it is not working
I am trying this
Future<File> _fileFromUrl(String url) async {
final response = await http.get(url);
final documentDirectory = await getApplicationDocumentsDirectory();
final file = File(p.join(documentDirectory.path, 'excel_file.xslx'));
print(file.path);
print(await file.exists());
file.writeAsBytesSync(response.bodyBytes);
return file;
}
File excelFile = await _fileFromUrl(path);
OpenFile.open(excelFile.path);

How to add local image to flutter_local_notifications

I am trying to create push notifications and would like to add an image to the notification. I am able to add images from the web as shown in the screenshot below.
How can I add a local image instead? I tried adding the file path as shown below, but it did not work:
The file path you are adding is a root path of your project but this method needs an android file path(e.g. /storage/emulated/0/Android/data/com.expampe.app/cache/bg.png), so you have to convert your asset image to a File and save it, then return its path:
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';
Future<String> getImageFilePathFromAssets(String asset) async {
final byteData = await rootBundle.load(asset);
final file =
File('${(await getTemporaryDirectory()).path}/${asset.split('/').last}');
await file.writeAsBytes(byteData.buffer
.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file.path;
}
then just
final attachmentPicturePath = await getImageFilePathFromAssets('assets/image2.jpg');
The Easiest Way is--
static Future<String> getImageFilePathFromAssets(
String asset, String filename) async {
final byteData = await rootBundle.load(asset);
final temp_direactory = await getTemporaryDirectory();
final file = File('${temp_direactory.path}/$filename');
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes,
byteData.lengthInBytes));
return file.path;
}
final bigpicture = await Utils.getImageFilePathFromAssets(
'assets/images/largicon.png', 'bigpicture');
And For donwload Using URL---
add http and path_provider in pubspec.yml
static Future<String> downloadFile(String URL, String filename) async
{
final direactory = await getApplicationSupportDirectory();
final filepath = '${direactory.path}/$filename';
final response = await http.get(Uri.parse(URL));
print(response);
final file = File(filepath);
await file.writeAsBytes(response.bodyBytes);
return filepath;
}
check this demo github

How to download video from url into internal storage of phone in flutter?

I am playing a video in my app from the URL. I need to download that video into internal storage of phone. How can I achieve this. Is there any way. I am new to flutter?
You can download video using the following code ....
static var httpClient = HttpClient();
Future<File> downloadFile(String url1, String filename) async {
var request = await httpClient.getUrl(Uri.parse(url1));
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
String dir = (await getApplicationDocumentsDirectory()).path;
File file = new File('$dir/$filename');
await file.writeAsBytes(bytes);
return file;
}
Here is an example that can help you
downloadVideo()
{ var url = "Your url";
var status = await Permission.storage.status;
if (!status.isGranted) {
await Permission.storage.request();
}
var tempPath = await ExtStorage.getExternalStoragePublicDirectory(
ExtStorage.DIRECTORY_DOWNLOADS);
try {
var res = await http.get(
'$url',
headers: <String, String>{
'Authorization': _userDataController.userDataModel.token,//if authorization is not required then remove this line
},
);
filePath = tempPath + '/Video1.mp4';//use you own video format
} catch (e) {
print(e);
}}
you have to use permission_handler: ^8.1.2 & http: ^0.13.3 and path_provider: ^2.0.2

how to upload image to rest API in flutter through http post method?

I'm trying to upload an image through the flutter via post method. and I'm using image_picker for pick file from mobile but I can't able to upload
and I have tried to send the file like FormData that also doesn't work
Future<dynamic> uploadLicence(int id ,dynamic obj) async {
FormData formdata = new FormData(); // just like JS
formdata.add("image",obj);
final response = await post('Logistic/driver/LicenceImage?
driverId=$id',
formdata);
print(response);
// return null;
if (response.statusCode == 200) {
final result = json.decode(response.body);
return result;
} else {
return null;
}
}
after that, I just tried with this method but this also not working
Future<dynamic> uploadLicence(int id, File file) async {
final url = Uri.parse('$BASE_URL/Logistic/driver/LicenceImage?
driverId=$id');
final fileName = path.basename(file.path);
final bytes = await compute(compress, file.readAsBytesSync());
var request = http.MultipartRequest('POST', url)
..files.add(new http.MultipartFile.fromBytes(
'image',bytes,filename: fileName,);
var response = await request.send();
var decoded = await
response.stream.bytesToString().then(json.decode);
if (response.statusCode == HttpStatus.OK) {
print("image uploded $decoded");
} else {
print("image uplod failed ");
}
}
List<int> compress(List<int> bytes) {
var image = img.decodeImage(bytes);
var resize = img.copyResize(image);
return img.encodePng(resize, level: 1);
}
It's possible with MultipartRequest. Or you can use simply dio package. It's one command.
With http:
import 'package:http/http.dart' as http;
final Uri uri = Uri.parse(url);
final http.MultipartRequest request = http.MultipartRequest("POST", uri);
// Additional key-values here
request.fields['sample'] = variable;
// Adding the file, field is the key for file and file is the value
request.files.add(http.MultipartFile.fromBytes(
field, await file.readAsBytes(), filename: filename);
// progress track of uploading process
final http.StreamedResponse response = await request.send();
print('statusCode => ${response.statusCode}');
// checking response data
Map<String, dynamic> data;
await for (String s in response.stream.transform(utf8.decoder)) {
data = jsonDecode(s);
print('data: $data');
}
I user this code for my project i hope work for you
Upload(File imageFile) async {
var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var uri = Uri.parse(uploadURL);
var request = new http.MultipartRequest("POST", uri);
var multipartFile = new http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
//contentType: new MediaType('image', 'png'));
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}