In Flutter, how does one preview a document? - flutter

I've searched through DuckDuckGo/Google, stackOverflow, Github and flutter documentation and plugin repository, but I can't seem to find the answer to this simple question:
How can I, having a document's file uri, display a preview thumbnail for it as an Image?

Well, you could read the file as a String and then get the first 500 characters with a substring from it:
// File path
final file = await File.fromUri(uri);
// Read the file
String contents = await file.readAsString();
// Get first 500 characters or how many you want
String preview = contents.substring(0, 500);
// Display in widget
Text(preview);
Don't forget to put it into a StatefulWidget and update the state when the file was finished reading. Also see Flutters File class.

Related

How to convert a pdf file (composed of different images) to list of images in flutter?

I am developeing a PDF converter flutter app it converts images into pdf file. I want to expand it so that it should take pdf file and convert it into list of images so that i can rearrange order of images or remove a specific image form pdf. How can i solve this issue.I tried multiple packages but didn't find a solution.
Anyone can help me?
Thanks!
I am developeing a PDF converter flutter app it converts images into pdf file. I want to expand it so that it should take pdf file and convert it into list of images so that i can rearrange order of images or remove a specific image form pdf. How can i solve this issue.I tried multiple packages but didn't find a solution. Anyone can help me? Thanks!
Try to use PDFTron SDK package.
pdftron_flutter: ^0.5.0
or import this:
import 'package:pdftron_flutter/pdftron_flutter.dart';
import 'package:pdftron/pdftron.dart';
Initialize first:
await PDFNet.initialize();
methhods:
var pdfDoc = await PDFDoc.fromFilePath(filePath);
var page = await pdfDoc.getPage(pageNumber);
var resources = await page.getResources();
var image = await resources.getImage(imageName);
var imageData = await image.getImageData();
convert the image data to a flutter using Image.memory
var imageWidget = Image.memory(imageData);

iText - add image to an existing PDF

I am doing the following using iText.
I have a PDF
I add an image to the PDF
I save the modified PDF.
To add image in PDF I am using this method itext-add.
This worked fine until I got a certain PDF. In this PDF, the adding-image-to-the-pdf method doesn't work. Moreover, it corrupts the PDF.
Points to note:
I'm getting PDFs from a third party and these are contractual PDFs. So it is possible that they have added some restrictions.
And one fun fact, when I add an annotation on the same page where I want to add that image, that image starts coming!
I'm using iText 7.1.10
String srcFileName = "/Users/kalpit/Desktop/step1-stack.pdf";
String destFileName = "step1-test1-kd2.pdf";
File destFile = new File(destFileName);
PdfDocument pdf = new PdfDocument(new PdfReader(srcFileName), new PdfWriter(destFile),new StampingProperties().useAppendMode());
Document document = new Document(pdf);
String imFile = "/Users/kalpit/Desktop/sample-image.png";
ImageData data = ImageDataFactory.create(imFile);
Image image = new Image(data);
document.add(image);
document.close();
and here is the PDF : https://ipupload.com/tP6/step1.pdf
As #Nikita found out, the problem does only occur if working in append mode. The cause is that in unfortunate conditions the changed resources are not stored, a bug.
The unfortunate conditions here are that on page 1
the content stream array already is an indirect object in its own right, so only this indirect object (and not the page object) is marked as changed when the instructions for showing the image are added; and
the resources and resource type dictionaries are direct objects but only they (and not the page object, the indirect object holding them) are marked as changed when the image resource is added.
Thus, the changes to the page content streams are stored but the page object is not.
So there now is an instruction to draw an image from an image page resource which is not there.
One way to work around this is not to use append mode as proposed by #Nikita.
Alternatively, if you are required to use append mode, you can explicitly mark your page as changed:
Document document = new Document(pdf);
String imFile = "/Users/kalpit/Desktop/sample-image.png";
ImageData data = ImageDataFactory.create(imFile);
Image image = new Image(data);
document.add(image);
pdf.getFirstPage().setModified(); // <-----
document.close();
Well, something wrong with appendMode. Do you really need him? Try to add image via the next code:
PdfDocument pdf = new PdfDocument(new PdfReader(srcFile), new PdfWriter(outFileName));
Document doc = new Document(pdf);
PdfImageXObject xObject = new PdfImageXObject(ImageDataFactory.createPng(UrlUtil.toURL(pathToYourimage.png)));
Image image = new Image(xObject, 100).setHorizontalAlignment(HorizontalAlignment.RIGHT);
doc.add(image);
doc.close();
The result is the next

Replace uploaded image using Cloudinary and Flutter

I upload my images like this:
CloudinaryResponse response = await this.url.uploadImage(filePath,
filename: "background",
folder: "alquileres/$userId/$portfolioId/$investmentId");
The image names are "background_longID". I'd like to overwrite all the images.
I've found an old issue in Github but doesn't provide too much info (https://github.com/cloudinary/cloudinary_ios/issues/87)
You can find details about the upload and various flags for upload on the documentation page at https://cloudinary.com/documentation/image_upload_api_reference#upload_method.
If the primary concern is that you don't want Cloudinary to add the _longId parameter to the file name, you can set the flag unique_filename=false during the upload.
Another flag that you should consider is overwrite. By default, this flag is set to false. So when you re-upload, the old image is not replaced. You could set the flag overwrite=true as well to ensure that the new image is uploaded correctly.
Cloudinary doesn't support integration with flutter. there are some third parties that you can use for example here: https://gist.github.com/Wizpna/eab058e15cc1533bdb73bf764078f642
If you would like to upload images to Cloudinary, our best practice is to add an upload widget. You can read more about it here:
https://cloudinary.com/documentation/upload_widget
For someone who might be having the same issue, here is what i did
CloudinaryClient client = new CloudinaryClient(<API_KEY>, <API SECRET>, <CLOUD NAME>);
await client.uploadImage( file.path, filename: <NAME_FOR_PHOTO>, folder: <FOLDER_NAME(OPTIONAL)>)
.then((result){
print("CLOUDINARY:: ${result.secure_url}==> result");
})
.catchError((error) => print("ERROR_CLOUDINARY:: $error"));
You can use this package https://pub.dev/packages/cloudinary_public which does not require your API_KEY or API_SECRET

How can I read and Write Files in Flutter Web?

I am working on flutter-web, I would like to do file operations(read and write) in flutter-web.
For Android and IOS, I was using path_provider dependency. But in Flutter-web, it is not supported.
Can anyone help me with this?
The accepted answer is not completely right. Yes, dart:io is not available on the web, but it is still possible to read files. You can select a file through the system's file picker and read it afterward.
An easy option to "write" a file is to send the user an auto-download.
Read:
Use this library to select a file: pub.dev/packages/file_picker (Web migration guide)
import 'dart:html' as webFile;
import 'package:file_picker_web/file_picker_web.dart' as webPicker;
if (kIsWeb) {
final webFile.File file = await webPicker.FilePicker.getFile(
allowedExtensions: ['pd'],
type: FileType.custom,
);
final reader = webFile.FileReader();
reader.readAsText(file);
await reader.onLoad.first;
String data = reader.result;
}
Write (a.k.a download):
import 'dart:html' as webFile;
if (kIsWeb) {
var blob = webFile.Blob(["data"], 'text/plain', 'native');
var anchorElement = webFile.AnchorElement(
href: webFile.Url.createObjectUrlFromBlob(blob).toString(),
)..setAttribute("download", "data.txt")..click();
}
in the dart docs it has been explained ... dart:io is not available to web build ... it means that you can not directly access to system files in flutter web . the build will fail .. you need to remove the code in order to run it
this is a security thing .. js doesn't allow it too .. imagine a website that can read all your system files if you visit it .. that's why things like path reading or file reading is not allowed .. it goes same for flutter
hope you have your answer
I created a package specifically for this before Flutter web was a thing. https://pub.dev/packages/async_resource
It looks at things as either a network resource (usually over HTTP), or a local resource such as a file, local storage, service worker cache, or shared preferences.
It isn't the easiest thing in the world but it works.
What about "dart:indexed_db library", You can store structured data, such as images, arrays, and maps using IndexedDB. "Window.localStorage" can only store strings.
dart:indexed_db
Window.localStorage
When it comes specifically to reading a file from disk on web, the easiest way is to use a PickedFile like so:
PickedFile localFile = PickedFile(filePath);
Uint8List bytes = await localFile.readAsBytes();

BlackBerry 10: Load GroupDataModel data into a JSON file?

I have a ListView in QML using a cpp GroupDataModel that is created from a .json file in the assets folder. Items from this ListView are removed and added to. In cpp how do I get the GroupDataModel data into the JSON file?
I know there is this:
JsonDataAccess jda;
jda.save(huh?, "/app/native/assets/employees.json");
How do I get the GroupDataModel data into a QVariant to put in the first parameter of that function? I can't just stick my m_model GroupDataModel in there; it causes an error.
You have to iterate over your model with GroupDataModel::data() and GroupDataModel::childCount() to create your resulting QVariant, then store it. As far as I know, there's no automatic way to do this.
Edit: there is one.
for loading groupdatamodel content in to json file, you have to do:
QList<QVariantMap> myList = m_model->toListOfMaps();
QVariantList membersList;
foreach(QVariantMap s, myList){
membersList << s;
}
JsonDataAccess jda;
jda.save(membersList,path);