How to convert a PDF file to an image with Flutter? - flutter

How can I convert a PDF file into an image with Flutter?
I want to print the image to an ESC/POS printer using esc_pos_printer. This package won't accept PDFImage, it needs to be a Flutter Image.
I see plenty of PHP plugins that do this but nothing for Flutter.
edit: There is an answer to another question here which shows some code to decode an image from "pdf64" but I can't figure out exactly what "pdf64" is.
I created a PDF from html using flutter_html_to_pdflike this:
Directory appDocDir = await getApplicationDocumentsDirectory();
var targetPath = appDocDir.path;
var generatedPdfFile = await FlutterHtmlToPdf.convertFromHtmlContent(
htmlContent, targetPath, targetFileName);
generatedPdfFilePath = generatedPdfFile.path;
Now I need to know how to create a Flutter Image from that PDF or the bytecode to send raw to the printer.

You can use https://pub.dev/packages/printing:
await for (var page in Printing.raster(document)) {
final image = page.asImage();
...
}
This plugin can also convert your Html to Pdf with this:
final pdf = await Printing.convertHtml(
format: PdfPageFormat.a4,
html: '<html><body><p>Hello!</p></body></html>',
));

Related

Get text content from an epub file flutter

I am trying to extract text content from an epub file but unable to do so. I have tried converting it to bytes and then read it but it's not returning a proper text. I can't find any library that helps me do so.
I only need the text file from the epub file so that I can read it with text to speech.
I did it using the epubx package
Here is the complete code
File _epubFile = File(file.path);
final contents = await _epubFile.readAsBytes();
EpubBookRef epub = await EpubReader.openBook(contents.toList());
var cont = await EpubReader.readTextContentFiles(epub.Content!.Html!);
List<String> htmlList = [];
for (var value in cont.values) {
htmlList.add(value.Content!);
}
var doc = parse(htmlList.join());
final String parsedString = parse(doc.body!.text).documentElement!.text;
return parsedString;

How can one convert an XFile image from any format to a JPG image for upload?

Right now I'm able to chose an image as XFile using MultiImage picker as follows:
final List<XFile>? images = await _picker.pickMultiImage(maxWidth: _maxWidth, maxHeight:_maxHeight);
which then gives me a list of images which I am able to send into my upload service for uploading to my server
for (var image in images)
{
await myUploadService(image); //image is an XFile
}
Now what I need to do is convert the images, no matter what format they are in, into a JPG image before the upload
So I have tried to convert the images, using the image Flutter package (https://github.com/brendan-duncan/image) as follows:
import 'package:image/image.dart' as ImageConvert;
for (var image in images)
{
//Convert all images to JPG
final newImage = ImageConvert.decodeImage(File(image.path).readAsBytesSync())!;
var newImg = ImageConvert.encodeJpg(newImage);
var newImg2 = Image.memory(Uint8List.fromList(newImg)) as XFile; // <--- the main problem
await myUploadService(newImg2);
}
But this isn't working, mainly at the point where I try to put the image back into an XFile format for upload with my upload service
So the main question is here is how can I convert the newly encoded JPG image back to XFile format?
Open to totally different strategies of dealing with this issue as well

Store image uploaded by user into Flutter Web as an actual .jpg file

I am using the flutter_web_image_picker package to allow the user to select -and then upload to Firebase- an image.
However, the package returns an image widget, which I can display, but I cannot upload to Firebase. Therefore, I am trying to read the package's code and update it to fit my needs.
In general, I think the packages main functionalities are:
It gets the file
//...
final reader = html.FileReader();
reader.readAsDataUrl(input.files[0]);
await reader.onLoad.first;
final encoded = reader.result as String;
Then it 'strippes' it
final stripped = encoded.replaceFirst(RegExp(r'data:image/[^;]+;base64,'), '');
final imageName = input.files?.first?.name;
//...
To finally return it as a Widget:
final imageName = imageName;
final imageData = base64.decode(stripped);
return Image.memory(imageData, semanticLabel: imageName);
As I said, it works perfectly, however, I need to adapt it to my needs:
I would like to get the image as a .jpg file so that I can upload it to Firebase.
Is any of the variables above the actual .jpg file? Is there any transformation that I should perform to get a .jpg file?
Thanks!
I based my answer on this post.
Basically, on the flutter_web_image_picker package, before the code I posted, there were a few lines that get an actual html file:
final html.FileUploadInputElement input = html.FileUploadInputElement();
input..accept = 'image/*';
input.click();
await input.onChange.first;
if (input.files.isEmpty) return null;
Then using firebase's pacakge, I uploaded the image as follow:
import 'package:firebase/firebase.dart' as fb;
fb.StorageReference storageRef = fb.storage().ref('myLocation/filename.jpg');
fb.UploadTaskSnapshot uploadTaskSnapshot = await storageRef.put(input.files[0]).future;
Uri imageUri = await uploadTaskSnapshot.ref.getDownloadURL();
return imageUri;

How to Share Image from API(URL) in flutter?

Here I want to share image which I get through API. I tried different method for this functionality but I did not get any solution because every solutions have for only one image.
Exactly, I get multiple image from Url and I open any particular image in next page. So, I want to share that image which I opened in another page.
I tried for sharing image but I could not did this. Whenever I try to share that image, Image url share with sharing option on device but I want share image not URl of image How I can accomplish this?
You have to download the image like this:
http.Response response = await http.get(url);
then create an image on the device using the downloaded image like this (Read and Write Files):
final directory = await getTemporaryDirectory();
final path = directory.path;
final file = File('$path/image.png');
file.writeAsBytes(response.bodyBytes);
The getTemporaryDirectory() is in the plugin path_provider. Now, you have the image you'd like to share stored in the temporarily as "image.png" and you can use the share_plus plugin to share the image like this:
Share.shareFiles(['$path/image.png']);
Thanks to #abdulrazak, At first, you have to download the image in a temporary path & then you can share the image as you want. used Dio to download the image & share_plus for sharing
void _shareNetworkImage(String url) async {
Directory tempDir = await getTemporaryDirectory();
final path = '${tempDir.path}/test.jpeg';
await Dio().download(url, path);
Share.shareFiles([path]);
}
You can use the esys_flutter_share plugin.
Install it, and then get dependencies:
dependencies:
esys_flutter_share: ^1.0.2
Import the plugin to your code:
import 'package:esys_flutter_share/esys_flutter_share.dart';
Use the below code:
var request = await HttpClient().getUrl(Uri.parse('https://yourImageURL.jpg'));
var response = await request.close();
Uint8List bytes = await consolidateHttpClientResponseBytes(response);
await Share.file('ESYS AMLOG', 'amlog.jpg', bytes, 'image/jpg');

Getting FirebaseVisionImage from manipulated image in Flutter

I'm trying to do some pre-processing in my image before using Firebase MLkit. Previously, I was simply loading my image and then passing it directly like this.
File file = await FilePicker.getFile(type: FileType.IMAGE);
final FirebaseVisionImage visionImage = FirebaseVisionImage.fromFile(file);
VisionText visionText = await textRecognizer.processImage(visionImage);
But now, I wanted to do some processing on the image. I did this using Flutter's Image package like this.
import 'package:image/image.dart' as Img;
File file = await FilePicker.getFile(type: FileType.IMAGE);
Img.Image image = Img.decodeImage(file.readAsBytesSync());
var img = Img.invert(image);
Now, how do I pass this new object to FirebaseVisionImage. I see that there is this function:
FirebaseVisionImage.fromBytes(bytes, metadata)
I'm guessing I can get bytes from the above image object using img.getBytes() but I'm confused how to set the metadata.
EDIT:
I see that one can write the image to a temporary file doing
img.writeAsBytesSync(decoded.ToList());
and then use that image again using FirebaseVisionImage.fromFile() but I would really prefer not to do that.