Flutter PDF viewer implementation for beginners

 

Flutter PDF Viewer:

Flutter PDF viewer is used to read the files ending with the extension ‘.pdf ‘ because pdf is a reliable format for exchanging documents providing a proper security mechanism.

These files can contain audio, video and more graphical representation files like GIF, Charts, Vector Graphics.

These can be included in the documents they can be signed electronically too for avoiding unwanted access to these files.

Some times PDF format is preferred to avoid alignment issues in the document like a MS Word where we create a file in windows which can be easily viewed in mac system too.

Not only in desktops but these files are much easily accessed in mobile devices of different resolution.

And also these are easy to mail or share them because of the less file size and also word file can cause alignment issues when used on multiple systems but pdf won’t.

 

Flutter PDF Viewer Video Tutorial :

You can watch the video tutorial below for a more detailed explanation of the PDF viewer implementation

 

 

pubspec.yaml :

Add flutter_plugin_pdf_viewer dependency to pubspec for Flutter PDF viewer implementation

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_plugin_pdf_viewer: ^1.0.7

 

 

Add sample pdf file to folder

flutter:
  uses-material-design: true
  assets:
    - assets/sample.pdf

 

 

main.dart :

Initialize with void main()

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

 

Create a state for the class using this state we can refresh the view

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

 

 

Declare variables boolean for progress bar display and also PDFDocument to display pdf document on your screen.

bool _isLoading = true; 
PDFDocument document;

 

 

Add a init() block where we are loading document on app start with the help of loadDocument()

@override
void initState() {
  super.initState();
  loadDocument();
}

 

 

Load asynchronously pdf file from assets folder(local folder in app) in below way displaying a progress bar until the data is displayed i.e., pdf file is completely loaded.

loadDocument() async {
  document = await PDFDocument.fromAsset('assets/sample.pdf');
  setState(() => _isLoading = false);
}

 

 

Add two buttons using which we can either select the PDF file from local file or from a api provided.Here you can also automate the process based on your requirement as we did initially did in init().

RaisedButton(
  onPressed: () {
    changePDF(1);
  },
  child: Text("Load from assets pdf"),
),
RaisedButton(
  onPressed: () {
    changePDF(2);
  },
  child: Text("Load from URL pdf"),
),

 

 

Also add a container using which we can load pdf file in app i.e., pdf viewer required screen size here we are providing a height of 400 for the container.

Container(
  height: 400,
  child: PDFViewer(document: document),
),

 

 

Add a asynchronous method to select either way to open document

changePDF(value) async {
  setState(() => _isLoading = true);
  if (value == 1) {
    document = await PDFDocument.fromAsset('assets/sample.pdf');
  } else {
    document = await PDFDocument.fromURL(
        "http://www.africau.edu/images/default/sample.pdf");
  }
  setState(() => _isLoading = false);
}

 

 

 

Flutter PDF Viewer Full Code :

Below is the complete code for implementing a PDF viewer in Flutter.

import 'package:flutter/material.dart';
import 'package:flutter_plugin_pdf_viewer/flutter_plugin_pdf_viewer.dart';

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

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

class _MyAppState extends State<MyApp> {
  bool _isLoading = true;
  PDFDocument document;

  @override
  void initState() {
    super.initState();
    loadDocument();
  }

  loadDocument() async {
    document = await PDFDocument.fromAsset('assets/sample.pdf');

    setState(() => _isLoading = false);
  }

  changePDF(value) async {
    setState(() => _isLoading = true);
    if (value == 1) {
      document = await PDFDocument.fromAsset('assets/sample.pdf');
    } else {
      document = await PDFDocument.fromURL(
          "http://www.africau.edu/images/default/sample.pdf");
    }
    setState(() => _isLoading = false);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter PDF Viewer'),
        ),
        body: Center(
          child: Container(
            child: Column(
              children: [
                RaisedButton(
                  onPressed: () {
                    changePDF(1);
                  },
                  child: Text("Load from assets pdf"),
                ),
                RaisedButton(
                  onPressed: () {
                    changePDF(2);
                  },
                  child: Text("Load from URL pdf"),
                ),
                Container(
                  height: 400,
                  child: PDFViewer(document: document),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

 

 

Flutter PDF Viewer Output :

The following screen demonstrates the implementation of the Flutter PDF viewer.

Flutter pdf viewer

If you have any questions about the PDF viewer tutorial, feel free to ask in the comments. If you found it helpful, please like and share for more updates

 

Show Buttons
Hide Buttons
Read previous post:
Flutter video background on Login Page

  Flutter Video Background : Flutter Video Background screen is used to display a video on background and screen components...

Close