How to add network image in pdf in flutter? - flutter

Hello guys, I was trying to add network image in the pdf. The pdf is
created using printing: ^5.5.0 plugin . I am getting run time
error. Please help out, Thanks in advance.
previewpage.dart
final pdf = pw.Document();
MemoryImage images = [];
Future _getImage() async {
for (var i = 0; i < 2; i++) {
var response = await http
.get(Uri.parse("image url here"));
final image =
pw.RawImage(bytes: response.bodyBytes, width: 50, height: 100);
images.add(image);
}
_writeOnPdf();
}

using printing: ^5.5.0
try {
final provider = await flutterImageProvider(NetworkImage(
"https://miro.medium.com/max/1000/1*ilC2Aqp5sZd1wi0CopD1Hw.png"));
images.add(provider);
} catch (e) {
print("****ERROR: $e****");
return;
}
pw.Center(
child: pw.Padding(
padding: const pw.EdgeInsets.all(3),
child: pw.Image(
images[i],
width: 50,
height: 100,
),
),
)

Related

Save and print generated barcode as image

I am using the barcode_widget to generate both barcode and 2d QR code. But I also need to print and save the codes.
My Current code for generating bar code and qr code is as below:
Center(
child: BarcodeWidget(
data: widget.product.productId!,
barcode: Barcode.code128(),
width: 200,
height: 200,
drawText: false,
),
),
and
BarcodeWidget(
data: widget.product.productId!,
barcode: Barcode.qrCode(),
),
Both are inside a Column and I have two buttons called save and print. So how can I save and print the generated codes?
You can use RepaintBoundary
Follow these steps:
1. Create a key.
GlobalKey _screenShotKey = GlobalKey();
2. Wrap the barcode in a repaint boundary and attach the key
RepaintBoundary(
key: _screenShotKey,
child: Center(
child: BarcodeWidget(
data: widget.product.productId!,
barcode: Barcode.code128(),
width: 200,
height: 200,
drawText: false,
),
)
)
3. Import dart:ui as ui
import 'dart:ui' as ui;
4. Create a method to take a screenshot of the widget and save it.
Future<File> takeScreenshot() async {
RenderRepaintBoundary boundary =
_screenShotKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage();
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
final tempPath = (await getTemporaryDirectory()).path;
final path = tempPath + "qr.png";
File imgFile = File(path);
return imgFile.writeAsBytes(pngBytes);
}
5. To save in gallery/photos app; Use GallerySaver package
void save() async {
takeScreenshot().then((value) async {
bool saved = await GallerySaver.saveImage(value.path);
print(saved);
}).catchError((onError) {});
}

Unable to load pdf from url using Syncfusion_flutter_pdf

I am working on an application that requires me to load pdf from url. The plugin I am using is syncfusion_flutter_pdf. I couldn't find a direct way to do the same so I tried downloading the file first and then use it. But the pdf is not displaying for some reason! There were nothing in the logs. Can you guys please tell me what went wrong?
fileDownload() async {
tempDir = await getApplicationDocumentsDirectory();
tempPath = tempDir.path + 'flutter-succinctly.pdf';
final dio = Dio();
if (await File(tempPath).exists()) {
//print('tempPath exists at: $tempPath');
if (await File(tempPath).length() == 0) {
dio.download(
'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
tempPath,
);
} else {
_readPDF();
}
} else {
print('path does not exist');
dio.download(
'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
tempPath);
}
}
Future<void> _readPDF() async {
final PdfDocument document =
PdfDocument(inputBytes: File(tempPath).readAsBytesSync());
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextButton(
child: const Text('Generate PDF'),
style: TextButton.styleFrom(
primary: Colors.white,
backgroundColor: Colors.lightBlue,
onSurface: Colors.grey,
),
onPressed: fileDownload,
)
],
),
));
}
We do not have direct support to load PDF from URL. We can load and read PDF data by using http package. We have created a sample to read the PDF data from webspace/website to load and save it using the retrieved PDF data. Kindly try the following code example and sample in your side,
Add http package in dependencies section of pubspec.yaml file
dependencies:
http: ^0.13.3
Import the following package in your dart file.
//Read an PDF data from website/webspace
import 'package:http/http.dart' show get;
Get image data
//Read an PDF data from website/webspace
var url = "https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf";
var response = await get(Uri.parse(url));
var data = response.bodyBytes;
Load data into PDF document
//Create a new PDF document
PdfDocument document = PdfDocument(inputBytes: data);
//Save PDF document
final List bytes = document.save();
//Dispose the document.
document.dispose();
Please find the sample from https://www.syncfusion.com/downloads/support/directtrac/general/ze/pdf_sample565926150.

Getting a "File$" instead of a File in flutter

I am allowing users to grab a profile pic and upload that picture as file to my server, but I'm getting this error when inputting the image via ImagePickerWeb:
<error>:<getObject: Unexpected error from chrome devtools:>
I don't know if it's my browser or me, but this is what I'm trying:
Future<void> getMultipleImageInfos() async {
var imageFile =
await ImagePickerWeb.getImage(outputType: ImageType.file);
print(imageFile);
if (imageFile != null) {
setState(() {
currentSelfie = imageFile;
_accDetails['customer_selfie'] = currentSelfie;
});
}
}
Then displaying that photo here:
Image.file(
currentSelfie,
height: screenAwareSize(100, context),
width: screenAwareSize(100, context),
fit: BoxFit.fill,
)

How to use preference for showing profile picture in my application in flutter

I want to display a profile picture of the user when they log in. I am using the image URL stored in firestore database.
I want to keep the image in the app until logout. Every time I start the app, Image is called from that URL but I want to store it. I am new to flutter and have no clue to achieve this task.
Future<void> _getImage(ImageSource source) async {
var image = await ImagePicker.pickImage(source: source);
if (image != null) {
setState(() {
_cropImage(image);
});
}
Navigator.pop(context);
}
// Crop fetched image
_cropImage(File image) async {
File cropped = await ImageCropper.cropImage(
sourcePath: image.path,
aspectRatio: CropAspectRatio(ratioY: 1.0, ratioX: 1.0));
if (cropped != null) {
setState(() {
_imageFile = cropped;
uploadFile();
});
}
}
// Upload image file to firestrore Storage and get image URL
Future uploadFile() async {
StorageReference storageReference = FirebaseStorage.instance
.ref()
.child('${Path.basename(_imageFile.path)}}');
StorageUploadTask uploadTask = storageReference.putFile(_imageFile);
var downUrl = await (await uploadTask.onComplete).ref.getDownloadURL();
var url = downUrl.toString();
await uploadTask.onComplete;
setState(() {
imageUrl = url.toString();
});
// Show message on successful image upload
AppUtils.showToast('Picture Uploaded', green, white);
// Updating database with Image URL
Firestore.instance
.collection('account')
.document(widget.user)
.updateData({"url": imageUrl});
}
// Display Image
ClipRRect(
borderRadius: BorderRadius.circular(200.0),
clipBehavior: Clip.hardEdge,
child: Container(
height: 200,
width: 200,
child: widget.photoUrl == null
? Image(
image: NetworkImage(
'https://cdn1.iconfinder.com/data/icons/technology-devices-2/100/Profile-512.png'),
fit: BoxFit.fill,
)
: Image(
image: NetworkImage(widget.photoUrl),
fit: BoxFit.fill,
))),
What you need is a proper State Management throughout your app.
You can check the Provider Package to get started.
You can find more information about State Management here and here

Flutter error while showing profile picture google play games

Using the play_games extension, I'm having trouble returning the user's profile image.
Use the method below to login and set the state with the return of the user's data.
Image provider: NetworkImage ("content: //com.google.android.gms.games.background/images/f56551ac/42", scale: 1.0)
// Google Play Games stance
final GameServices gameservices = GameServices();
Account profile;
ui.Image profileimage;
void _login() async {
final res = await gameservices.login();
final resimage = await res.hiResImage;
setState(() {
profile = res;
profileimage = resimage;
});
print(profileimage);
}
In the widget I'm in the form of NetworkImage, but it's still not rendering on the screen.
this error: The argument type 'Image' can't be assigned to the parameter type 'String'.
Container(
width: 128,
height: 128,
padding: EdgeInsets.all(8),
child: CircleAvatar(
backgroundImage: NetworkImage(this.profileimage != null ? this.profileimage : 'https://api.adorable.io/avatars/128/')
),
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle
),
),
[ RESOLVED!!! ]
Change my code and play_games returns type vars.
Lets go:
Future<Uint8List> get hiResImage async =>
await _fetchToMemory(await _channel.invokeMethod('getHiResImage'));
Future<Uint8List> get iconImage async =>
await _fetchToMemory(await _channel.invokeMethod('getIconImage'));
}
Future<Uint8List> _fetchToMemory(Map<dynamic, dynamic> result) {
Uint8List bytes = result['bytes'];
if (bytes == null) {
print('was null, mate');
return Future.value(null);
}
// Completer<Image> completer = new Completer();
// decodeImageFromList(bytes, (image) => completer.complete(image));
return Future.value(bytes);
}
And my code, only this change:
Uint8List profileimage;
Flutter is yelling at you because you gave it a URL with protocol content://, when it expects http:// or https:// for a NetworkImage widget. See documentation at: https://flutter.dev/docs/cookbook/images/network-image
This happen because google provide encoded image. In android we can use ImageManager for that as google suggest.
In flutter there are mechanism for getting Future<Image> from hiresImageUri. Check here.
Use Something like below,
profile.hiResImage.then((Image result){
//here you can get image in result
});