skip to Main Content

I am using pdf package to generate pdf. I was able to share the pdf but I don’t know, how to save the pdf in the local storage.

Future<void> sharePdf() async {
final pdf = pw.Document();

pdf.addPage(
  pw.Page(
      build: (pw.Context context) {
        return pw.Container(
          child: pw.Column(
              children: [
                pw.Text('Example', style: pw.TextStyle(fontWeight: pw.FontWeight.bold, fontSize: 20)),
               
              ]
          ),
        );
      }
  ),
);


final directory = await getExternalStorageDirectory();
final file = File("${directory?.path}/example.pdf");

final pdfBytes = await pdf.save();
await file.writeAsBytes(pdfBytes.toList());



await Share.shareFiles([(file.path)]);}

This is my code to share the pdf. I like to know how to save the pdf in the local storage.

3

Answers


  1. Chosen as BEST ANSWER

    With the help of other answers and document_file_save_plus package, I was able to save the pdf in local storage. This is the code

    Future<void> saveFile() async {
    final pdf = pw.Document();
    
    pdf.addPage(
      pw.Page(
          build: (pw.Context context) {
            return pw.Container(
              child: pw.Column(
                  children: [
                    pw.Text('Example', style: pw.TextStyle(fontWeight: pw.FontWeight.bold, fontSize: 20)),
                  ]
              ),
            );
          }
      ),
    );
    
    
    final directory = await getExternalStorageDirectory();
    final file = File("${directory?.path}/example.pdf");
    
    
    final pdfBytes = await pdf.save();
    await file.writeAsBytes(pdfBytes.toList());
    
    
    
    DocumentFileSavePlus().saveMultipleFiles(
      dataList: [pdfBytes,],
      fileNameList: ["example.pdf",],
      mimeTypeList: ["example/pdf",],
    );}    
    

  2. use this package doc_file_save

    setp 1 :
    add permission

    android ->

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    ios ->

    No permission needed. < as package documentation >

    final file = File("${directory?.path}/example.pdf");
    

    setp 2 : convert the file to Uint8List

    Uint8List data = await file.readAsBytesSync();
    

    setp 3: call this Function :

    Then pass the Uint8List like this

    void saveFile(Uint8List data, "my_sample_file.pdf", "appliation/pdf")
    
    Login or Signup to reply.
  3. I am sharing details process download file from url to save in local storage step by step if you already implemented Download just follow the savepdf File only.

    call download function & pass url to the specific method

      @override
      Widget build(BuildContext context) {
        return InkWell(
                onTap: () => downloadPDFrmUrl(downloadurl),
                child: SizedBox(
                  height: 36,
                  width: 100,
                  child: Text('download Button'),
                ),
          
            
                      );
      }
    
      void downloadPDFrmUrl(String? _downloadUrl) async {
    await downloadPdfWithHttp(
        context: context, url: _downloadUrl!);
    

    }

    First download Pdf from http url

      static Future<void> downloadPdfWithHttp({required BuildContext context,
        required String url}) async {
        // print('download file url ==$url');
    
        File? _file;
        final String _fileName = 'demofilename.pdf';
        final permission = await Permission.storage
            .request()
            .isGranted;
        // print('download exam url ==$r');
    
        if (!permission) {
          return;
        } else {
          // print('download file storage permission ==$r');
        }
        // Either the permission was already granted before or the user just granted it.
    
        final path = await getDownloadPath();
        //  print('download exam permission ==$path');
    
        if (path == null) {
          return;
        }
    
    
        try {
    
          // create file name, if exist file then add a incremental value to file name
          _file = File('$path/$_fileName');
          int count = 0;
          while (_file?.existsSync() ?? false) {
            count++;
            // String newFilename = basenameWithoutExtension(fileName)+"($count)."+extension(fileName);
            String newFilename =
                "${basenameWithoutExtension(_fileName)}($count)${extension(
                _fileName)}";
            _file = File('$path/$newFilename');
          }
    
          var sink = _file?.openWrite();
    
    
          if (sink != null) {
            await sink.close();
          }
    
        } catch (ex) {
        }
    
      }
    

    Save download file in stoarge by below function

     static Future<String?> getDownloadPath() async {
        String? externalStorageDirPath;
        if (Platform.isAndroid) {
          try {
            externalStorageDirPath = await AndroidPathProvider.downloadsPath;
            // externalStorageDirPath = "/storage/emulated/0/Download";
    
          } catch (e) {
            //  print('permisison error == $e');
            final directory = await getExternalStorageDirectory();
            externalStorageDirPath = directory?.path;
            // print('stoarge path == $externalStorageDirPath');
          }
        } else if (Platform.isIOS) {
          externalStorageDirPath = (await getApplicationDocumentsDirectory()).path;
        }
        return externalStorageDirPath;
      }
    

    Add read / write permissions in your android/app/src/main/AndroidManifest.xml before tag.

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    

    If you are still get the Permission Denied error, add the following line on AndroidManifest.xml file.

    <application
          android:requestLegacyExternalStorage="true"
    >  
    

    Don’t forget to add libray android pathprovider in pubspec.yaml

        android_path_provider: ^0.3.0
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search