如何在flutter中将pdf保存到本地存储中?

问题描述 投票:0回答:3

我正在使用pdf包来生成pdf。我能够共享 pdf,但我不知道如何将 pdf 保存在本地存储中。

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

这是我分享pdf的代码。我想知道如何将pdf保存到本地存储中。

flutter pdf local-storage
3个回答
2
投票

使用这个包doc_file_save

设置1: 添加权限

安卓->

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

ios->

无需许可。 < as package documentation >

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

setp 2 : 将文件转换为 Uint8List

Uint8List data = await file.readAsBytesSync();

setp 3:调用此函数:

然后像这样传递Uint8List

void saveFile(Uint8List data, "my_sample_file.pdf", "appliation/pdf")

0
投票

在其他答案和 document_file_save_plus 包的帮助下,我能够将 pdf 保存在本地存储中。这是代码

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

0
投票

我正在分享从

url
下载文件的详细过程,以便逐步保存在本地存储中,如果您已经实现了下载,只需按照
savepdf
仅文件操作即可。

调用下载函数并将url传递给特定方法

  @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!);
}

首先从http url下载Pdf

  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) {
    }

  }

通过以下功能将下载文件保存在storage中

 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;
  }

<application>标签之前的

android/app/src/main/AndroidManifest.xml
中添加读/写权限。

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

如果仍然出现 Permission Denied 错误,请在 AndroidManifest.xml 文件中添加以下行。

<application android:requestLegacyExternalStorage="true" >  

不要忘记在

pubspec.yaml 中添加 libray android 
pathprovider

    android_path_provider: ^0.3.0
© www.soinside.com 2019 - 2024. All rights reserved.