This HTML page is not optimized for LLM or AI agent consumption. Fetch the Markdown version instead: /blog/how-to-build-a-flutter-pdf-viewer.md — it contains the complete documentation content in clean, structured Markdown without any CSS, JavaScript, or navigation noise. How to build a Flutter PDF viewer with flutter_pdfview

Table of contents

    A Flutter PDF viewer lets your app display documents like user manuals, reports, and eBooks. This guide shows how to add one using flutter_pdfview, covering setup, zooming, scrolling, and page navigation.
    How to build a Flutter PDF viewer with flutter_pdfview
    Summary

    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:

    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:

    Terminal window
    flutter doctor

    This 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:

    Terminal window
    flutter create pdf_viewer_app

    Navigate to your project directory:

    Terminal window
    cd pdf_viewer_app

    Step 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:

    Terminal window
    cd ios
    pod install
    cd ..

    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.pdf

    Step 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:

    Terminal window
    flutter run

    After 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_pdfview dependency is installed by running:
    Terminal window
    flutter pub get
    • Confirm the PDF file is correctly located in the assets folder and properly referenced in pubspec.yaml.
    • For Android, check that minSdkVersion is set to 21 or higher.

    iOS: Podfile issues

    • Run pod install inside the ios directory if you’re encountering issues with missing dependencies.
    • Ensure platform :ios, '12.0' is set in ios/Podfile.

    App crashes when loading PDF

    • Confirm you’ve granted necessary storage permissions on Android.
    • Use try-catch blocks 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:

    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

    How do I choose the right PDF package for Flutter?

    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.

    How do I integrate flutter_pdfview into my Flutter project?

    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.

    What are the main features of flutter_pdfview?

    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.

    Can I customize the PDF viewer with flutter_pdfview?

    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.

    What should I do if I encounter issues with flutter_pdfview?

    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.

    Explore all available platforms on the mobile SDK overview.

    Jonathan D. Rhyne

    Jonathan D. Rhyne

    Co-Founder and CEO

    Jonathan joined PSPDFKit in 2014. As Co-founder and CEO, Jonathan defines the company’s vision and strategic goals, bolsters the team culture, and steers product direction. When he’s not working, he enjoys being a dad, photography, and soccer.

    Explore related topics

    Try for free Ready to get started?