简体   繁体   English

从 flutter 中的 Firebase Firestore 集合创建一个 PDF 文件

[英]Create a PDF file from Firebase Firestore collection in flutter

I have various collections in Firestore,I want to create a button which saves the data fetched from specific collection into a PDF file.我在 Firestore 中有各种 collections,我想创建一个按钮,将从特定集合中获取的数据保存到 PDF 文件中。 I don't know how to use PDF package for saving the data fetched via query into a PDF file.我不知道如何使用PDF package 将通过查询获取的数据保存到 PDF 文件中。

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.我有一个演示代码,它从 Firestore 集合中获取数据并将其显示在列表视图中,现在我想在那里创建一个按钮,允许用户将获取的数据下载到 PDF 并将该 PDF 保存到设备。

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.现在我希望将此数据保存在 PDF 中,但不知道如何实现。 Please suggest how it can be done?请建议如何完成?

You need to use the packages widgets to build generate the pdf您需要使用包小部件来构建生成 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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM