Flutter PDF - Create Pdf and Read From Internet, Storage or Asset

Follow @desiprogrammer_

Reading PDF Files

First, we need to add the following plugins to our pubspec.yaml file And then fetch all the plugins. The pdf_flutter plugin will be used to read and display PDF files. The file_picker plugin will be used to pick a file from the local storage.
Now the path_provider plugin and the pdf plugin well together help us in creating and saving a PDF file as path provider plugin will give us a path to save our file and the PDF plugin will help us in creating a PDF file.


  pdf_flutter: ^1.1.3
  file_picker: ^1.13.3
  
  pdf: ^1.10.1
  path_provider: ^1.6.11
        

Working with pdf_flutter is very simple and here are quick examples on how you can open a file from the internet, from the assets or how you can pick a file using the file_picker plugin and then display the file content using PDF plugin.
I have allowed only the PDF extension in file_picker to make sure that we don't end up getting errors

To Open a File from internet


  PDF.network(
      // file url
     'http://africau.edu/images/default/sample.pdf',
     // optional height and width
     height: 600,
     width: MediaQuery.of(context).size.width * 0.90,
  ),
        

To Open a File from asset


  PDF.assets('assets/dummypdf.pdf'),
        

To Open a File from Local Storage


  import 'dart:io';
  // declare a File variable
  File localfile;
  
  // to view a file only if a file is picked
  localfile != null
  ? PDF.file(
      localfile,
      height: 600,
      width: MediaQuery.of(context).size.width * 0.90,
    )
  : RaisedButton(
      child: Text("Grab A File"),
      onPressed: () async {
        File pickedFile = await FilePicker.getFile(
            allowedExtensions: ['pdf'], type: FileType.custom);
        setState(() {
          localfile = pickedFile;
        });
      },
    ),

        

Creating PDF Files

Let's talk about creating the PDF and to do that we will create a function named generateFile that will use the PDF widgets provided by the pdf plugin to create a PDF file.
Here we have a doc variable which is a PDF widget document We will add a page to our PDF document with the page format as A4 and we will build the page. The best part is that the entire page structure can we built using normal flutter widgets the only difference being that they will be provided by the PDF widget. For example we will add a column then a center with some dummy text.


  // import the packages
  import 'package:path_provider/path_provider.dart';
  import 'package:pdf/pdf.dart';
  import 'package:pdf/widgets.dart' as pw;

  // a dcoument variable decalration
  final doc = pw.Document();
  
  // the function
  void generateFile() async {
   doc.addPage(pw.Page(
       pageFormat: PdfPageFormat.a4,
       build: (pw.Context context) {
         return pw.Column(
           mainAxisAlignment: pw.MainAxisAlignment.center,
           children: [
             pw.Center(
               child: pw.Text("Dummy PDF",
                   style: pw.TextStyle(
                     fontSize: 50.0, 
                   ),
                ),
             ),
           ],
         ); 
       }
    ),
  ); 
            
        

Then we have to save our document.
For that, First we will get the getExternalStorageDirectory path and will add a filename to that. We will then use File to create file at that path and will save the doc and will write that to our file.
I will simply print the pdf path so that you can go and check if the file exists there.


  final outPut = await getExternalStorageDirectory();

  String path = outPut.path + '/example.pdf';
  final file = File(path);
  file.writeAsBytesSync(doc.save());
  
  print(outPut.path);
        

If You face Errror In Release Follow This.