Umaiz Khan
Umaiz Khan

Reputation: 1227

Flutter pdf file isnt saving and showing error

I am trying to simple generate and save pdf issue is its showing error in my code

I am doing like this

  import 'package:path_provider/path_provider.dart';
  import 'package:pdf/pdf.dart';
  import 'package:pdf/widgets.dart' as pw;

  onTap: () async{
    final pdf = pw.Document();

    pdf.addPage(
      pw.Page(
        build: (pw.Context context) => pw.Center(
          child: pw.Text('Hello World!'),
        ),
      ),
    );
    // Share.shareFiles([pdf], text: 'Reports');

    final output = await getTemporaryDirectory();
    final path = "${output.path}/temp.pdf";
    final file = File(path); // here its showing error 2 positional 
    await file.writeAsBytes(pdf.save()); // here its showing The method 'writeAsBytes' isn't defined for the type 'File'.

  },

Plugin versions

pdf: 2.1.0 & path_provider: ^2.0.2

I search every where but I didnt find any solution cant find it so why I am getting this error -_-

Upvotes: 1

Views: 1976

Answers (1)

Krish Bhanushali
Krish Bhanushali

Reputation: 2007

Use io library to write the file:

    import 'dart:io' as io;
    
    onTap: () async{
    final pdf = pw.Document();

    pdf.addPage(
      pw.Page(
        build: (pw.Context context) => pw.Center(
          child: pw.Text('Hello World!'),
        ),
      ),
    );
    // Share.shareFiles([pdf], text: 'Reports');

    //replace your code to save file from bellow
    final output = await getTemporaryDirectory();
    final path = "${output.path}/temp.pdf";
    final file = await io.File(path).writeAsBytes(pdf.save());


  },

The error would be due to methods defined in the pdf library. You can use default io library to solve that.

Upvotes: 1

Related Questions