August 14, 2021

How to create PDF in flutter using pdf package

By lj007

We will create PDF file in flutter using pdf package. I am using this package from pub.dev site. This package is easy to use and very similar to flutter widgets tree, so It will be fun. We will follow simple step to create our basic pdf file.

Steps:

  1. add-package
  2. Import Package
  3. Create PDF
  4. Save PDF

Add Package

Adding package in flutter as easy as adding plugin in wordpress, just one line of code and you are ready to use package (If Package author does not provide any specification about particular platform setup).

dependencies:

  ..
  path_provider: ^2.0.2
  pdf: ^3.4.2

Import Package

We need to import package manually if editor not showing suggestion when we write code, I am using android studio and it shows suggestion. When we select from suggestion it will automatically import package, but if it fails we can manually import package.

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

Create PDF

We are ready to create our pdf file. I have create one simple pdf with very common widget. Note that pdf package uses their own widget not flutter, because I was confused when first time I have used it.

final pdf = pw.Document();
    pdf.addPage(
      pw.Page(
        pageFormat: PdfPageFormat.a4,
        build: (context) {
          return pw.Column(
            children: [
              pw.Row(
                children: [
                  pw.Text('Report Generated At:'),
                  pw.Text(getDateText(DateTime.now().millisecondsSinceEpoch)),
                ],
              ),
            ]
          );
        },
      ),
    );

Save PDF

Creating pdf is not enough for application, we might need to save it for later use.

    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path;

    final file = File(appDocPath + "/" +DateTime.now().millisecondsSinceEpoch.toString() + ".pdf");
    print("file Path : ${file.path}");
    await file.writeAsBytes(await pdf.save());

I have used path_provider package to get default application save path.

Open PDF file

To open pdf file we need to add another package nape OpenFile, Then we finished our pdf creation.

OpenFile.open(file.path);