• Stars
    star
    170
  • Rank 223,307 (Top 5 %)
  • Language
    Java
  • License
    Other
  • Created almost 6 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

About PDFTron Flutter

PDFTron's Flutter PDF library brings smooth, flexible, and stand-alone document viewing and editing solutions using Flutter codebases for iOS and Android applications.

  • Direct MS Office document viewing and conversion
  • Fully customizable open source UI to improve app engagement
  • Document reflow to increase readability and accessibility on mobile
  • File streaming to view remote and complex documents faster
  • Night mode to improve viewing in low-light environments
  • And much more...

More information can be found at https://www.pdftron.com/documentation/guides/flutter

Android iOS
A gif showcasing the UI and some features on Android A gif showcasing the UI and some features on iOS

Contents

Prerequisites

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

Null Safety

Dart now supports sound null safety, which is available starting from Dart 2.12.0 and Flutter 2.0.0. Here is a guide to migrate to null safety

If you would like to use our null safe SDK, it is available in the following places:

The rest of this README.md contains documentation, installation instructions, and information for the null safe version of our SDK.

Legacy UI

Version 0.0.6 is the last stable release for the legacy UI.

The release can be found here: https://github.com/PDFTron/pdftron-flutter/releases/tag/legacy-ui.

Installation

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

  • If you want to use our null safe package from pub.dev:
    dependencies:
        flutter:
          sdk: flutter
    +   pdftron_flutter:
  • If you want to use our null safe package from GitHub:
    dependencies:
        flutter:
          sdk: flutter
    +   pdftron_flutter:
    +     git:
    +       url: git://github.com/PDFTron/pdftron-flutter.git
  1. In the myapp directory, run flutter packages get.

Android

The following instructions are only applicable to Android development; click here for the iOS counterpart.

  1. Now add the following items in your myapp/android/app/build.gradle file:

    defaultConfig {
        applicationId "com.example.myapp"
    -   minSdkVersion flutter.minSdkVersion
    +   minSdkVersion 21
    +   multiDexEnabled true
    +   manifestPlaceholders += [pdftronLicenseKey:PDFTRON_LICENSE_KEY]
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }
  2. In your myapp/android/gradle.properties file, add the following line:

    # Add the PDFTRON_LICENSE_KEY variable here. 
    # For trial purposes leave it blank.
    # For production add a valid commercial license key.
    PDFTRON_LICENSE_KEY=
  3. In your myapp/android/app/src/main/AndroidManifest.xml file, add the following lines:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.myapp">
    
    + <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" />
    
      <application
        ...
    +   android:largeHeap="true"
    +   android:usesCleartextTraffic="true">
    
        <!-- Add license key in meta-data tag here. This should be inside the application tag. -->
    +   <meta-data
    +     android:name="pdftron_license_key"
    +     android:value="${pdftronLicenseKey}"/>
        ...

    If you are using the DocumentView widget, change the parent class of your MainActivity file (either Kotlin or Java) to FlutterFragmentActivity:

    import androidx.annotation.NonNull
    import io.flutter.embedding.android.FlutterFragmentActivity
    import io.flutter.embedding.engine.FlutterEngine
    import io.flutter.plugins.GeneratedPluginRegistrant
    
    class MainActivity : FlutterFragmentActivity() {
        override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
            GeneratedPluginRegistrant.registerWith(flutterEngine);
        }
    }
  4. Follow the instructions outlined in the Usage section.

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

  6. Run the app with the command flutter run.

iOS

The following instructions are only applicable to iOS development; click here for the Android counterpart.

Note
(August 2022)

There are new podspec files to use when integrating the PDFTron Flutter Wrapper for iOS:

Please update your ios/Podfile accordingly.

  1. Open myapp/ios/Podfile file and add:
      # Uncomment this line to define a global platform for your project
    - # platform :ios, '9.0'
    + platform :ios, '10.0'
      ...
      target 'Runner' do
        ...
    +   # PDFTron Pods
    +   pod 'PDFTron', podspec: 'https://pdftron.com/downloads/ios/flutter/pdftron/latest.podspec'
    +   pod 'PDFTronTools', podspec: 'https://pdftron.com/downloads/ios/flutter/pdftron-tools/latest.podspec'
      end
  2. To ensure integration process is successful, run flutter build ios --no-codesign
  3. Follow the instructions outlined in the Usage section.
  4. Run flutter emulators --launch apple_ios_simulator
  5. Run flutter run

Widget or Plugin

There are 2 different ways to use PDFTron Flutter API:

  • Present a document via a plugin.
  • Show a PDFTron document view via a Widget.

You must choose either the widget or plugin, and use it for all APIs. Mixing widget and plugin APIs will not function correctly. Whether you choose the widget or plugin is personal preference.

If you pick the Android widget, you will need to add padding for operating system intrusions like the status bar at the top of the device. One way is to set the enabled system UI, and then wrap the widget in a SafeArea or use an AppBar:

// If using Flutter v2.3.0-17.0.pre or earlier.
SystemChrome.setEnabledSystemUIOverlays(
  SystemUiOverlay.values
);
// If using later Flutter versions.
SystemChrome.setEnabledSystemUIMode(
  SystemUiMode.edgeToEdge,
);

// If using SafeArea:
return SafeArea (
  child: DocumentView(
    onCreated: _onDocumentViewCreated,
  ));

// If using AppBar:
return Scaffold(
  appBar: AppBar( toolbarHeight: 0 ),
  body: DocumentView(
    onCreated: _onDocumentViewCreated,
  ));

Usage

  1. If you want to use local files on Android, add the following dependency to myapp/pubspec.yaml:
  permission_handler: ^8.1.1
  1. 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';
// Uncomment this if you are using local files
// import 'package:permission_handler/permission_handler.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Viewer(),
    );
  }
}

class Viewer extends StatefulWidget {
  @override
  _ViewerState createState() => _ViewerState();
}

class _ViewerState extends State<Viewer> {
  String _version = 'Unknown';
  String _document =
      "https://pdftron.s3.amazonaws.com/downloads/pl/PDFTRON_mobile_about.pdf";
  bool _showViewer = true;

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

    showViewer();

    // If you are using local files delete the line above, change the _document field
    // appropriately and uncomment the section below.
    // if (Platform.isIOS) {
      // // Open the document for iOS, no need for permission.
      // showViewer();
    // } else {
      // // Request permission for Android before opening document.
      // launchWithPermission();
    // }
  }

  // Future<void> launchWithPermission() async {
  //  PermissionStatus permission = await Permission.storage.request();
  //  if (permission.isGranted) {
  //    showViewer();
  //  }
  // }

  // Platform messages are asynchronous, so initialize in an async method.
  Future<void> initPlatformState() async {
    String version;
    // Platform messages may fail, so use a try/catch PlatformException.
    try {
      // Initializes the PDFTron SDK, it must be called before you can use any functionality.
      PdftronFlutter.initialize("your_pdftron_license_key");

      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, you want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

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

  void showViewer() async {
    // opening without a config file will have all functionality enabled.
    // await PdftronFlutter.openDocument(_document);

    var config = Config();
    // How to disable functionality:
    //      config.disabledElements = [Buttons.shareButton, Buttons.searchButton];
    //      config.disabledTools = [Tools.annotationCreateLine, Tools.annotationCreateRectangle];
    // Other viewer configurations:
    //      config.multiTabEnabled = true;
    //      config.customHeaders = {'headerName': 'headerValue'};

    // An event listener for document loading
    var documentLoadedCancel = startDocumentLoadedListener((filePath) {
      print("document loaded: $filePath");
    });

    await PdftronFlutter.openDocument(_document, config: config);

    try {
      // The imported command is in XFDF format and tells whether to add, modify or delete annotations in the current document.
      PdftronFlutter.importAnnotationCommand(
          "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
              "    <xfdf xmlns=\"http://ns.adobe.com/xfdf/\" xml:space=\"preserve\">\n" +
              "      <add>\n" +
              "        <square style=\"solid\" width=\"5\" color=\"#E44234\" opacity=\"1\" creationdate=\"D:20200619203211Z\" flags=\"print\" date=\"D:20200619203211Z\" name=\"c684da06-12d2-4ccd-9361-0a1bf2e089e3\" page=\"1\" rect=\"113.312,277.056,235.43,350.173\" title=\"\" />\n" +
              "      </add>\n" +
              "      <modify />\n" +
              "      <delete />\n" +
              "      <pdf-info import-version=\"3\" version=\"2\" xmlns=\"http://www.pdftron.com/pdfinfo\" />\n" +
              "    </xfdf>");
    } on PlatformException catch (e) {
      print("Failed to importAnnotationCommand '${e.message}'.");
    }

    try {
      // Adds a bookmark into the document.
      PdftronFlutter.importBookmarkJson('{"0":"Page 1"}');
    } on PlatformException catch (e) {
      print("Failed to importBookmarkJson '${e.message}'.");
    }

    // An event listener for when local annotation changes are committed to the document.
    // xfdfCommand is the XFDF Command of the annotation that was last changed.
    var annotCancel = startExportAnnotationCommandListener((xfdfCommand) {
      String command = xfdfCommand;
      print("flutter xfdfCommand:\n");
      // Dart limits how many characters are printed onto the console. 
      // The code below ensures that all of the XFDF command is printed.
      if (command.length > 1024) {
        int start = 0;
        int end = 1023;
        while (end < command.length) {
          print(command.substring(start, end) + "\n");
          start += 1024;
          end += 1024;
        }
        print(command.substring(start));
      } else {
        print("flutter xfdfCommand:\n $command");
      }
    });

    // An event listener for when local bookmark changes are committed to the document.
    // bookmarkJson is JSON string containing all the bookmarks that exist when the change was made.
    var bookmarkCancel = startExportBookmarkListener((bookmarkJson) {
      print("flutter bookmark: $bookmarkJson");
    });

    var path = await PdftronFlutter.saveDocument();
    print("flutter save: $path");

    // To cancel event:
    // annotCancel();
    // bookmarkCancel();
    // documentLoadedCancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child:
            // Uncomment this to use Widget version of the viewer.
            // _showViewer
            // ? DocumentView(
            //     onCreated: _onDocumentViewCreated,
            //   ):
            Container(),
      ),
    );
  }

  // This function is used to control the DocumentView widget after it has been created.
  // The widget will not work without a void Function(DocumentViewController controller) being passed to it.
  void _onDocumentViewCreated(DocumentViewController controller) async {
    Config config = new Config();

    var leadingNavCancel = startLeadingNavButtonPressedListener(() {
      // Uncomment this to quit the viewer when leading navigation button is pressed.
      // this.setState(() {
      //   _showViewer = !_showViewer;
      // });

      // Show a dialog when leading navigation button is pressed.
      _showMyDialog();
    });

    controller.openDocument(_document, config: config);
  }

  Future<void> _showMyDialog() async {
    print('hello');
    return showDialog<void>(
      context: context,
      barrierDismissible: false, // User must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('AlertDialog'),
          content: SingleChildScrollView(
            child: Text('Leading navigation button has been pressed.'),
          ),
          actions: <Widget>[
            TextButton(
              child: Text('OK'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }
}

Changelog

See Changelog

Contributing

See Contributing

License

See License

More Repositories

1

webviewer-ui

WebViewer UI built in React
JavaScript
405
star
2

pdftron-sign-app

Sign and request signatures on PDFs, MS Office documents
JavaScript
198
star
3

webviewer-react-sample

Sample to demonstrate integrating WebViewer into React
JavaScript
156
star
4

pdftron-react-native

A convenience wrapper for building react native apps with PDFTron mobile SDK.
Objective-C
106
star
5

webviewer-vue-sample

Sample to demonstrate integrating WebViewer into Vue
Vue
99
star
6

pdftron-android-samples

PDFTron Android Samples
Kotlin
57
star
7

web-to-pdf

Convert any web technology to PDF (HTML to PDF, html2pdf)
JavaScript
52
star
8

PDFNetWrappers

Code repository for building different language bindings for PDFNetC.
SWIG
48
star
9

webviewer-video-sample

Annotate videos frame-by-frame collaboratively
JavaScript
44
star
10

pdftron-document-search

Build search across multiple documents client-side in your file storage
JavaScript
42
star
11

webviewer-angular-sample

Sample to demonstrate integrating WebViewer into Angular
TypeScript
41
star
12

webviewer-salesforce

LWC component to view, annotate and edit PDFs, MS Office, images in Salesforce
JavaScript
38
star
13

pdftron-android-ocr-scanner-sample

Android Scanner with OCR support using PDFTron
Kotlin
31
star
14

webviewer-react-toolkit

A React component library for integrating with PDFTron WebViewer API.
TypeScript
24
star
15

rails-generate-pdf

rails-generate-pdf
Ruby
21
star
16

webviewer-realtime-collaboration-sqlite3-sample

WebViewer sample to show how you can create a real time collaboration app with WebViewer using WebSocket, SQLite3, and Node.js server.
JavaScript
20
star
17

webviewer-electron-sample

Sample to demonstrate integrating WebViewer into an Electron App
JavaScript
19
star
18

webviewer-nextjs-sample

CSS
14
star
19

pdftron-go

PDFTron GoLang
Go
14
star
20

pdftron-cordova

A plugin for building Cordova and Ionic apps with PDFTron's iOS and Android native PDF SDKs.
Java
13
star
21

pdf-in-react

Boilerplate for rendering a PDF using React
JavaScript
13
star
22

webviewer-barcode

Stamp and read barcodes using WebViewer SDK
JavaScript
13
star
23

webviewer-custom-ui

Demonstrates how to get started with making your own UI
JavaScript
13
star
24

webviewer-3d-sample

View, annotate and collaborate on GLB, GLTF models
CSS
11
star
25

Android-Getting-Started

Shows how to view and annotate a PDF on Android using PDFNet.
Java
11
star
26

android-pdf-viewer

Blog: How to Build an Android PDF Viewer Using Java
Java
9
star
27

webviewer-document-merge

Drag and drop PDFs, MS Office, images to assemble documents.
JavaScript
9
star
28

webviewer-blazor-sample

A sample project demonstrating how to integrate PDFTron's WebViewer into a Blazor server project
HTML
9
star
29

pdf-viewer-android

Android Quick Start Guide: Add a document viewer using the PDFTron Android SDK
Java
9
star
30

pdf-viewer-swift

Boilerplate for adding a PDF viewer to a Swift app.
Swift
9
star
31

xamarin-forms-sample

This sample shows how to use PDFTron for Xamarin in Xamarin.Forms project via PageRenderer. You can run this sample on Android, iOS and UWP. It shows a simple PDFViewCtrl with annotation functionality.
C#
9
star
32

flutter-sample

Sample to demonstrate integrating PDFTron in Flutter
Dart
8
star
33

salesforce-pdf-app

Demo app for showcasing file upload/handling, searching, ContentReplacer, Redaction etc.
Apex
8
star
34

webviewer-cordova-sample

A sample WebViewer app in Cordova/Ionic.
CSS
7
star
35

salesforce-webviewer-attachments

JavaScript
7
star
36

webviewer-blazor-wasm-sample

A sample project demonstrating how to integrate PDFTron's WebViewer into a Blazor WebAssembly project
HTML
7
star
37

webviewer-svelte-sample

Sample to demonstrate integrating WebViewer into Svelte
JavaScript
7
star
38

iOS-Getting-Started

Shows how to view and annotate a PDF on iOS using PDFNet.
Objective-C
7
star
39

webviewer-annotations-php-sample

WebViewer sample that shows saving annotations to XFDF files in PHP
JavaScript
6
star
40

ng5-pdf-viewer-ui

ng5-pdf-viewer-ui
TypeScript
6
star
41

pdftron-android-blogs

This repository contains sample projects that accompany relevant PDFTron Android blog posts.
Kotlin
6
star
42

webviewer-annotations-document-sample

WebViewer sample that shows saving annotations back to PDF file in Node.js
JavaScript
6
star
43

react-native-sample

Sample to demonstrate integrating PDFTron in React Native
TypeScript
6
star
44

webviewer-typescript-sample

JavaScript
6
star
45

webviewer-generate-docx

Generate DOCX, and save as a PDF, all client-side in the browser.
JavaScript
6
star
46

pdfjs-express-typescript

JavaScript
5
star
47

webviewer-html-annotate-proxy

JavaScript
5
star
48

nodejs-mail-to-pdf

Convert emails EML to a PDF with all attachments
JavaScript
5
star
49

webviewer-html-annotate

Annotate live HTML web pages by providing URL
JavaScript
5
star
50

webviewer-user-bookmarks-nodejs-sample

WebViewer sample that shows saving user bookmarks to a json file in nodejs
JavaScript
5
star
51

pdftron-react-and-react-native-sample

A sample project that uses Expo and shows how to create a PDF viewer app for both web and mobile with a single codebase between React and React Native.
Java
5
star
52

PDFNetLoader

.Net assembly to load 32 or 64 bit PDFNet at runtime. This allows for easier intergration with the AnyCPU platform.
C#
5
star
53

webviewer-typescript

JavaScript
4
star
54

webviewer-mendix-sample

Mendix PDF, MS Office, image viewer and editor. Review and approve, annotate documents, split/merge pages.
TypeScript
4
star
55

pdftron-android-barcode

Stamp and read barcodes using PDFTron Android SDK
Kotlin
4
star
56

webviewer-annotations-nodejs-sample

WebViewer sample that shows saving annotations to XFDF files in Node.js
JavaScript
4
star
57

webviewer-react-toolkit-demo

An example implementation of WebViewer React Toolkit.
TypeScript
4
star
58

webviewer-salesforce-apex-example

WebViewer demo in Lightning Web Component (LWC) and Apex class in Salesforce
JavaScript
4
star
59

webviewer-annotations-aspnet-sample

WebViewer sample that shows saving annotations to XFDF files in ASP.NET
C#
4
star
60

angular-pdf-ui

angular-pdf-ui
JavaScript
3
star
61

pdfjs-typescript

JavaScript
3
star
62

pdftron-apple-package

PDFTron iOS Swift Package
Swift
3
star
63

website-reviewer

A sample application showing how to combine PDFTron technology to build a website reviewal app
TypeScript
3
star
64

webviewer-offline-sample

CSS
3
star
65

webviewer-js-sample

A simple JS application demonstrating how to embed PDFTron's WebViewer
JavaScript
3
star
66

cordova-sample

This project is no longer maintained. Please see https://github.com/PDFTron/webviewer-cordova-sample.
Java
3
star
67

webviewer-collab-advanced-sample

A sample project using the WebViewer Collaboration modules
TypeScript
2
star
68

webviewer-audio-sample

CSS
2
star
69

salesforce-webviewer-diff

A semantic diff sample for WebViewer in Salesforce
JavaScript
2
star
70

webviewer-appian-sample

Appian PDF, MS Office, image viewer and editor. Review and approve, annotate documents, split/merge pages.
JavaScript
2
star
71

salesforce-webviewer-scorpio

Spinoff of https://github.com/PDFTron/salesforce-webviewer-attachments with compatability to S3 links. Added modifications to work with LMS and to auto load most recently created attachment
JavaScript
2
star
72

webviewer-html-proxy-server

TypeScript
2
star
73

webviewer-cors

Load WebViewer's lib on a different domain
TypeScript
2
star
74

pdftron-uwp-samples

C#
2
star
75

aws-function-example

Example code for using PDFTron SDK in an AWS Lambda.
Python
2
star
76

webviewer-flutter-sample

Sample to demonstrate integrating WebViewer into Flutter Web
Dart
2
star
77

pdftron-winui-samples

Sample projects using PDFTron's WinUI SDK
C#
2
star
78

webviewer-server-side-search

Sample code for integrating server side search for PDFTron WebViewer
JavaScript
2
star
79

webviewer-jquery-sample

A sample project demonstrating how to integrate PDFTron's WebViewer into a jQuery project
JavaScript
2
star
80

pdftron-xamarin-samples

PDFTron Xamarin Samples
C#
2
star
81

webviewer-react

TypeScript
2
star
82

pdftron-ios-samples

Swift
2
star
83

webviewer-angularjs-sample

JavaScript
2
star
84

webviewer-angular-azure-sample

Sample to demonstrate integrating WebViewer into an Angular & Azure App
TypeScript
2
star
85

sharepoint-integration

JavaScript
1
star
86

salesforce-webviewer-document-merge

JavaScript
1
star
87

sharepoint-integration-examples

TypeScript
1
star
88

salesforce-webviewer-prepopulate

JavaScript
1
star
89

DotNetCore-GettingStarted

1
star
90

pdftron-apple-package-no-tools

Swift
1
star
91

salesforce-webviewer-video

JavaScript
1
star
92

webviewer-collab-sql-sample

A basic sample showing how to integrate WebViewer Collaboration modules with an SQL database
TypeScript
1
star
93

webviewer-collab-get-started

The repo containing the code for the WebViewer Collaboration get started guide
JavaScript
1
star
94

salesforce-webviewer-docgen

JavaScript
1
star
95

canvasToPDF-webviewer-react-sample

JavaScript
1
star
96

webviewer-codesandbox-samples

A repository that is used for showcasing PDFTron WebViewer samples in CodeSandbox
1
star
97

webviewer-tomcat-java-sample

Sample to demonstrate integrating WebViewer into an Tomcat Java App
HTML
1
star
98

react-ab

A powerful AB testing suite for React projects
TypeScript
1
star
99

webviewer-microsoft-teams-samples

Sample projects on how to integrate PDFTron's Webviewer with Microsoft Teams
TypeScript
1
star
100

flutter-unified-web-mobile-sample

Dart
1
star