从资产颤振中打开pdf文件

2024-03-17

我正在尝试使用 flutter_fullpdfview 1.0.12 打开 PDF 文件,我的 PDF 文件位于 asset 文件夹下,但不知何故我收到错误,无法找到文件。我尝试了几个选项,但没有一个有效,并且都返回相同的错误。以下是我尝试加载文件的函数,但它们都因相同的错误而失败。

  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;

}


您正在使用的 pdf 库似乎被设置为使用系统文件路径来加载 pdf。不幸的是,这与您有权访问的资产路径不同,Flutter 目前不支持在运行时获取资产系统文件路径的功能。我找到使用该库的唯一方法是将文件传输到已知目录,然后从那里加载。我不建议这样做,而是推荐本机_pdf_视图 https://pub.dev/packages/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 已被实例化。

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);
            },
          ),
        ],
      ),
    );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从资产颤振中打开pdf文件 的相关文章

随机推荐