I am trying to open PDF file using flutter_fullpdfview 1.0.12, i have the PDF file located under assets folder but somehow i am getting error unable to find file. I tried several options but none of them worked all return same error. Below are the functions i tried to load file and both of them failed with same error.
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;
}
It appears that the pdf library you are using is set up to use a system filepath to load the pdf. Unfortunately, this differs from the asset path that you have access to, and Flutter currently does not support the ability to get an assets system filepath at runtime. The only way I can find to use that library is to transfer the files to a known directory, and load from there. Rather than do this, I would recommend the native_pdf_view library, as it supports asset loading as well as full screen. You should be able to implement it as follows:
final pdfController = PdfController(
document: PdfDocument.openAsset('assets/copy.pdf'),
);
return Scaffold(
body: Center(
child: PdfView(
controller: pdfController,
)
),
);
-- EDIT --
To switch pages, if you want to start the viewer on a different page, just edit the initialPage in the pdfController
final pdfController = PdfController(
document: PdfDocument.openAsset('assets/copy.pdf'),
initialPage: 2
);
If you want to switch pages after the pdfView has been created, you can call jumpToPage() or animateToPage() from anywhere, provided you can get a reference to the pdfController, and that it and the pdfView have been instantiated.
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);
},
),
],
),
);