Regarding How to draw Unicode text in a PDF file - flutter

The following is excellent instruction. This is helpful information.
https://www.syncfusion.com/kb/11976/how-to-draw-unicode-text-in-a-pdf-file-using-google-fonts-package
However, I can't understand how to create the TTF file data by the getFont method. There is no "writeAsBytes" statement. This means the TTF file is always empty.
In what cases is the following condition TRUE?
// Line 11 of getFont
if (fontBytes != null && fontBytes.isNotEmpty) {

In the below KB documentation, we are getting the font from the Google fonts package in Flutter. The Google fonts package fetches the font files via HTTP at runtime and caches them in the application’s file system. In this article, we have used cached files to render the Unicode text in a PDF document. The reported problem is due to the Flutter Google fonts package being updated. And please make sure the device/emulator internet connectivity is properly connected or not. If not, please connect to the internet and try the below code snippet on your end and let us know the result.
Please refer to the below code snippet,
Future<PdfFont> getFont(TextStyle style) async {
//Get the external storage directory
Directory directory = await getApplicationSupportDirectory();
//Create an empty file to write the font data
File file = File('${directory.path}/${style.fontFamily}.ttf');
if (!file.existsSync()) {
List<FileSystemEntity> entityList = directory.listSync();
for (FileSystemEntity entity in entityList) {
if (entity.path.contains(style.fontFamily!)) {
file = File(entity.path);
break;
}
}
}
List<int>? fontBytes;
//Check if entity with the path exists
if (file.existsSync()) {
fontBytes = await file.readAsBytes();
}
if (fontBytes != null && fontBytes.isNotEmpty) {
//Return the google font
return PdfTrueTypeFont(fontBytes, 12);
} else {
//Return the default font
return PdfStandardFont(PdfFontFamily.helvetica, 12);
}
}

Related

Get file path from system directory using Flutter web (chrome) to read file content Eg: CSV or Text file

Package tried: https://pub.dev/packages/file_picker
Tried the example code implementation shared via GitHub. But the file path is returned as null for
web platform. Where same implementation in mobile platform return the path as expected.
https://github.com/miguelpruivo/flutter_file_picker/blob/master/example/lib/src/file_picker_demo.dart
Things aware of:
Path_Provider - Not supported for web
dart-io-library - Not supported for web
Open issue in Flutter Repo
Goal is to read the file from the path and not to upload. Any workaround to achieve this will be helpful.
Flutter channel: beta
As mentioned in the file_picker FAQ:
Paths aren't inaccessible from browsers since those provide fake paths. If you want to create a File instance to upload it somewhere, like FireStorage, you can do so with the bytes directly.
final result = await FilePicker.platform.pickFiles(type: FileType.any, allowMultiple: false);
if (result.files.first != null){
var fileBytes = result.files.first.bytes;
var fileName = result.files.first.name;
print(String.fromCharCodes(fileBytes));
}
I have a function for picking image from computer. Might work for you.
import 'dart:html';
void uploadImage({#required Function(File file) onSelected}) {
InputElement uploadInput = FileUploadInputElement()..accept = 'image/*';
uploadInput.click();
uploadInput.onChange.listen((event) {
final file = uploadInput.files.first;
final reader = FileReader();
reader.readAsDataUrl(file);
reader.onLoadEnd.listen((event) {
onSelected(file);
});
});
}

How to record a video with Camera Plugin in flutter?

I have this page where the camera is initialized and ready with a button that will record and stop the video, so I tried this :
FlatButton(
onPressed: () => {
!isRecording
? {
setState(() {
isRecording = true;
}),
cameraController.prepareForVideoRecording(),
cameraController.startVideoRecording('assets/Videos/test.mp4')
}
: cameraController.stopVideoRecording(),
},
............
but throws this error : nhandled Exception: CameraException(videoRecordingFailed, assets/Videos/test.mp4: open failed: ENOENT (No such file or directory)).
I don't understand, I don't want to open this file I want to save it there, Is there sth wrong with my code ?
In the new version, static method startRecordingVideo doesn't take any string parameter.
When you want to start the recording just see whether a video is already getting recorded, if not start
if (!_controller.value.isRecordingVideo) {
_controller.startVideoRecording();
}
and when you want to finish the recording you can call the static method stopVideoRecording() and it will give you a object of the class XFile, it will have the path to your video.
if (_controller.value.isRecordingVideo) {
XFile videoFile = await _controller.stopVideoRecording();
print(videoFile.path);//and there is more in this XFile object
}
This thing has worked for me. I am new to flutter please improve my answer if you know more.
You are trying to save a video in your assets folder which is not possible ,
What you need to do is to save to device locally either common folders like downloads or app directory.
Here is an example of how to go about it
dependencies:
path_provider:
Flutter plugin for getting commonly used locations on host platform
file systems, such as the temp and app data directories.
We will be saving the video to app directory.
We need to get the path to the directory where the file is or will be. Usually a file is put in the application's document directory, in the application's cache directory, or in the external storage directory. To get the path easily and reduce the chance of type, we can use PathProvider
Future<String> _startVideoRecording() async {
if (!controller.value.isInitialized) {
return null;
}
// Do nothing if a recording is on progress
if (controller.value.isRecordingVideo) {
return null;
}
//get storage path
final Directory appDirectory = await getApplicationDocumentsDirectory();
final String videoDirectory = '${appDirectory.path}/Videos';
await Directory(videoDirectory).create(recursive: true);
final String currentTime = DateTime.now().millisecondsSinceEpoch.toString();
final String filePath = '$videoDirectory/${currentTime}.mp4';
try {
await controller.startVideoRecording(filePath);
videoPath = filePath;
} on CameraException catch (e) {
_showCameraException(e);
return null;
}
//gives you path of where the video was stored
return filePath;
}

Flutter how to specify file path in asset folder

I have a sound file in asset folder and I can check if it exist using code like below:
if (FileSystemEntity.typeSync(
'/Users/admin/Library/Developer/CoreSimulator/Devices/AC8BED2E-4EF1-4777-A399-EBD52E38B5C7/data/Containers/Data/Application/1390EE2C-A5D8-46E0-A414-AAC2B83CD20C/Library/Caches/sounds/3/unbeaten.m4a') !=
FileSystemEntityType.notFound) {
print('file is found');
} else {
print('not found');
}
As you can see I need to use the absolute path. Is there a way to check if the file is in the asset folder using path like 'assets/sounds/3/unbeaten.m4a' without the need to specify the whole path?
As was mentioned by #frank06, by using path_provider, I am able to check if a file is in asset folder or not by using the following code. But this works for iOS only and I am still trying to find a solution for Android. Notice the need to add /Library and /Caches for iOS. For Android, it seems that I can't see the path unlike that of iOS.
I would appreciate it if anyone could provide me some info for that of Android. The appDir looks like this for Android - /data/user/0/com.learnchn.alsospeak/app_flutter/
directory = await getApplicationDocumentsDirectory();
var parent = directory.parent;
var directoryPath = directory.path;
var parentPath = parent.path;
String testString = 'sounds/3/unbeaten.m4a';
parentPath = parentPath + '/Library' '/Caches/' '$testString';

How to fix Flutter stream exiting whenever i try to listen to it

In a flutter app, I'm trying to read a large csv file one line at a time by opening a stream on it. The issue is that when i try to listen to the stream the execution just skips over that code block and the program ends.
The file I'm opening is located in my assets folder and I've confirmed programmatically that it does exist before opening the stream. Changing the file the stream is opened on doesn't help, the same problem persists. I've also tried to change the way i listen to the stream, following different methods provided by Darts official documentation (that code is commented out) but the outcome is again the same. The assets have been declared in the pubspec.yaml. When i change the code to read the file as a String the program works perfectly but I want to use a stream because the file is so massive that creating a String object for it would take a large amount of time and memory.
void trainDigitsStream() async{
List<List<List>> filters = createRandomFilter(4, 4, 1, -1, 1);
List flattened= new List<double>();
File file = new File("assets/digit_train_data.csv");
if(file.existsSync())print("EXISTS!");
Stream<List<int>> stream = file.openRead();
Stream lines = utf8.decoder.bind(stream).transform(LineSplitter());
/*
try{
await for (var line in lines){
print(line);
}
print("file ended");
}catch(e){
print(e);
}
*/
lines.listen((data){//code exits here, execution never reaches next line
String line = data.toString();
List<List> instance = new List<List<int>>();
List x = new List<int>();
int i = 0;
line.split(',').forEach((d){
x.add(int.parse(d));
i++;
if(i == 28){
instance.add(x);
x = new List<int>();
i = 0;
}
});
List<List<List>> kernels = new List<List<List<double>>>();
List<List> pools = new List<List>();
filters.forEach((f){kernels.add(convo.applyFilter(instance, f, 0));});
kernels.forEach((k){pools.add(pool.maxPool(k, 2));});
pools.forEach((p){flattened.addAll(p);});
});
}
It's hard without further information, It would be better if you can post more information.
So I guess the problem should be , please check the following two steps.
1. Register the assets folder in pubspec.yaml
flutter:
assets:
- assets/digit_train_data.csv
2. You need to use rootBundle to access this csv file, reference document https://flutter.dev/docs/development/ui/assets-and-images
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadAsset() async {
return await rootBundle.loadString('assets/digit_train_data.csv');
}
similar question here Flutter - Read text file from assets

cn1 - get file path to image for share()

I'm trying to use the share() method, including an image, but I'm having trouble supplying the proper path to the image. Where should I put the image file, and what is the path (putting in the default package and trying "jar:///myimage.png" didn't work), and why is this not documented clearly?
image can be stored in storage which is following path for window
C:\Users\userName.cn1
and the image can be read by using following codes
InputStream is = Storage.getInstance().createInputStream("tizbn.JPG");
EncodedImage i = EncodedImage.create(is, is.available());
Loading image from default folder
Image i =EncodedImage.create("/tizbn.png");
Loading image From Theme
EncodedImage current = (EncodedImage) fetchResourceFile().getImage("tizbn.png");
The share API works with https://www.codenameone.com/javadoc/com/codename1/io/FileSystemStorage.html[FileSystemStorage] and not with https://www.codenameone.com/javadoc/com/codename1/io/Storage.html[Storage].
You need to save the file into a file system path which is always an absolute path, we recommend using the app home to store files. There is a sample in the developer guide section on the ShareButton covering this:
Form hi = new Form("ShareButton");
ShareButton sb = new ShareButton();
sb.setText("Share Screenshot");
hi.add(sb);
Image screenshot = Image.createImage(hi.getWidth(), hi.getHeight());
hi.revalidate();
hi.setVisible(true);
hi.paintComponent(screenshot.getGraphics(), true);
String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
} catch(IOException err) {
Log.e(err);
}
sb.setImageToShare(imageFile, "image/png");