从资产波动中打开pdf文件

时间:2020-06-10 03:57:20

标签: flutter dart pdf-viewer

我正在尝试使用flutter_fullpdfview 1.0.12打开PDF文件,我的PDF文件位于资产文件夹下,但不知何故我遇到无法找到文件的错误。我尝试了几种选择,但是它们都没有返回相同的错误。以下是我尝试加载文件的功能,但它们均因相同的错误而失败。

  Future<File> copyAsset() async {
      Directory tempDir = await getTemporaryDirectory();
      String tempPath = tempDir.path;
      File tempFile = File('$tempPath/copy.pdf');
      ByteData bd = await rootBundle.load('assets/jainaarti.pdf');
      await tempFile.writeAsBytes(bd.buffer.asUint8List(), flush: true);
      return tempFile;
    }

Future<File> fromAsset(String asset, String filename) async {
// To open from assets, you can copy them to the app storage folder, and the access them "locally"
    Completer<File> completer = Completer();
    try {
      var dir = await getApplicationDocumentsDirectory();
      File file = File("${dir.path}/$filename");
      var data = await rootBundle.load(asset);
      var bytes = data.buffer.asUint8List();
      await file.writeAsBytes(bytes, flush: true);
      completer.complete(file);
    } catch (e) {
      throw Exception('Error parsing asset file!');
    }
    return completer.future;

}

enter image description here

1 个答案:

答案 0 :(得分:4)

您正在使用的pdf库似乎已设置为使用系统文件路径来加载pdf。不幸的是,这不同于您可以访问的资产路径,Flutter当前不支持在运行时获取资产系统文件路径的功能。我可以找到使用该库的唯一方法是将文件传输到已知目录,然后从该目录加载。我不建议这样做,而是推荐native_pdf_view库,因为它支持资产加载和全屏显示。您应该能够实现它,如下所示:

final pdfController = PdfController(
  document: PdfDocument.openAsset('assets/copy.pdf'),
);

return Scaffold(
  body: Center(
    child: PdfView(
      controller: pdfController,
    )
  ),
);

-编辑-

要切换页面,如果要在其他页面上启动查看器,只需在pdfController中编辑initialPage

final pdfController = PdfController(
    document: PdfDocument.openAsset('assets/copy.pdf'),
    initialPage: 2
  );

如果要在创建pdfView之后切换页面,可以从任何地方调用jumpToPage()或animateToPage(),只要可以获取对pdfController的引用,并且已经实例化了它和pdfView。 / p>

return Scaffold(
      body: Stack(
        children: [
          Center(
            child: PdfView(
              controller: pdfController,
            )
          ),
          RaisedButton(
            child: Text("Page 2"),
            onPressed: (){
              pdfController.jumpToPage(2);
              //  -- or --
              pdfController.animateToPage(2, duration: Duration(seconds: 1), curve: Curves.linear);
            },
          ),
        ],
      ),
    );
相关问题