Flutter PDF View With Example

In this article, we are going to integrate pdf view in flutter applications. We can display pdf from two storages (1) from assets folder (2) from url through internet.

In this example, we are using a package called flutter_pdfview to integrate pdf viewer in our flutter applications. This package provided native pdf view for android & iOS platforms.

We can get pdf from both assets folder and from url in this example. For assets folder, we need to save pdf in our main source code folder and set path in pubspec.yaml file.

If we want to display pdf from url, then first we need to download pdf using internet. Then we can display it in our pdf viewer using flutter_pdfview package.

 

Add require dependency in pubspec.yaml file

After adding below lines in your pubspec.yaml file under dependecies, click on pub get button to install dependencies.

flutter_pdfview: ^1.0.4
path_provider: ^1.2.0
 
 

Change in iOS Platform for Flutter PDF View

To display pdf view in iOS platform you need to add below key in Info.plist file.

<key>io.flutter.embedded_views_preview</key>
<true/>
 
 

Get PDF From Local Storage

First we need to store pdf in main folder in our source code. Then you need to add path in your pubspec.yaml file as below.

assets:
    – docs/test_pdf.pdf
 

After that we need to get this pdf file path on start of app screen as below.

@override
void initState() {
super.initState();
fromAsset(‘docs/test_pdf.pdf’, ‘test_pdf.pdf’).then((f) {
    setState(() {
        pathPDF = f.path;
    });
});
}
 
Future<File> fromAsset(String asset, String filename) async {
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 pdf file!’);
}

return completer.future;
}

 
 

Get PDF From URL

To display pdf from url, first we need to download pdf and convert response into bytes. Then we need to create file using these bytes data and display in in flutter pdf view.

@override
void initState() {
super.initState();

createFileOfPdfUrl().then((f) {
    setState(() {
        remotePathPDF = f.path;
    });
});
}

 
Future<File> createFileOfPdfUrl() async {
Completer<File> completer = Completer();
try {
    final url = “http://www.pdf995.com/samples/pdf.pdf”;
    final fileName = url.substring(url.lastIndexOf(“/”) + 1);
    var request = await HttpClient().getUrl(Uri.parse(url));
    var response = await request.close();
    var bytes = await consolidateHttpClientResponseBytes(response);
    var dir = await getApplicationDocumentsDirectory();
    File file = File(“${dir.path}/$fileName”);

    await file.writeAsBytes(bytes, flush: true);
    completer.complete(file);
} catch (e) {
    throw Exception(‘Error downloading pdf file!’);
}

return completer.future;
}

 
 

Display Flutter PDF View

There are different properties in PDFView widget. filePath property defines path of pdf file. You can swipe pdf using enableSwipe property. There are many listeners in PDFView widget.

We can also do some work when pdf page is changed using onPageChanged listener. We can also detect pdf rendering using onRender listener. There are also two error listeners in PDFView widget such as onPageError and onError.

Stack(
children: [
PDFView(
    filePath: widget.path,
    enableSwipe: true,
    swipeHorizontal: true,
    autoSpacing: false,
    pageFling: false,
    onRender: (_pages) {
        setState(() {
            pages = _pages;
            isReady = true;
        });
    },
    onError: (error) {
        print(error.toString());
    },
    onPageError: (page, error) {
        print(‘$page: ${error.toString()}’);
    },
    onViewCreated: (PDFViewController pdfViewController) {
        _controller.complete(pdfViewController);
    },
    onPageChanged: (int page, int total) {
        print(‘page change: $page/$total’);
    },
),
errorMessage.isEmpty
? !isReady
? Center(
    child: CircularProgressIndicator(),
)
: Container()
: Center(
    child: Text(errorMessage),
)
],
),
 
 
flutter pdf view
 
 

One thought on “Flutter PDF View With Example

Leave a Reply