Skip to content

A convenience wrapper for building Flutter apps with PDFTron mobile SDK.

License

Notifications You must be signed in to change notification settings

venky9885/pdftron-flutter

 
 

Repository files navigation

PDFTron Flutter Wrapper

Prerequisites

  • No license key is requird for trial. However, a valid commercial license key is required after trial.
  • PDFTron SDK >= 6.9.0
  • Flutter >= 1.0.0

Preview

Android iOS
demo demo

Installation

The complete installation and API guides can be found at https://www.pdftron.com/documentation/android/flutter

Android

  1. First follow the Flutter getting started guides to install, set up an editor, and create a Flutter Project. The rest of this guide assumes your project is created by running flutter create myapp.

  2. Add the following dependency to your Flutter project in myapp/pubspec.yaml:

    dependencies:
       flutter:
         sdk: flutter
    +  pdftron_flutter:
    +    git:
    +      url: git://github.com/PDFTron/pdftron-flutter.git
    +  permission_handler: '3.0.1'
    
  3. Now add the following items in your myapp/android/app/build.gradle file:

    android {
    -   compileSdkVersion 27
    +   compileSdkVersion 29
    
        lintOptions {
    	disable 'InvalidPackage'
        }
    
        defaultConfig {
    	applicationId "com.example.myapp"
    -       minSdkVersion 16
    +       minSdkVersion 21
    -       targetSdkVersion 27
    +       targetSdkVersion 29
    +       multiDexEnabled true
    	versionCode flutterVersionCode.toInteger()
    	versionName flutterVersionName
    	testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        }
    	...
    }
  4. In your myapp\android\app\src\main\AndroidManifest.xml file, add the following lines to the <application> tag:

    ...
    <application
    	android:name="io.flutter.app.FlutterApplication"
    	android:label="myapp"
    	android:icon="@mipmap/ic_launcher"
    +	android:largeHeap="true"
    +	android:usesCleartextTraffic="true">
      ...

    Additionally, add the required permissions for your app in the <manifest> tag:

    	...
    	<uses-permission android:name="android.permission.INTERNET" />
    	<!-- Required to read and write documents from device storage -->
    +	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    	<!-- Required if you want to record audio annotations -->
    +	<uses-permission android:name="android.permission.RECORD_AUDIO" />
    	...
  5. Replace lib/main.dart with what is shown here

  6. Check that your Android device is running by running the command flutter devices. If none are available, follow the device set up instructions in the Install guides for your platform.

  7. Run the app with the command flutter run.

iOS

  1. First, follow the official getting started guide on installation, setting up an editor, and create a Flutter project, the following steps will assume your app is created through flutter create myapp

  2. Open myapp folder in a text editor. Then open myapp/pubspec.yaml file, add:

    dependencies:
       flutter:
         sdk: flutter
    +  pdftron_flutter:
    +    git:
    +      url: git://github.com/PDFTron/pdftron-flutter.git
    +  permission_handler: '3.0.1'
  3. Run flutter packages get

  4. Open myapp/ios/Podfile, add:

     # Uncomment this line to define a global platform for your project
    -# platform :ios, '9.0'
    +platform :ios, '9.3'
    ...
     target 'Runner' do
       ...
    +  # PDFTron Pods
    +  use_frameworks!
    +  pod 'PDFNet', podspec: 'https://www.pdftron.com/downloads/ios/cocoapods/pdfnet/latest.podspec'
     end
  5. Run flutter build ios --no-codesign to ensure integration process is sucessful

  6. Replace lib/main.dart with what is shown here

  7. Run flutter emulators --launch apple_ios_simulator

  8. Run flutter run

Usage

Open lib/main.dart, replace the entire file with the following:

import 'dart:async';
import 'dart:io' show Platform;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:pdftron_flutter/pdftron_flutter.dart';
import 'package:permission_handler/permission_handler.dart';

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

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

class _MyAppState extends State<MyApp> {
  String _version = 'Unknown';
  String _document = "https://pdftron.s3.amazonaws.com/downloads/pl/PDFTRON_mobile_about.pdf";

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

    if (Platform.isIOS) {
      // Open the document for iOS, no need for permission
      showViewer();

    } else {
      // Request for permissions for android before opening document
      launchWithPermission();
    }
  }

  Future<void> launchWithPermission() async {
    Map<PermissionGroup, PermissionStatus> permissions = await PermissionHandler().requestPermissions([PermissionGroup.storage]);
    if (granted(permissions[PermissionGroup.storage])) {
      showViewer();
    }
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String version;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      PdftronFlutter.initialize("Insert commercial license key here after purchase");
      version = await PdftronFlutter.version;
    } on PlatformException {
      version = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _version = version;
    });
  }


  void showViewer() {
    // Shows how to disable functionality. Uncomment to configure your viewer with a Config object.
    //  var disabledElements = [Buttons.shareButton, Buttons.searchButton];
    //  var disabledTools = [Tools.annotationCreateLine, Tools.annotationCreateRectangle];
    //  var config = Config();
    //  config.disabledElements = disabledElements;
    //  config.disabledTools = disabledTools;
    // config.customHeaders = {'headerName': 'headerValue'};
    //  PdftronFlutter.openDocument(_document, config: config);

    // Open document without a config file which will have all functionality enabled.
    PdftronFlutter.openDocument(_document);
  }

  bool granted(PermissionStatus status) {
    return status == PermissionStatus.granted;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('PDFTron flutter app'),
        ),
        body: Center(
          child: Text('Running on: $_version\n'),
        ),
      ),
    );
  }
}

APIs

PdftronFlutter.version

Obtain PDFTron SDK version

Returns: String

PdftronFlutter.initialize(String)

Initializes PDFTron SDK

Params

key

Your PDFTron license key

Type Required Default
String true

PdftronFlutter.openDocument(String)

Opens a document in the viewer

Params

path

Path to the document

Type Required Default
String true

PdftronFlutter.openDocument(String, password: String, config: Config)

Opens a document in the viewer with options to remove buttons and disable tools

Optional parameters:

  • password: String, password to an encrypted document
  • config: Config, viewer configuration options
var disabledElements = [Buttons.shareButton, Buttons.searchButton];
var disabledTools = [Tools.annotationCreateLine, Tools.annotationCreateRectangle];
var config = Config();
config.disabledElements = disabledElements;
config.disabledTools = disabledTools;
config.customHeaders = {'headerName': 'headerValue'};
PdftronFlutter.openDocument(_document, config: config);

PdftronFlutter.importAnnotationCommand(String)

Imports XFDF command string to the document. The XFDF needs to be a valid command format with <add> <modify> <delete> tags.

PdftronFlutter.importBookmarkJson(String)

Imports user bookmarks to the document. The input needs to be a valid bookmark JSON format, for example {"0":"Page 1"}.

PdftronFlutter.saveDocument()

Saves the currently opened document in the viewer and returns the absolute path to the file. Must only be called when the document is opened in the viewer.

var path = await PdftronFlutter.saveDocument();

Events

startExportAnnotationCommandListener

Event is raised when local annotation changes committed to the document.

var annotCancel = startExportAnnotationCommandListener((xfdfCommand) {
  // local annotation changed
  // upload XFDF command to server here
  print("flutter xfdfCommand: $xfdfCommand");
});

startExportBookmarkListener

Event is raised when user bookmark changes committed to the document.

var bookmarkCancel = startExportBookmarkListener((bookmarkJson) {
  print("flutter bookmark: ${bookmarkJson}");
});

Contributing

See Contributing

License

See License

About

A convenience wrapper for building Flutter apps with PDFTron mobile SDK.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Java 45.1%
  • Objective-C 36.3%
  • Dart 14.4%
  • Ruby 4.2%