NilxSingh
NilxSingh

Reputation: 293

How to overwrite pdf file in flutter?

I am creating a pdf file like this write to method... using this package https://pub.dev/packages/pdf

writeOnPdf(context) async {
    final roboto = await rootBundle.load('assets/fonts/Roboto-Regular.ttf');
    var robotoF = pw.Font.ttf(roboto);
    final robotobold = await rootBundle.load('assets/fonts/Roboto-Bold.ttf');
    var robotoB = pw.Font.ttf(robotobold);
    pdf.addPage(pw.MultiPage(
      theme: pw.ThemeData.withFont(
        base: robotoF,
        bold: robotoB,
      ),
      pageFormat: PdfPageFormat.a4,
      margin: pw.EdgeInsets.fromLTRB(24, 24, 24, 24),
      // header: ,
      maxPages: 1,
      build: (pw.Context context) {
        return <pw.Widget>[
          pw.Column(
            children: [
              pw.Container(
                height: 40,
                color: PdfColors.grey200,
                padding: pw.EdgeInsets.fromLTRB(15, 0, 15, 0),
                child: pw.Row(
                  mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
                  children: [
                    pw.Expanded(
                      child: pw.Text(
                        'Description / Items',
                        style: pw.TextStyle(
                          font: robotoB,
                          // fontWeight: pw.FontWeight.bold,
                        ),
                      ),
                    ),
                    pw.Container(
                      width: 1,
                      height: 25,
                      color: PdfColors.black,
                      padding: pw.EdgeInsets.fromLTRB(10, 0, 10, 0),
                    ),
                    pw.Container(
                      width: 70,
                      child: pw.Center(
                        child: pw.Text(
                          'Qt. $quantity',
                          textAlign: pw.TextAlign.center,
                          style: pw.TextStyle(
                            font: robotoB,
                            // fontWeight: pw.FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                    pw.Container(
                      width: 1,
                      height: 25,
                      color: PdfColors.black,
                      padding: pw.EdgeInsets.fromLTRB(10, 0, 10, 0),
                    ),
                    pw.Container(
                      width: 120,
                      child: pw.Align(
                        alignment: pw.Alignment.centerRight,
                        child: pw.Text(
                          '$Amount',
                          textAlign: pw.TextAlign.right,
                          style: pw.TextStyle(
                            font: robotoB,
                            // fontWeight: pw.FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ];
      },
    ));
  }

Now I am saving the file with below function...

Future<File> savePDF() async {
    final appPath = Directory("storage/emulated/0/Myxyzapp/Invoices").path;
    pdfFile = File('$appPath/myxyzapp-invoice-$invoiceNo.pdf');
    await pdfFile.writeAsBytes(pdf.save());
    return pdfFile;
  }

    InkWell(
  onTap: () async {
    await writeOnPdf(context);
    await savePDF().then((value) {
      showDialog(
          context: (context),
          builder: (context) => AlertDialog(
                shape: ContinuousRectangleBorder(
                    borderRadius:
                        BorderRadius.circular(20)),
                content: Text(
                    'Invoice PDF regenerated successfully.'),
                actions: <Widget>[
                  FlatButton(
                    onPressed: () => Navigator.pop(
                        context, true),
                    child: Text(
                      "OK",
                      style:
                          TextStyle(fontSize: 14),
                    ),
                  ),
                ],
              ));
    });
  },
  child: Container(
    padding: EdgeInsets.fromLTRB(10, 7, 10, 7),
    decoration: BoxDecoration(
        color: Colors.grey[200],
        borderRadius: BorderRadius.circular(5)),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          'Re-generate PDF ',
          style: TextStyle(
            color: Colors.black54,
            fontSize: 14,
          ),
        ),
        Icon(
          Icons.insert_drive_file,
          color: Colors.black54,
          size: 18,
        ),
      ],
    ),
  ),
),

But when I re-generate this file and try to open it still shows previous data...

Note : All of my flutter code and writeToPdf() widget are on same page... basically I can't seperate them as I am fetching data from server and creatring dynamic PDF file.

I have tried :

  1. deleting old file via "pdfFile.delete();" and then saving file to path.

This works only when I manually delete file from folder and then again open app and generate my pdf...

Any suggestions or advise where I am doing mistake???

Upvotes: 2

Views: 1669

Answers (1)

Emanuele
Emanuele

Reputation: 192

You can simply check if file already exists and then delete it.

await File( YOURFILE ).exists();

or

File( YOURFILE ).existsSync();

If return true, then delete the file with :

await File( YOURFILE ).delete();

or

File( YOURFILE ).deleteSync();

At this point, you can create a new Pdf file with the same name and path.

NOTE With pdfFile.delete() your are not deleting the file already exists, but the file you have just created.

Upvotes: 2

Related Questions