Home > Back-end >  Flutter base64 pdf view and download
Flutter base64 pdf view and download

Time:02-24

Here comes the pdf converted to base64 from an API. I cannot view and download from within the application. I would be glad if you help. Thanks in advance.

CodePudding user response:

First you need to add "path_provider" and "open_file"

dependencies:
  path_provider: ^2.0.9
  open_file: ^3.2.1

Then create new class

 class FileProcess {
  static bool isFolderCreated = false;
  static Directory? directory;

  static checkDocumentFolder() async {
    try {
      if (!isFolderCreated) {
        directory = await getApplicationDocumentsDirectory();
        await directory!.exists().then((value) {
          if (value) directory!.create();
          isFolderCreated = true;
        });
      }
    } catch (e) {
      print(e.toString());
    }
  }

  static Future<File> downloadFile() async {
    final base64str = "put your base64 value";
    Uint8List bytes = base64.decode(base64str);
    await checkDocumentFolder();
    String dir =
        directory!.path   "/"   "your file name"   ".pdf";
    File file = new File(dir);
    if (!file.existsSync()) file.create();
    await file.writeAsBytes(bytes);
    return file;
  }
}

After you create the class you can use it for download your pdf.

For open the file add this lines into your class

static void openFile(String fileName) {
        String dir =
            directory!.path   "/${fileName}.pdf";
        OpenFile.open(dir));
      }

After all you can use like

await FileProcess.downloadFile()

and

FileProcess.openFile(fileName)

These codes should be working.

  • Related