Home > Blockchain >  Flutter Firestore Collection to PDF
Flutter Firestore Collection to PDF

Time:04-29

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'];
        });
      });
    });
  }

CodePudding user response:

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');
  • Related