Skip to content
Related Articles

Related Articles

Flutter – Simple PDF Generating App
  • Last Updated : 15 Jan, 2021

Flutter Community has created several packages to work with PDFs in our apps. In this article, we will be creating a simple PDF generating app. This application will convert a plain text to PDF. The package that we are going to need are listed below with their uses:

  • pdf: It is a PDF creation library for flutter. It can create a full multi-page document with images, tables, different fonts etc.
  • flutter_full_pdf_viewer: It is used to preview the PDF.
  • path_provider: It is used for finding commonly used locations on the file system.

Now let’s do some coding.

First, we have to install the necessary packages in the dependencies section of pubspec.yaml file as shown below:

pubspec.yaml ss

1. PDF Preview Screen Page:

Now that the packages are installed first we are going to create PDF preview screen as new dart file(pdf_preview_screen.dart) with the given path as shown below:



Dart




import 'package:flutter/material.dart';
import 'package:flutter_full_pdf_viewer/flutter_full_pdf_viewer.dart';
  
class PdfPreviewScreen extends StatelessWidget {
  final String path;
  
  PdfPreviewScreen({this.path});
  
  @override
  Widget build(BuildContext context) {
    return PDFViewerScaffold(
      path: path,
    );
  }
}

In this page we have created PDFPreviewScreen as a StatelessWidget with the path of the PDF file as the parameter.

2. Main Page :

We have imported the necessary packages for creating the desired layout. Here we have imported ‘package:pdf/widgets.dart‘ as pw because the material package already has a widget class.

Dart




import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:pdf_demo/pdf_preview_screen.dart';

This is the main function which is called when the app starts:

Dart




void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'PDF Demo',
      theme: ThemeData(
        primarySwatch: Colors.grey,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

The widget package from pdf has different types of widget for creating the desired layout. MyHomePage() is a StatelessWidget which contains the code for PDF creation. Now we are going to add content to the app. We will be creating a function writeOnPdf() for this purpose:

Dart




class MyHomePage extends StatelessWidget {
  final pdf = pw.Document();
  
  writeOnPdf() {
    pdf.addPage(pw.MultiPage(
      pageFormat: PdfPageFormat.a4,
      margin: pw.EdgeInsets.all(32),
      build: (pw.Context context) {
        return <pw.Widget>[
          pw.Header(
              level: 0,
              child: pw.Row(
                  mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
                  children: <pw.Widget>[
                    pw.Text('Geeksforgeeks', textScaleFactor: 2),
                  ])),
          pw.Header(level: 1, text: 'What is Lorem Ipsum?'),
            
          // Write All the paragraph in one line. 
          // For clear understanding
          // here there are line breaks.
          pw.Paragraph(
              text:
                  'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
                  tempor incididunt ut labore et dolore magna aliqua. Nunc mi ipsum faucibus
                  vitae aliquet nec. Nibh cras pulvinar mattis nunc sed blandit libero
                  volutpat. Vitae elementum curabitur vitae nunc sed velit. Nibh tellus
                  molestie nunc non blandit massa. Bibendum enim facilisis gravida neque.
                  Arcu cursus euismod quis viverra nibh cras pulvinar mattis. Enim diam
                  vulputate ut pharetra sit. Tellus pellentesque eu tincidunt tortor
                  aliquam nulla facilisi cras fermentum. '),
          pw.Paragraph(
              text:
                  'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
                  tempor incididunt ut labore et dolore magna aliqua. Nunc mi ipsum faucibus
                  vitae aliquet nec. Nibh cras pulvinar mattis nunc sed blandit libero
                  volutpat Vitae elementum curabitur vitae nunc sed velit. Nibh tellus
                  molestie nunc non blandit massa. Bibendum enim facilisis gravida neque.
                  Arcu cursus euismod quis viverra nibh cras pulvinar mattis. Enim diam
                  vulputate ut pharetra sit. Tellus pellentesque eu tincidunt tortor
                  aliquam nulla facilisi cras fermentum. '),
          pw.Header(level: 1, text: 'This is Header'),
          pw.Paragraph(
              text:
                  'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
                  tempor incididunt ut labore et dolore magna aliqua. Nunc mi ipsum faucibus
                  vitae aliquet nec. Nibh cras pulvinar mattis nunc sed blandit libero
                  volutpat. Vitae elementum curabitur vitae nunc sed velit. Nibh tellus
                  molestie nunc non blandit massa. Bibendum enim facilisis gravida neque.
                  Arcu cursus euismod quis viverra nibh cras pulvinar mattis. Enim diam
                  vulputate ut pharetra sit. Tellus pellentesque eu tincidunt tortor aliquam
                  nulla facilisi cras fermentum. Consectetur adipiscing elit duis tristique
                  sollicitudin nibh sit. '),
          pw.Paragraph(
              text:
                  'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
                  tempor incididunt ut labore et dolore magna aliqua. Nunc mi ipsum faucibus
                  vitae aliquet nec. Nibh cras pulvinar mattis nunc sed blandit libero
                  volutpat. Vitae elementum curabitur vitae nunc sed velit. Nibh tellus
                  molestie nunc non blandit massa. Bibendum enim facilisis gravida neque.
                  Arcu cursus euismod quis viverra nibh cras pulvinar mattis. Enim diam
                  vulputate ut pharetra sit. Tellus pellentesque eu tincidunt tortor aliquam
                  nulla facilisi cras fermentum. Consectetur adipiscing elit duis tristique
                  sollicitudin nibh sit. '),
          pw.Padding(padding: const pw.EdgeInsets.all(10)),
          pw.Table.fromTextArray(context: context, data: const <List<String>>[
            <String>['Year', 'Sample'],
            <String>['SN0', 'GFG1'],
            <String>['SN1', 'GFG2'],
            <String>['SN2', 'GFG3'],
            <String>['SN3', 'GFG4'],
          ]),
        ];
      },
    ));
  }

The widgets available in this package are not the same as that available in material package. They are used to structure the layout of the document. Here we have created the document with some header, paragraphs and table to show how the basic structuring can be created.

Dart




Future savePdf() async {
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    String documentPath = documentDirectory.path;
    File file = File("$documentPath/example.pdf");
    file.writeAsBytesSync(pdf.save());
  }

The savePdf() function is used to save the PDF which is later on used to preview the document from the path provided. After writing the above lines of code we have to rerun the app.

The above below code is for the screen which we will get after running the app. It contains an App Bar along with a Raised Button which is used to generate and preview the PDF we have created by writing the above line of code. We pass an async function to onPressed parameter of the button as the file location is needed which returns a future as already stored while saving the file. This is also the end of the MyHomePage class.

Dart




Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Geeksforgeeks"),
      ),
      body: Container(
        padding: EdgeInsets.all(10),
        child: Column(
          children: <Widget>[
            SizedBox(
              width: double.infinity,
              child: RaisedButton(
                color: Colors.blueGrey,
                child: Text(
                  'Preview PDF',
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 18,
                      color: Colors.white),
                ),
                onPressed: () async {
                  writeOnPdf();
                  await savePdf();
  
                  Directory documentDirectory =
                      await getApplicationDocumentsDirectory();
  
                  String documentPath = documentDirectory.path;
  
                  String fullPath = "$documentPath/example.pdf";
                  print(fullPath);
  
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => PdfPreviewScreen(
                                path: fullPath,
                              )));
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Output:

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!
My Personal Notes arrow_drop_up
Recommended Articles
Page :