DavBfr / dart_pdf

Pdf creation module for dart/flutter
https://pub.dev/packages/pdf
Apache License 2.0
1.42k stars 632 forks source link

Doesn't work after deploying to firebase. Works of mobile chrome but not on windows browser #1765

Open jeedy20 opened 4 weeks ago

jeedy20 commented 4 weeks ago

`// ignore_for_file: avoid_print

import 'dart:async'; import 'package:admin/constance.dart'; import 'package:admin/models/currency_formatter.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:pdf/pdf.dart'; import 'package:pdf/widgets.dart' as pw; import 'package:printing/printing.dart'; import '../models/order_model.dart';

class PdfGeneratorOrderReceipt extends StatefulWidget { final OrderModel2 orderModel2; final String fullName; const PdfGeneratorOrderReceipt({ super.key, required this.orderModel2, required this.fullName, });

@override State createState() => _PdfGeneratorOrderReceiptState(); }

class _PdfGeneratorOrderReceiptState extends State {

@override initState() { super.initState(); getCurrencyDetails(); getPhoneDetails(); getAddressDetails(); getBusinessDetails(); getEmailDetails(); // fetchOrders(); }

String userID = ''; String getcurrencySymbol = ''; String businessName = ''; String email = ''; String address = ''; String phone = '';

getCurrencyDetails() { FirebaseFirestore.instance .collection('Currency Settings') .doc('Currency Settings') .get() .then((value) { setState(() { getcurrencySymbol = value['Currency symbol']; }); }); }

getPhoneDetails() { FirebaseFirestore.instance .collection('Business Details') .doc('phone') .snapshots() .listen((value) { if (mounted) { setState(() { phone = value['phone']; }); } }); }

getEmailDetails() { FirebaseFirestore.instance .collection('Business Details') .doc('email') .snapshots() .listen((value) { if (mounted) { setState(() { email = value['email']; }); } }); }

getBusinessDetails() { FirebaseFirestore.instance .collection('Business Details') .doc('business name') .snapshots() .listen((value) { if (mounted) { setState(() { businessName = value['business name']; }); } }); }

getAddressDetails() { FirebaseFirestore.instance .collection('Business Details') .doc('address') .snapshots() .listen((value) { if (mounted) { setState(() { address = value['address']; }); } }); }

@override Widget build(BuildContext context) { print('Orders are $getcurrencySymbol'); return Scaffold( appBar: AppBar( backgroundColor: Colors.white, elevation: 0, automaticallyImplyLeading: false, actions: [ Padding( padding: const EdgeInsets.all(8.0), child: IconButton( color: Colors.black, onPressed: () { Navigator.pop(context); }, icon: const Icon(Icons.close)), ) ], ), body: businessName.isEmpty ? const Center(child: CircularProgressIndicator()) : PdfPreview( build: (format) => _generatePdf( format, 'Order Receipt', widget.orderModel2, context, getcurrencySymbol, widget.fullName, businessName, email, address, phone), ), ); }

Future _generatePdf( PdfPageFormat format, String title, OrderModel2 users, BuildContext context, String currencySymbol, String fullname, String business, String email, String address, String phone, ) async { final pdf = pw.Document(version: PdfVersion.pdf_1_5, compress: true); // Load the image from assets final image = await imageFromAssetBundle(logo);

pdf.addPage(
  pw.MultiPage(
    pageFormat: format,
    build: (context) {
      return [
        pw.Container(
          padding: const pw.EdgeInsets.all(10),
          decoration: pw.BoxDecoration(
            color: PdfColors.grey300, // Grey background color
            borderRadius: pw.BorderRadius.circular(4),
          ),
          child: pw.Row(
            mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
            crossAxisAlignment: pw.CrossAxisAlignment.start,
            children: [
              // Company Logo Placeholder
              pw.Image(image, height: 100, width: 120),
              // Company Details
              pw.Column(
                crossAxisAlignment: pw.CrossAxisAlignment.end,
                children: [
                  pw.Text(business,
                      style: pw.TextStyle(
                          fontSize: 14, fontWeight: pw.FontWeight.bold)),
                  pw.Text(address),
                  pw.Text('Email: $email'),
                  pw.Text('Phone: $phone'),
                ],
              ),
            ],
          ),
        ),
        pw.SizedBox(height: 10),
        // pw.Divider(),
        pw.SizedBox(height: 10),
        pw.Center(
          child: pw.Text(
            title,
            style: pw.TextStyle(
              fontSize: 20,
              fontWeight: pw.FontWeight.bold,
            ),
          ),
        ),
        pw.SizedBox(height: 20),

        // Header Section
        pw.Row(
          mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
          children: [
            pw.Text('Order ID: ${users.orderID}',
                style: pw.TextStyle(fontWeight: pw.FontWeight.bold)),
            pw.Text(
              'Date: ${users.timeCreated.toLocal()}',
              style: pw.TextStyle(fontWeight: pw.FontWeight.bold),
            ),
          ],
        ),
        pw.Divider(),

        // Customer Details Section
        pw.Text("Customer's Name: $fullname",
            style: const pw.TextStyle(fontSize: 12)),
        pw.SizedBox(height: 5),
        if (users.deliveryAddress.isEmpty)
          pw.Text("Pickup: ${users.pickupAddress}",
              style: const pw.TextStyle(fontSize: 12)),
        if (users.deliveryAddress.isNotEmpty)
          pw.Text("Delivery Address: ${users.deliveryAddress}",
              style: const pw.TextStyle(fontSize: 12)),
        pw.SizedBox(height: 5),

        pw.Divider(),

        // Table Header
        pw.TableHelper.fromTextArray(
          headers: [
            'No.',
            'Product',
            'Selected Product',
            'Quantity',
            'Price'
          ],
          headerStyle: pw.TextStyle(
            color: PdfColors.white,
            fontWeight: pw.FontWeight.bold,
          ),
          headerDecoration: const pw.BoxDecoration(
            color: PdfColors.grey800,
          ),
          // Table Data
          data: List<List<dynamic>>.generate(users.orders.length, (index) {
            OrdersList userModel = users.orders[index];
            return <dynamic>[
              1 + index,
              userModel.productName,
              userModel.selected,
              CurrencyFormatter().converter(userModel.quantity.toDouble()),
              '$currencySymbol${CurrencyFormatter().converter(userModel.selectedPrice.toDouble())}',
            ];
          }),
          cellStyle: const pw.TextStyle(fontSize: 10),
          cellAlignment: pw.Alignment.centerLeft,
          cellAlignments: {
            0: pw.Alignment.centerLeft,
            1: pw.Alignment.centerLeft,
            2: pw.Alignment.centerLeft,
            3: pw.Alignment.center,
            4: pw.Alignment.centerRight,
          },
          rowDecoration: const pw.BoxDecoration(
            border: pw.Border(
              bottom: pw.BorderSide(
                color: PdfColors.grey300,
                width: .5,
              ),
            ),
          ),
        ),

        // pw.Divider(),
        pw.SizedBox(height: 40),
        // Footer Section
        pw.Row(
          mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
          children: [
            pw.Text('Payment Type: ${users.paymentType}',
                style: const pw.TextStyle(fontSize: 12)),
            pw.Text(
                'Total: $currencySymbol${CurrencyFormatter().converter(users.total.toDouble())}',
                style: pw.TextStyle(
                    fontWeight: pw.FontWeight.bold, fontSize: 14)),
          ],
        ),

        pw.SizedBox(height: 40),

        // Signature Field
        // pw.Divider(),
        pw.SizedBox(height: 40),
        pw.Text('Signature: ____________________________',
            style: const pw.TextStyle(fontSize: 12)),
        pw.SizedBox(height: 5),
        pw.Text('(Customer Signature)',
            style:
                pw.TextStyle(fontSize: 10, fontStyle: pw.FontStyle.italic)),
      ];
    },
  ),
);

return pdf.save();

} } `