I have various collections in Firestore,I want to create a button which saves the data fetched from specific collection into a PDF file. I don't know how to use PDF package for saving the data fetched via query into a PDF file.
I have a demo code which fetch data from Firestore collection and show it in list view, now I want to create a button over there which will allow the user to download that fetched data into a PDF and save that PDF to device.
below is the code which shows list view of data fetched from that collection
Container buildUserPosts() {
Future<List<NewsPost>> getPosts() async {
List<NewsPost> posts = [];
var snap = await FirebaseFirestore.instance
.collection('News')
.orderBy("timestamp")
.get();
for (var doc in snap.docs) {
posts.add(NewsPost.fromDocument(doc));
}
return posts.reversed.toList();
}
return Container(
child: FutureBuilder<List<NewsPost>>(
future: getPosts(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Container(
alignment: FractionalOffset.center,
padding: const EdgeInsets.only(top: 10.0),
child: CircularProgressIndicator());
} else {
return Column(
children: snapshot.data!.map((NewsPost imagePost) {
return imagePost;
}).toList());
}
},
));
Now I want this data to be saved in a PDF but unable to figure how to achieve it. Please suggest how it can be done?
You need to use the packages widgets to build generate the pdf
import 'dart:io';
import 'package:pdf/widgets.dart' as pw;
Future<void> generatePdf(MyData? mydata) async {
final pdf = pw.Document();
// build your pdf view here
pdf.addPage(
pw.Page(
build: (pw.Context context) => pw.Center(
child: pw.Text(mydata?.title ??''),
),
),
);
//save pdf
final file = File('example.pdf');
await file.writeAsBytes(await pdf.save());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.