Getting started with Flutter PDF Viewer (SfPdfViewer)

6 Dec 202415 minutes to read

This section explains the steps required to add the SfPdfViewer widget and its features. This section covers only the basic features needed to get started with the Syncfusion Flutter PDF Viewer plugin.

Add the Flutter PDF Viewer to an application

Create a simple project using the instructions given in the Getting Started with your first Flutter app documentation.

Add dependency

Add the Syncfusion Flutter PDF Viewer dependency to your pubspec.yaml file.

  • DART
  • dependencies:
    
    syncfusion_flutter_pdfviewer: ^xx.x.xx

    NOTE

    Here xx.x.xx denotes the current version of the Syncfusion Flutter PDF Viewer package.

    For the web platform, we have used PdfJs for rendering the PDF pages, so the script file must be referred to in your web/index.html file.

    On your web/index.html file, add the following script tags, somewhere in the head or body of the document:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
    <script type="text/javascript">
       pdfjsLib.GlobalWorkerOptions.workerSrc = "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.min.js";
    </script>

    NOTE

    Version 2.11.338 is recommended for using annotation support. This will not flatten the unsupported annotations while rendering the pages.

    Get packages

    Run the following command to get the required packages.

  • DART
  • $ flutter pub get

    Import package

    Import the following package in your Dart code.

    import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';

    Initialize the PDF Viewer

    Once the package has been imported, initialize the SfPdfViewer as a child of any widget. In the following shown examples, the SfPdfViewer widget is added as a child of the container widget. Several constructors are provided for the various ways that a PDF document can be loaded. They are,

    • Asset
    • Network
    • File
    • Memory

    Load document from the Asset

    The SfPdfViewer.asset creates a widget that displays the PDF document obtained from an AssetBundle. The following code example explains the same.

    @override
    Widget build(BuildContext context) {
      return Scaffold(
          body: SfPdfViewer.asset(
                  'assets/flutter-succinctly.pdf'));
    }

    Load document from the Network

    The SfPdfViewer.network creates a widget that displays the PDF document obtained from a URL. The following code example explains the same.

    @override
    Widget build(BuildContext context) {
      return Scaffold(
          body: SfPdfViewer.network(
                  'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf'));
    }

    To load PDF from network using SfPdfViewer.network in macOS, network access must be enabled in your macOS application. On your macos/Runner/DebugProfile.entitlements file, add the following lines inside the <dict>
    tag to enable the network access in your application:

    <key>com.apple.security.network.client</key>
    <true/>

    NOTE

    Due to CORS security restrictions in a web application, some PDFs obtained from URLs might not be loaded in the SfPdfViewer web platform. Kindly refer to the flutter forum reported on the same.

    This issue can be resolved by configuring the CORS settings in the requested server or by disabling the security settings in chrome.dart as mentioned in the below steps:

    1. Go to flutter\bin\cache and remove a file named: flutter_tools.stamp
    2. Go to flutter\packages\flutter_tools\lib\src\web and open the file chrome.dart.
    3. Find ’–disable-extensions’.
    4. Add ’–disable-web-security’.

    Load document from the File

    The SfPdfViewer.file creates a widget that displays the PDF document obtained from a File. The following code example explains the same.

    @override
    Widget build(BuildContext context) {
      return Scaffold(
          body: SfPdfViewer.file(
                  File('storage/emulated/0/Download/flutter-succinctly.pdf')));
    }

    NOTE

    On Android, this may require the android.permission.READ_EXTERNAL_STORAGE.

    NOTE

    Since the file system is not accessible from the browser, SfPdfViewer.file is not supported on Flutter Web.

    Load document from the Memory

    The SfPdfViewer.memory creates a widget that displays the PDF document obtained from the Uint8List. The following code example explains the same.

    @override
    Widget build(BuildContext context) {
      return Scaffold(
          body: SfPdfViewer.memory(
                  bytes));
    }

    How to load document from base64 string?

    To load a document from a base64 string, you can convert the base64 string to a Uint8List using the base64Decode method and pass it to the SfPdfViewer.memory constructor. The following code example explains the same.

    • Import the dart:convert package to use the base64Decode method.
    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
    
    void main() {
      runApp(const MaterialApp(
        home: MainApp(),
      ));
    }
    
    class MainApp extends StatelessWidget {
      const MainApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        // Pass the base64 string of the PDF document to the SyncfusionPDFViewer widget.
        return const SyncfusionPDFViewer(base64: base64);
      }
    }
    
    class SyncfusionPDFViewer extends StatefulWidget {
      const SyncfusionPDFViewer({super.key, required this.base64});
    
      /// Base64 string of the PDF document.
      final String base64;
    
      @override
      State<SyncfusionPDFViewer> createState() => _SyncfusionPDFViewerState();
    }
    
    class _SyncfusionPDFViewerState extends State<SyncfusionPDFViewer> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: SfPdfViewer.memory(
            // Decoding the base64 string to Uint8List.
            base64Decode(widget.base64),
          ),
        );
      }
    }

    Load the document with the specified page

    The SfPdfViewer allows you to load the document with the specified page using the initialPageNumber property. The following code example explains the same.

    @override
    Widget build(BuildContext context) {
      return Scaffold(
          body: SfPdfViewer.network(
                  'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
                  initialPageNumber: 5));
    }

    NOTE

    It is recommended not to use both the initialScrollOffset and initialPageNumber properties at the same time. If both properties are defined, the initialPageNumber will be prioritized over the initialScrollOffset

    Load document with the specified scroll offset position or zoom level

    The SfPdfViewer allows you to load the document with the specified scroll offset position or zoom level using the initialScrollOffset and initialZoomLevel properties. The following code example explains the same.

    @override
    Widget build(BuildContext context) {
      return Scaffold(
          body: SfPdfViewer.network(
                  'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
                  initialScrollOffset: Offset(0, 500),
                  initialZoomLevel: 1.5));
    }

    Get the current scroll offset position

    The SfPdfViewer allows you to get the current scroll offset position using the scrollOffset property. The following code example explains the same.

    final PdfViewerController _pdfViewerController=PdfViewerController();
    
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text('Syncfusion Flutter PDF Viewer'),
          actions: <Widget>[
            IconButton(
              icon: Icon(
                Icons.arrow_drop_down_circle,
                color: Colors.white,
              ),
              onPressed: () {
                _pdfViewerController.jumpToPage(3);
                print( _pdfViewerController.scrollOffset.dy);
                print( _pdfViewerController.scrollOffset.dx);
              },
            ),
          ],
        ),
        body: SfPdfViewer.network(
          'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
          controller: _pdfViewerController,
        ),
      );
    }

    Customize the space being displayed between the PDF pages

    By default, the SfPdfViewer displays the spacing between the PDF pages with the value of 4 pixels. You can customize the space being displayed using the pageSpacing property. The following code example explains the same.

    @override
    Widget build(BuildContext context) {
      return Scaffold(
          body: SfPdfViewer.network(
                  'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
                  pageSpacing: 2));
    }

    Customize the visibility of scroll head and scroll status

    By default, the SfPdfViewer displays the scroll head and scroll status. You can customize the visibility of these items using the canShowScrollHead and canShowScrollStatus properties. The following code example explains the same.

    @override
    Widget build(BuildContext context) {
      return Scaffold(
          body: SfPdfViewer.network(
                  'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
                  canShowScrollHead: false,
                  canShowScrollStatus: false));
    }

    NOTE

    On a desktop or mobile web browser, this canShowScrollHead property will have no effect since the scroll head will not be displayed there.

    Customize the visibility of page navigation dialog

    By default, the page navigation dialog will be displayed when the scroll head is tapped. You can customize the visibility of the page navigation dialog using the canShowPaginationDialog property. The following code example explains the same.

    @override
    Widget build(BuildContext context) {
      return Scaffold(
          body: SfPdfViewer.network(
                  'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf', 
                  canShowPaginationDialog: false));
    }

    NOTE

    On a desktop or mobile web browser, this canShowPaginationDialog property will have no effect since the pagination dialog will not be displayed there.

    Customize the visibility of page loading busy indicator

    By default, the SfPdfViewer displays the page loading busy indicator. You can customize the visibility of this using the canShowPageLoadingIndicator property. The following code example explains the same.

    @override
    Widget build(BuildContext context) {
      return Scaffold(
          body: SfPdfViewer.network(
                  'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf', 
                  canShowPageLoadingIndicator: false));
    }

    Callbacks

    The SfPdfViewer loading supports the PdfDocumentLoadedCallback and PdfDocumentLoadFailedCallback to notify whether the document has been loaded completely or not.

    Document loaded callback

    The onDocumentLoaded callback triggers after the document are loaded in the SfPdfViewer. The document in the PdfDocumentLoadedDetails will return the loaded PdfDocument instance. The following code example explains the same.

    @override
    Widget build(BuildContext context) {
      return Scaffold(
          body: SfPdfViewer.network(
        'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
        onDocumentLoaded: (PdfDocumentLoadedDetails details) {
          print(details.document.pages.count);
        },
      ));
    }

    Document load failed callback

    The onDocumentLoadFailed callback triggers when the document loading fails in the SfPdfViewer. That is,

    • When any corrupted document is loaded.
    • When any password-protected document is loaded with invalid or empty password.
    • When any improper input source value like the wrong URL or file path is given.
    • When any non-PDF document is loaded.

    The PdfDocumentLoadFailedDetails will return the error title and description message for the failure reason. The following code example explains the same.

    /// Displays the error message.
      void showErrorDialog(BuildContext context, String error, String description) {
        showDialog<dynamic>(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text(error),
                content: Text(description),
                actions: <Widget>[
                  TextButton(
                    child: const Text('OK'),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            });
     }
    
    @override
    Widget build(BuildContext context) {
      return Scaffold(
          body: SfPdfViewer.network(
        'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
        onDocumentLoadFailed: (PdfDocumentLoadFailedDetails details) {
            showErrorDialog(context, details.error, details.description);
        },
      ));
    }

    NOTE

    You can refer to our Flutter PDF Viewer feature tour page for its groundbreaking feature representations. You can also explore our Flutter PDF Viewer example that shows you how to render and configure the PDF Viewer.