我试图从一个URL获取一个PDF文件,并在我的Flutter应用程序(Android和iOS)中呈现它。我已经在网上搜索了关于如何在Flutter中呈现一个提取的PDF文件的答案,但是我所能找到的只是如何呈现一个本地预添加的PDF文件。我也搜索了做同样事情的软件包,但我找不到一个有效的。
示例:
例如,我正在尝试获取this PDF文件,并在我的应用程序中的Flutter小部件屏幕内呈现它。有谁知道我该怎么做?谢谢你,谢谢你
qvtsj1bj1#
使用flutter_pdfview包。1.在Android清单中添加权限
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
1.在pubspec.yaml中添加依赖项
dependencies: flutter: sdk: flutter flutter_pdfview: ^1.0.1 http: ^0.12.0+4 path_provider: any permission_handler: 4.4.0 //For asking permission to load the pdf
1.然后使用PDFView完整代码:
import 'package:flutter/material.dart'; import 'package:flutter_pdfview/flutter_pdfview.dart'; import 'dart:io'; import 'package:http/http.dart' as http; import 'package:path_provider/path_provider.dart'; import 'package:permission_handler/permission_handler.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { String urlPDFPath = ""; bool exists = true; int _totalPages = 0; int _currentPage = 0; bool pdfReady = false; PDFViewController _pdfViewController; bool loaded = false; Future<File> getFileFromUrl(String url, {name}) async { var fileName = 'testonline'; if (name != null) { fileName = name; } try { var data = await http.get(url); var bytes = data.bodyBytes; var dir = await getApplicationDocumentsDirectory(); File file = File("${dir.path}/" + fileName + ".pdf"); print(dir.path); File urlFile = await file.writeAsBytes(bytes); return urlFile; } catch (e) { throw Exception("Error opening url file"); } } void requestPersmission() async { await PermissionHandler().requestPermissions([PermissionGroup.storage]); } @override void initState() { requestPersmission(); getFileFromUrl("http://www.africau.edu/images/default/sample.pdf").then( (value) => { setState(() { if (value != null) { urlPDFPath = value.path; loaded = true; exists = true; } else { exists = false; } }) }, ); super.initState(); } @override Widget build(BuildContext context) { print(urlPDFPath); if (loaded) { return Scaffold( body: PDFView( filePath: urlPDFPath, autoSpacing: true, enableSwipe: true, pageSnap: true, swipeHorizontal: true, nightMode: false, onError: (e) { //Show some error message or UI }, onRender: (_pages) { setState(() { _totalPages = _pages; pdfReady = true; }); }, onViewCreated: (PDFViewController vc) { setState(() { _pdfViewController = vc; }); }, onPageChanged: (int page, int total) { setState(() { _currentPage = page; }); }, onPageError: (page, e) {}, ), floatingActionButton: Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ IconButton( icon: Icon(Icons.chevron_left), iconSize: 50, color: Colors.black, onPressed: () { setState(() { if (_currentPage > 0) { _currentPage--; _pdfViewController.setPage(_currentPage); } }); }, ), Text( "${_currentPage + 1}/$_totalPages", style: TextStyle(color: Colors.black, fontSize: 20), ), IconButton( icon: Icon(Icons.chevron_right), iconSize: 50, color: Colors.black, onPressed: () { setState(() { if (_currentPage < _totalPages - 1) { _currentPage++; _pdfViewController.setPage(_currentPage); } }); }, ), ], ), ); } else { if (exists) { //Replace with your loading UI return Scaffold( appBar: AppBar( title: Text("Demo"), ), body: Text( "Loading..", style: TextStyle(fontSize: 20), ), ); } else { //Replace Error UI return Scaffold( appBar: AppBar( title: Text("Demo"), ), body: Text( "PDF Not Available", style: TextStyle(fontSize: 20), ), ); } } } }
e3bfsja22#
您可以使用flutter_cached_pdfview这是一个超级的flutter_pdfview得到了很多方法,以帮助你更快地与pdf工作这是一个从URL查看pdf并缓存它的示例
PDF().cachedFromUrl('http://africau.edu/images/default/sample.pdf'),
它具有flutter_pdfview的所有功能看一看https://pub.dev/packages/flutter_cached_pdfview
92dk7w1h3#
我一直在寻找解决这个问题的方法,我尝试了前面的答案中提到的,我没有得到一个很好的结果,在搜索和尝试了几个库后,我找到了一个最初对我有效的,我希望它能帮助你To you too syncfusion_flutter_pdfviewer
import 'package:flutter/material.dart'; import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart'; void main() { runApp(MaterialApp( title: 'Syncfusion PDF Viewer Demo', home: HomePage(), )); } /// Represents Homepage for Navigation class HomePage extends StatefulWidget { @override _HomePage createState() => _HomePage(); } class _HomePage extends State<HomePage> { final GlobalKey<SfPdfViewerState> _pdfViewerKey = GlobalKey(); @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Syncfusion Flutter PDF Viewer'), actions: <Widget>[ IconButton( icon: const Icon( Icons.bookmark, color: Colors.white, semanticLabel: 'Bookmark', ), onPressed: () { _pdfViewerKey.currentState?.openBookmarkView(); }, ), ], ), body: SfPdfViewer.network( 'https://cdn.syncfusion.com/content/PDFViewer/flutter- succinctly.pdf', key: _pdfViewerKey, ), ); } }
yizd12fk4#
我试过使用pdf_render软件包,它对我很有效,这个软件包也可以直接从url加载pdf文档。
PdfViewer.openFutureFile( // Accepting function that returns Future<String> of PDF file path () async => (await DefaultCacheManager().getSingleFile( 'https://github.com/espresso3389/flutter_pdf_render/raw/master/example/assets/hello.pdf')) .path, viewerController: controller, onError: (err) => print(err), params: const PdfViewerParams( padding: 10, minScale: 1.0, // scrollDirection: Axis.horizontal, ), ))
4条答案
按热度按时间qvtsj1bj1#
使用flutter_pdfview包。
1.在Android清单中添加权限
1.在pubspec.yaml中添加依赖项
1.然后使用PDFView
完整代码:
e3bfsja22#
您可以使用flutter_cached_pdfview
这是一个超级的flutter_pdfview
得到了很多方法,以帮助你更快地与pdf工作
这是一个从URL查看pdf并缓存它的示例
它具有flutter_pdfview的所有功能
看一看https://pub.dev/packages/flutter_cached_pdfview
92dk7w1h3#
我一直在寻找解决这个问题的方法,我尝试了前面的答案中提到的,我没有得到一个很好的结果,在搜索和尝试了几个库后,我找到了一个最初对我有效的,我希望它能帮助你To you too syncfusion_flutter_pdfviewer
yizd12fk4#
我试过使用pdf_render软件包,它对我很有效,这个软件包也可以直接从url加载pdf文档。