How to build a Flutter PDF viewer with flutter_pdfview
Table of contents
This guide shows how to build a Flutter PDF viewer from scratch. It compares open source packages like flutter_pdfview, walks through integration steps (dependencies, configuration, and widget creation), and covers page navigation, zooming, and dragging. It also covers the options available through Nutrient’s Flutter PDF editor.
This post will walk you through the process of setting up a basic PDF viewer in Flutter to handle single-page documents.
Flutter(opens in a new tab) is an open source framework developed by Google that allows for creating natively compiled applications for mobile, web, and desktop from a single codebase in Dart(opens in a new tab).
First, you’ll choose a package for PDF viewing from the open source options. Then you’ll integrate it into a Flutter project to get a working PDF viewer app.
Choosing the right PDF package for Flutter
When selecting a PDF library for Flutter, evaluate your requirements against package quality and functionality. For simple use cases, an open source library is a good starting point. For more advanced needs, Nutrient offers a Flutter PDF editor.
To find suitable packages, searching for pdf(opens in a new tab) on pub.dev(opens in a new tab) reveals many options. Key factors to consider include:
- Pub points — Reflects the quality of the package based on static analysis, including support for null safety and adherence to Dart conventions.
- Popularity — Indicates the number of developers using the package.
- Update frequency — A recent update date often signifies an actively maintained project.
- Verified publisher — Some packages come from verified publishers.
Among the search results, the following packages are noteworthy:
flutter_pdfview(opens in a new tab) — A Flutter plugin that provides aPDFViewwidget on Android and iOSnative_pdf_view(opens in a new tab) — A Flutter plugin for rendering PDF files on web, macOS, Windows, Android, and iOS (now published aspdfx)advance_pdf_viewer(opens in a new tab) — A Flutter plugin for handling PDF files
Of the three packages, flutter_pdfview fits a simple PDF viewer best. It ships an example in its GitHub repository(opens in a new tab), the configuration steps are short, and on Android, it’s built on a Google library called PDFium(opens in a new tab), which we use at Nutrient too. (On iOS, it renders with Apple’s PDFKit.)
Building a PDF viewer with flutter_pdfview
flutter_pdfview renders PDFs on both Android and iOS. It displays PDF files inside your Flutter app and supports page navigation, zooming, and more. It exposes configuration options(opens in a new tab) to customize the experience, and there’s an example app(opens in a new tab) in the GitHub repository(opens in a new tab).
To keep the use case simple, this post will use flutter_pdfview to show a single-page PDF document on an Android device with API 30(opens in a new tab).
The app’s main layout is a widget that shows the rendered PDF and supports pinch-to-zoom and dragging the zoomed page.
Getting started
Make sure Flutter is installed(opens in a new tab) and set up on your development machine. Check it by running:
flutter doctorThis command will verify if you have everything in place to start developing with Flutter.
Step 1 — Creating a new Flutter project
Begin by creating a new Flutter project. Open your terminal and run:
flutter create pdf_viewer_appNavigate to your project directory:
cd pdf_viewer_appStep 2 — Adding the flutter_pdfview dependency
Next, add the flutter_pdfview package to your pubspec.yaml file under dependencies:
...dependencies: flutter: sdk: flutter flutter_pdfview: ^1.2.7...Be careful with the above, as spaces matter in YAML files.
Run flutter pub get to install the package.
Step 3 — Updating the Android and iOS configurations
For Android, ensure your minSdkVersion is at least 21 in android/app/build.gradle:
defaultConfig { ... minSdkVersion 21 ...}For iOS, enable Swift support by adding the following to your ios/Podfile:
platform :ios, '12.0'Then, install the dependencies:
cd iospod installcd ..Step 4 — Creating the PDF viewer widget
Now you’ll create the PDF viewer widget. Open lib/main.dart and replace its content with the following code:
import 'package:flutter/material.dart';import 'package:flutter_pdfview/flutter_pdfview.dart';import 'package:path_provider/path_provider.dart';import 'dart:io';import 'dart:async';import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: PDFScreen(), ); }}
class PDFScreen extends StatefulWidget { @override _PDFScreenState createState() => _PDFScreenState();}
class _PDFScreenState extends State<PDFScreen> { String? _localPath; int? _totalPages = 0; int? _currentPage = 0; bool pdfReady = false; late PDFViewController _pdfViewController;
@override void initState() { super.initState(); fromAsset('assets/sample.pdf', 'sample.pdf').then((file) { setState(() { _localPath = file.path; pdfReady = true; }); }); }
Future<File> fromAsset(String asset, String fileName) async { final byteData = await rootBundle.load(asset); final file = File('${(await getTemporaryDirectory()).path}/$fileName'); await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes)); return file; }
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('PDF Viewer'), actions: _totalPages != null ? <Widget>[ Center(child: Text('${_currentPage! + 1} / $_totalPages')), IconButton( icon: Icon(Icons.chevron_left), onPressed: () { setState(() { _currentPage = (_currentPage! - 1).clamp(0, _totalPages! - 1); }); _pdfViewController.setPage(_currentPage!); }, ), IconButton( icon: Icon(Icons.chevron_right), onPressed: () { setState(() { _currentPage = (_currentPage! + 1).clamp(0, _totalPages! - 1); }); _pdfViewController.setPage(_currentPage!); }, ), ] : null, ), body: pdfReady ? PDFView( filePath: _localPath, enableSwipe: true, swipeHorizontal: true, autoSpacing: false, pageFling: false, onRender: (_pages) { setState(() { _totalPages = _pages; }); }, onViewCreated: (PDFViewController vc) { _pdfViewController = vc; }, onPageChanged: (page, total) { setState(() { _currentPage = page; }); }, onError: (error) { print(error.toString()); }, onPageError: (page, error) { print('$page: ${error.toString()}'); }, ) : Center(child: CircularProgressIndicator()), ); }}Step 5 — Adding a sample PDF
Add a sample PDF document named sample.pdf to your assets folder. If the folder doesn’t exist, create it in the root directory of your project. Then, update your pubspec.yaml file to include the assets:
flutter: assets: - assets/sample.pdfStep 6 — Running the app
To run the PDF viewer, make sure to connect a physical Android device or open an emulator from the Android Virtual Device Manager(opens in a new tab). Then from the command line, type:
flutter runAfter a short building process, the PDF viewer app will be ready to use on the Android device. 🎉
Troubleshooting and error handling
The following sections outline errors you may encounter and how to deal with them.
flutter_pdfview isn’t displaying the PDF
- Ensure the
flutter_pdfviewdependency is installed by running:
flutter pub get- Confirm the PDF file is correctly located in the
assetsfolder and properly referenced inpubspec.yaml. - For Android, check that
minSdkVersionis set to21or higher.
iOS: Podfile issues
- Run
pod installinside theiosdirectory if you’re encountering issues with missing dependencies. - Ensure
platform :ios, '12.0'is set inios/Podfile.
App crashes when loading PDF
- Confirm you’ve granted necessary storage permissions on Android.
- Use
try-catchblocks around file loading logic to handle potential errors.
Cons of flutter_pdfview for advanced features
While flutter_pdfview is a solid package for rendering PDFs in Flutter, it does have certain limitations when it comes to advanced features.
Uneven cross-platform support
flutter_pdfview supports pinch-to-zoom (via the minZoom/maxZoom options and PDFViewController.setScale), but several other options — including fitPolicy, nightMode, pageSnap, and onPageError — work on Android only. Behavior can differ across platforms, so you may need per-platform handling.
Limited page navigation
While basic page navigation (like swiping between pages) is supported, there’s no built-in support for more advanced navigation controls like a page slider, page jump, or navigation bar. You need to implement custom controls for these features manually.
No native support for annotations or form filling
flutter_pdfview doesn’t have built-in support for adding annotations or filling out forms within the PDF. You can use additional packages such as pdf_render(opens in a new tab) or pdf_text(opens in a new tab) to manipulate the content, but combining them with flutter_pdfview to render the updated content requires additional development work.
No text selection or search functionality
Text selection and search aren’t natively supported in flutter_pdfview. To enable text search and selection, you’ll need to extract the text using packages like pdf_text(opens in a new tab) and build a custom search and selection system. This adds complexity to the implementation.
These limitations mean that flutter_pdfview might not be the best fit if you require these advanced features for your Flutter PDF viewer. You may need to consider other solutions or integrate additional libraries for a full-featured experience.
Conclusion
This post covered some factors to look at when selecting a PDF package from a set of open source packages, and it showed how to build a PDF viewer using the open source Flutter PDF library, flutter_pdfview(opens in a new tab), which is good for solving simple use cases without too much hassle. However, AndroidPdfViewer(opens in a new tab) — the library flutter_pdfview(opens in a new tab) is based on — has seen only intermittent maintenance, and older releases were published to JCenter(opens in a new tab), an artifact repository that’s now read-only.
For more complex customization, Nutrient offers its own Flutter PDF library with a detailed getting started guide. Nutrient ships with many features out of the box, including:
- A customizable UI that’s simple and easy to use.
- Embeddable prebuilt tools to easily add functionality like annotating documents, filling and signing forms, and much more.
- Multiple file type support — from image files (JPG, PNG, and TIFF) to PDF documents.
It also features active development cycles with constant improvements and bug fixes. To get started with Nutrient Flutter SDK, check out our free trial. If you have any questions about our Flutter PDF library, please don’t hesitate to reach out to us. We’re happy to help!
Recommended reading: Start with Flutter PDF creation, explore React Native alternatives, or learn about advanced PDF features.
FAQ
When selecting a PDF package, consider factors like pub points, popularity, update frequency, and whether the package supports your required features. Popular packages for Flutter include flutter_pdfview, native_pdf_view, and advance_pdf_viewer.
To integrate flutter_pdfview, add it to your pubspec.yaml dependencies, include path_provider(opens in a new tab) for file management, run flutter pub get, set the Android minSdkVersion and iOS Podfile platform, and add your PDF document to the project’s assets.
flutter_pdfview provides a widget for rendering PDFs in Flutter applications. It supports basic functionalities like viewing PDF documents with pinch-to-zoom and page navigation. It uses the AndroidPdfViewer library under the hood for rendering.
flutter_pdfview offers some configuration options to customize the viewing experience, such as setting up page zoom and scrolling. For more extensive customization, consider using more advanced libraries or integrating with tools like Nutrient.
If you face issues with flutter_pdfview, check the GitHub repository(opens in a new tab) for troubleshooting tips and open issues. For more complex needs, consider alternative solutions like Nutrient Flutter SDK, which offers additional support and features.
Related reading
- How to build a React Native PDF viewer — Cross-platform PDF viewing with React Native
- Build an Android PDF viewer using Nutrient — Step-by-step Android PDF viewer guide
- Top five document viewers for developers — Compare DOCX and PDF viewer libraries side by side
Explore all available platforms on the mobile SDK overview.