How to convert a whole flutter Screen to pdf? - flutter

I have a flutter E-commerce App which has a orderDetails page , I want to convert the whole page to pdf using flutter pdf package, as it would be more convinent because the data is retrived from FirebaseFirestore. Is there a way around I can achieve this ?
sub: I want to convert the whole flutter screen to pdf using this library

You can capture the screen using this package screenshot
then add that image to pdf document and save it
import 'dart:io';
import 'dart:typed_data';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart ' as pw;
Future getPdf(Uint8List screenShot) async {
pw.Document pdf = pw.Document();
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
build: (context) {
return pw.Expanded(
child: pw.Image(PdfImage.file(pdf.document, bytes: screenShot), fit: pw.BoxFit.contain)
);
},
),
);
File pdfFile = File('Your path + File name');
pdfFile.writeAsBytesSync(pdf.save());
}

full details:
load dependencies in pubspec.yaml:
screenshot:
share_plus:
path_provider:
permission_handler:
import packages in your dart file:
import 'package:screenshot/screenshot.dart';
import 'package:share_plus/share_plus.dart';
import 'package:permission_handler/permission_handler.dart';
shareImage() async {
final uint8List = await screenshotController.capture();
String tempPath = (await getTemporaryDirectory()).path;
String fileName ="myFile";
if (await Permission.storage.request().isGranted) {
File file = await File('$tempPath/$fileName.png').create();
file.writeAsBytesSync(uint8List);
await Share.shareFiles([file.path]);
}
}
and call shareImage() on any place:
GestureDetector(
onTap: (){ shareImage();},
child: ........,
),
remember to wrap your desire widget in:
Screenshot(
controller: screenshotController,
child: Text("This text will be captured as image"),
),

newest solution will be
shareImage() async {
final uint8List = await screenshotController.capture();
String tempPath = (await getTemporaryDirectory()).path;
String fileName =" ";>>>>>your file name between ""
File file = await File('$tempPath/$fileName" }.png').create();
file.writeAsBytesSync(uint8List!);
await Share.shareFiles([file.path]);
}

import 'dart:io';
import 'dart:typed_data';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart ' as pw;
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
Future screenToPdf(String fileName,Uint8List screenShot) async {
pw.Document pdf = pw.Document();
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
build: (context) {
return pw.Expanded(
child: pw.Image(pw.MemoryImage(screenShot), fit: pw.BoxFit.contain),
);
},
),
);
String path = (await getTemporaryDirectory()).path;
File pdfFile = await File('$path/$fileName.pdf').create();
pdfFile.writeAsBytesSync(await pdf.save());
await Share.shareFiles([pdfFile.path]);
}

Related

Flutter Firestore Collection to PDF

I'm making a travel app about Crete where people can look up the most important things to see. They can also add documents to their own trips, which is a collection on firestore "Selected".
I want people to be able to generate a pdf from their selected items, to save on their Android/Iphone.
I have a seperate class for generating the pdf..
But how do I pass snapshot.data() to the other class?
onTap: () async {
getSelectedItems();
final pdfFile = await PdfApi.generateCenteredText(data);
PdfApi.openFile(pdfFile);
},
getSelectedItems(){
mySelectedTrips.get().then((querySnapshot) {
querySnapshot.docs.forEach((snapshot) {
setState(() {
data = snapshot.data();
uid = snapshot['uid'];
description = snapshot['description'];
image = snapshot['image'];
});
});
});
}
Hi here is a short example how to create a pdf with one page.
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart';
class PdfCreator {
void createPdf(Snapshot snapshot) async {
final Document pdf = Document();
final page = Page(
pageFormat: PdfPageFormat.a4,
build: (Context context) {
return Column(
children: [
Text(snapshot.snapshot['description']),
Text(snapshot.snapshot['uid'].toString()),
Image(MemoryImage(snapshot['image'])),
],
);
},
);
pdf.addPage(page);
// Save file
final output = await getTemporaryDirectory();
var path = "${output.path}/test.pdf";
final file = File(path);
await file.writeAsBytes(await pdf.save());
}
}
You can enhance it and create one page per element in your foreach loop and and it to the pdf and so on.
Hint: if you want to use flutter widgets and pdf widgets in one file you can import pdf as p for example:
import 'package:pdf/widgets.dart' as p;
...
final flutterWidget = Text('abc');
final pdfWidget = p.Text('def');

error The argument type 'PdfImage' can't be assigned to the parameter type 'ImageProvider'

I am trying to make pdf from screenshot with screenshot and pdf plugins in flutter.
When I pass Uint8List to pdf creation function I am getting error at PdfImage.file(pdf.document, bytes: screenShot The argument type 'PdfImage' can't be assigned to the parameter type 'ImageProvider' The code to convert to pdf is
Future getPdf(Uint8List screenShot) async {
pw.Document pdf = pw.Document();
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
build: (context) {
return pw.Expanded(
child: pw.Image(PdfImage.file(pdf.document, bytes: screenShot), fit: pw.BoxFit.contain)
);
},
),
);
File pdfFile = File('Your path + File name');
pdfFile.writeAsBytesSync(await pdf.save());
}
and passing the screenshot to the pdf function is below
Uint8List _imageFile;
screenshotController.capture().then((Uint8List image) {
//Capture Done
setState(() {
_imageFile = image;
});
}).catchError((onError) {
print(onError);
});
getPdf(_imageFile);
},
Can anyone help me with this?
Try this way:
Future getPdf(Uint8List screenShot) async {
pw.Document pdf = pw.Document();
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
build: (context) {
return pw.Expanded(
// change this line to this:
child: pw.Image(pw.MemoryImage(screenshot), fit: pw.BoxFit.contain),
);
},
),
);
File pdfFile = File('Your path + File name');
pdfFile.writeAsBytesSync(await pdf.save());
}

Share and Print Screen Flutter

import 'dart:io';
import 'dart:typed_data';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:esys_flutter_share/esys_flutter_share.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
Imports...
screenshot: ^0.2.0
esys_flutter_share: ^1.0.2
I only need to take a capture, and then share it I am using the following code but I receive the error:
_takeScreenshotandShare() async {
_imageFile = null;
screenshotController
.capture(delay: Duration(milliseconds: 10), pixelRatio: 2.0)
.then((File image) async {
setState(() {
_imageFile = image;
});
final directory = (await getApplicationDocumentsDirectory()).path;
Uint8List pngBytes = _imageFile.readAsBytesSync();
File imgFile = new File('$directory/screenshot.png');
imgFile.writeAsBytes(pngBytes);
print("File Saved to Gallery");
await Share.file('Anupam', 'screenshot.png', pngBytes, 'image/png');
}).catchError((onError) {
print(onError);
});
}
My mistake is:
I/flutter ( 2486): NoSuchMethodError: The method 'findRenderObject' was called on null.
I/flutter ( 2486): Receiver: null
I/flutter ( 2486): Tried calling: findRenderObject()
I face the same issue with screenshot package so my workaround is call same function again incase of error occur.
screenshotController.capture().then((File image) async {
Uint8List pngBytes = image.readAsBytesSync();
final directory = (await getApplicationDocumentsDirectory()).path;
File imgFile = new File('$directory/${DateTime.now().millisecondsSinceEpoch}.png');
await imgFile.writeAsBytes(pngBytes);
if(pngBytes.length == 0)
// call Same function again
else
// your image
}).catchError((onError) {
print(onError);
Future.delayed(Duration(seconds: 1)).then((value) => //call Same function again);
});

how to create pdf from image dart command line using dart package pdf

Following code generates empty pdf, can you please point out the error
I am using dart pdf package https://pub.dev/packages/pdf. pdf is getting generated but content is empty.
adding tag flutter, if someone has used same package in flutter and may know answer.
import 'dart:io';
import 'package:pdf/pdf.dart';
main() {
try {
createPdf();
} catch (e) {
print(e);
}
}
void createPdf() async {
PdfDocument pdf = PdfDocument();
PdfPage page = PdfPage(pdf);
PdfImage image =
PdfImage.file(pdf, bytes: File('./test.jpg').readAsBytesSync());
final g = page.getGraphics();
g.drawImage(image, image.height.toDouble(), image.width.toDouble());
final file = File("./test.pdf");
await file.writeAsBytes(pdf.save());
}
You should use the widgets library:
import 'dart:io';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart';
void main() {
try {
createPdf();
} catch (e) {
print(e);
}
}
void createPdf() async {
final doc = Document();
final image = PdfImage.file(doc.document, bytes: File('./test.jpg').readAsBytesSync());
doc.addPage(
Page(
build: (context) => Center(child: Image(image)),
),
);
final file = File("./test.pdf");
await file.writeAsBytes(doc.save());
}

Flutter web Need a sample on how to pass and show image in generated PDF using PDF package

I am trying to generate PDF in Flutter web using https://pub.dev/packages/pdf package.
Everything is fine, except images, they won't work.
I tried several ways, but without success.
So my question is - how to pass and show image in PDF in Flutter web?
1 way throws chrome exception
Error: RangeError (index): Index out of range: index should be less than 876: 876
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/widgets.dart' as w;
import 'package:inspections/models/inspection.dart';
import 'package:intl/intl.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' ;
Future<Document> generateDocument(
PdfPageFormat format, Uint8List logo) async {
final Document doc = Document(
title: 'name',
author: 'author',
);
PdfImage sample = PdfImage(doc.document, image: logo, width: 100, height: 100, alpha: true);
....
2 way
does not return anything:
import 'package:flutter/widgets.dart' as w;
ByteData byteData = await rootBundle.load('assets/image.png');
var k = byteData.buffer.asUint8List();
var temp = await pdfImageFromImageProvider(
pdf: doc.document,
image: w.MemoryImage(k));
This one works for me in Flutter web:
ByteData imageData;
rootBundle
.load('assets/XYZ.jpg')
.then((data) => setState(() => this.imageData = data));
...
final image = PdfImage.jpeg(
pdf.document,
image: imageData.buffer.asUint8List()
);
...
pw.Image(image)