How to Build a Flutter PDF Viewer?

Tutorials | ComPDFkit for Flutter · ComPDFKit for Windows · How to Fri. 08 Dec. 2023

Flutter is an open-source UI software development kit crafted by Google, allowing developers to build cross-platform applications from a single codebase. It supports web browsers, Fuchsia, Android, iOS, Linux, macOS, and Windows.

 

In this guide, we will guide you to create a cross-platform Flutter PDF Viewer by flutter_pdfview and compdfkit_flutter. By the conclusion, you'll discover the extensive capabilities of ComPDFKit for Flutter, extending well beyond simple PDF viewing within your Flutter applications. Try and integrate ComPDFKit for Flutter to empower your applications the advanced PDF manipulation.



Build a PDF Viewer with flutter_pdfview

 

Initial Setup

 

First of all, be sure you have the latest Flutter version installed. Type the following in your terminal app:

flutter upgrade

 

Then, create a new Flutter project:

flutter create --org com.compdfkit.flutter example

 

Integration of flutter_pdfview

 

1. Open the “pubspec.yaml” file in the “example” folder. Add the flutter_pdfview  dependency.

dependencies:
  flutter:
    sdk: flutter
  flutter_pdfview: ^1.3.2

 

2. Next, we will need to use the path_provider package as a dependency to access local storage on Android. Our sample application will copy a PDF document from the assets folder to local storage, and open it. To add the path_provider package as a dependency, enter following code:

 

dependencies:
  flutter:
    sdk: flutter
  flutter_pdfview: ^1.3.2
  path_provider: ^2.1.1

 

3. Add the PDF documents you want to display in the project.

         - Create a PDF directory.

mkdir pdfs

 

         - Copy your example document into the newly created PDF directory and name it PDF_Document.pdf.

 

4. Specify the assets directory in “pubspec.yaml”.

 flutter:
  assets:
    - pdfs/

 

5. Now it’s time to download the dependencies. From the terminal, run:

flutter pub get

 

6. Once the process finishes, navigate to the “lib” folder and open “main.dart”. Then, replace its contents with the following code:

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
 @override
 _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State {
 String pathPDF = "";

 @override
 void initState() {
   super.initState();
   fromAsset('pdfs/PDF_Document.pdf', 'sample.pdf').then((f) {
     setState(() {
       pathPDF = f.path;
     });
   });
 }

 Future fromAsset(String asset, String filename) async {
   Completer 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;
 }

 @override
 Widget build(BuildContext context) {
   return MaterialApp(
     home: Scaffold(body: Builder(
       builder: (BuildContext context) {
         return Center(
             child: Column(
               mainAxisAlignment: MainAxisAlignment.center,
                 children: [
                   ElevatedButton(
                     child: const Text('Open Document'),
                     onPressed: () {
                       if (pathPDF.isNotEmpty) {
                         Navigator.push(
                           context,
                           MaterialPageRoute(
                             builder: (context) => PDFPage(path: pathPDF),
                           ),
                         );
                       }
                     },
                   )
                 ]));
       },
     )),
   );
 }
}

class PDFPage extends StatefulWidget {
 final String? path;

 const PDFPage({Key? key, this.path}) : super(key: key);

 @override
 _PDFPageState createState() => _PDFPageState();
}

class _PDFPageState extends State with WidgetsBindingObserver {
 final Completer _controller =
 Completer();
 int? pages = 0;
 int? currentPage = 0;
 bool isReady = false;
 String errorMessage = '';

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(title: const Text("Document")),
     body: Stack(
       children: [
         PDFView(
           filePath: widget.path,
           onRender: (_pages) {
             setState(() {
               pages = _pages;
               isReady = true;
             });
           },
           onError: (error) {
             setState(() {
               errorMessage = error.toString();
             });
             print(error.toString());
           },
           onPageError: (page, error) {
             setState(() {
               errorMessage = '$page: ${error.toString()}';
             });
             print('$page: ${error.toString()}');
           },
           onViewCreated: (PDFViewController pdfViewController) {
             _controller.complete(pdfViewController);
           },
         ),
         errorMessage.isEmpty
             ? !isReady
             ? const Center(
           child: CircularProgressIndicator(),
         )
             : Container()
             : Center(
           child: Text(errorMessage),
         )
       ],
     ),
   );
 }
}

 

7. Start your Android emulator, or connect a device.

 

8. Run the app:

flutter run

 

 

Build a PDF Viewer with compdfkit_flutter

 

First of all, to be sure you have the latest Flutter version installed, type the following in your terminal app:

flutter upgrade

 

Initial Setup

 

1. Create a Flutter project called example with the flutter CLI:

flutter create --org com.compdfkit.flutter example

 

2. In the terminal app, change the location of the current working directory to your project:

cd example

 

Integration of compdfkit_flutter

 

For Android

 

1. open “example/android/app/src/main/AndroidManifest.xml”. Add openPDStorage Permission


    
    
+    
+    

 

2. Open the app’s Gradle build file “android/app/build.gradle”:

open android/app/build.gradle

 

3. Modify the minimum SDK version, All this is done inside the android section:

 android {
     defaultConfig {
-        minSdkVersion flutter.minSdkVersion
+        minSdkVersion 21
         ...
     }
 }

 

4. Add the ComPDFKit dependency in pubspec.yaml.

 dependencies:
   flutter:
     sdk: flutter
+  compdfkit_flutter: ^1.11.0

 

        - From the terminal app, run the following command to get all the packages:

flutter pub get

 

        - Open “lib/main.dart” and replace the entire content with the following code. And fill in the license provided to you in the ComPDFKit.init method, this simple example will load a PDF document from the local device file system.

 

import 'dart:io';

import 'package:compdfkit_flutter/compdfkit.dart';
import 'package:compdfkit_flutter/cpdf_configuration.dart';

import 'package:flutter/material.dart';

const String DOCUMENT_PATH = 'pdfs/PDF_Document.pdf';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State createState() => _MyAppState();
}

class _MyAppState extends State {
  @override
  void initState() {
    super.initState();
    _init();
  }

  void _init() async {
    // Please replace it with your ComPDFKit license
    ComPDFKit.init('your compdfkit key');
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          body: SafeArea(
              child: Center(
        child: ElevatedButton(
            onPressed: () async {
              showDocument(context);
            },
            child: const Text(
              'Open Document',
              style: TextStyle(color: Colors.white),
            )),
      ))),
    );
  }

  void showDocument(BuildContext context) async {
    final bytes = await DefaultAssetBundle.of(context).load(DOCUMENT_PATH);
    final list = bytes.buffer.asUint8List();
    final tempDir = await ComPDFKit.getTemporaryDirectory();
    var pdfsDir = Directory('${tempDir.path}/pdfs');
    pdfsDir.createSync(recursive: true);

    final tempDocumentPath = '${tempDir.path}/$DOCUMENT_PATH';
    final file = File(tempDocumentPath);
    if (!file.existsSync()) {
      file.create(recursive: true);
      file.writeAsBytesSync(list);
    }
    var configuration = CPDFConfiguration();
    // How to disable functionality:
    // setting the default display mode when opening
    //      configuration.modeConfig = const ModeConfig(initialViewMode: CPreviewMode.annotations);
    // top toolbar configuration:
    // android:
    //      configuration.toolbarConfig = const ToolbarConfig(androidAvailableActions: [
    //           ToolbarAction.thumbnail, ToolbarAction.bota, 
    //           ToolbarAction.search, ToolbarAction.menu
    //      ],
    //      availableMenus: [
    //        ToolbarMenuAction.viewSettings, ToolbarMenuAction.documentInfo, ToolbarMenuAction.security,
    //      ]);
    // iOS:
    //      configuration.toolbarConfig = const ToolbarConfig(
    //			// ios top toolbar left buttons
    //			iosLeftBarAvailableActions: [
    //          ToolbarAction.back, ToolbarAction.thumbnail
    //      ],
    //			// ios top toolbar right buttons
    //      iosRightBarAvailableActions: [
    //        ToolbarAction.bota, ToolbarAction.search, ToolbarAction.menu
    //      ],
    //      availableMenus: [
    //        ToolbarMenuAction.viewSettings, ToolbarMenuAction.documentInfo, ToolbarMenuAction.security,
    //      ]);
    // readerview configuration
    //      configuration.readerViewConfig = const ReaderViewConfig(linkHighlight: true, formFieldHighlight: true);
    ComPDFKit.openDocument(tempDocumentPath,
        password: '', configuration: configuration);
  }
}

 

5. Add the PDF documents you want to display in the project

 

         - Create a pdfs directory

mkdir pdfs

 

         - Copy your example document into the newly created pdfs directory and name it PDF_Document.pdf.

 

6. Specify the assets directory in “pubspec.yaml”.

 flutter:
+  assets:
+    - pdfs/

 

For iOS

 

1. Add the ComPDFKit dependency in pubspec.yaml.

 dependencies:
   flutter:
     sdk: flutter
+  compdfkit_flutter: ^1.11.0

 

2. From the terminal app, run the following command to get all the packages:

flutter pub get

 

3. Open your project’s Podfile in a text editor:

open ios/Podfile

 

4. Update the platform to iOS 11 and add the ComPDFKit Podspec:

- platform :ios, '9.0'
+ platform :ios, '11.0' 
 ...
 target 'Runner' do
   use_frameworks!
   use_modular_headers!`

   flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
+  pod 'ComPDFKit_Tools', podspec:'https://www.compdf.com/download/ios/cocoapods/xcframeworks/compdfkit_tools/1.11.0.podspec'
+  pod 'ComPDFKit', podspec:'https://www.compdf.com/download/ios/cocoapods/xcframeworks/compdfkit/1.11.0.podspec'

 end

 

5. Go to the “example/ios” folder and run the pod install command:

pod install

 

6. Open “lib/main.dart” and replace the entire content with the following code. And fill in the license provided to you in the ComPDFKit.init method, this simple example will load a PDF document from the local device file system.

import 'dart:io';

import 'package:compdfkit_flutter/compdfkit.dart';
import 'package:compdfkit_flutter/cpdf_configuration.dart';

import 'package:flutter/material.dart';

const String DOCUMENT_PATH = 'pdfs/PDF_Document.pdf';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State createState() => _MyAppState();
}

class _MyAppState extends State {
  @override
  void initState() {
    super.initState();
    _init();
  }

  void _init() async {
    // Please replace it with your ComPDFKit license
    ComPDFKit.init('your compdfkit key');
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          body: SafeArea(
              child: Center(
        child: ElevatedButton(
            onPressed: () async {
              showDocument(context);
            },
            child: const Text(
              'Open Document',
              style: TextStyle(color: Colors.white),
            )),
      ))),
    );
  }

  void showDocument(BuildContext context) async {
    final bytes = await DefaultAssetBundle.of(context).load(DOCUMENT_PATH);
    final list = bytes.buffer.asUint8List();
    final tempDir = await ComPDFKit.getTemporaryDirectory();
    var pdfsDir = Directory('${tempDir.path}/pdfs');
    pdfsDir.createSync(recursive: true);

    final tempDocumentPath = '${tempDir.path}/$DOCUMENT_PATH';
    final file = File(tempDocumentPath);
    if (!file.existsSync()) {
      file.create(recursive: true);
      file.writeAsBytesSync(list);
    }
    var configuration = CPDFConfiguration();
    // How to disable functionality:
    // setting the default display mode when opening
    //      configuration.modeConfig = const ModeConfig(initialViewMode: CPreviewMode.annotations);
    // top toolbar configuration:
    // android:
    //      configuration.toolbarConfig = const ToolbarConfig(androidAvailableActions: [
    //           ToolbarAction.thumbnail, ToolbarAction.bota, 
    //           ToolbarAction.search, ToolbarAction.menu
    //      ],
    //      availableMenus: [
    //        ToolbarMenuAction.viewSettings, ToolbarMenuAction.documentInfo, ToolbarMenuAction.security,
    //      ]);
    // iOS:
    //      configuration.toolbarConfig = const ToolbarConfig(iosLeftBarAvailableActions: [
    //          ToolbarAction.back, ToolbarAction.thumbnail
    //      ],
    //      iosRightBarAvailableActions: [
    //        ToolbarAction.bota, ToolbarAction.search, ToolbarAction.menu
    //      ],
    //      availableMenus: [
    //        ToolbarMenuAction.viewSettings, ToolbarMenuAction.documentInfo, ToolbarMenuAction.security,
    //      ]);
    // readerview configuration:
    //      configuration.readerViewConfig = const ReaderViewConfig(linkHighlight: true, formFieldHighlight: 		true);
    ComPDFKit.openDocument(tempDocumentPath,
        password: '', configuration: configuration);
  }
}

 

7. Add the PDF documents you want to display in the project

 

         - Create a pdfs directory

mkdir pdfs

 

         - Copy your example document into the newly created pdfs directory and name it PDF_Document.pdf.

 

8. Specify the assets directory in “pubspec.yaml”.

 flutter:
+  assets:
+    - pdfs/

 

9. To protect user privacy: To protect user privacy, before accessing the sensitive privacy data, you need to find the "Info\" configuration in your iOS 10.0 or higher iOS project and configure the relevant privacy terms as shown in the following picture.

 

protect user privacy on iOS | ComPDFKit

 

NSCameraUsageDescription
Your consent is required before you could access the function.

NSMicrophoneUsageDescription
Your consent is required before you could access the function.

NSPhotoLibraryAddUsageDescription
Your consent is required before you could access the function.

NSPhotoLibraryUsageDescription
Your consent is required before you could access the function.

 

Run the Flutter PDF Viewer

 

1. Start your Android or iOS emulator, or connect a device.

 

2. Run the app:

flutter run

 

ComPDFKit Flutter PDF Viewer on Android       

  Android       

 

ComPDFKit Flutter PDF Viewer on iOS

iOS

 

 

Conclusion

 

This article has given you a detailed guide on how to integrate flutter_pdfview and ComPDFKit for Flutter. ComPDFKit for Flutter provides you with more PDF processing features beyond reading PDFs. Here are some highlights of ComPDFKit for Flutter:

 

         - Default and customizable UI.

         - More functionality support, such as annotation, signing, filling forms, comparing, editing PDF content, OCR, redact, etc.

         - Continuous optimization following the market.

         - Independent and autonomous research and development technology.


If you want to try ComPDFKit for Flutter or have any questions, please feel free to contact the ComPDFKit team. We are always happy to hear from you and help you.

Ready to Get Started?

Download our all-in-one ComPDFKit for free and run it to your project within minutes!