PDF with Flutter – Part 1

By 5 June 2020 June 8th, 2020 One Comment

PDF with Flutter – Part 1

Sharing is caring!

PDF with Flutter – Part 1

As we know, Google has provide the Flutter framework for X-platform application development, including for both mobile and web. I was working on the project where generating the PDF from given data is one of the vital tasks in that. Not only generating a pdf, but also viewing it is of same importance. So first, we will look into how to create PDF in flutter, then how can we view it in mobile and web.

Creating a PDF in Flutter

The package pdf let us create a PDF with ease. You can find the info related to package installation here.

The important thing to note here is widgets provided by the pdf package and the usual widgets from material package are conflicting:


So when you have both material and pdf package imported, you need to use ‘as’ for one of the import directive. Then you can access it like shown in below screenshot:


But having all the tens or hundreds of widgets accessed with ‘pdf.’ Is bad idea. So we go ahead and create our helper class to deal with PDF Generation.

PdfGenerator Class:

We prevent to import Material and Cupertino or any other package in this class that might be conflicting with the Pdf package.

It takes just 3 steps to generate pdf:

  1. Create a blank document.
  1. Add page or pages to blank document. Use:

Page – for single page pdf

Multipage – if you want more than one page, good for dynamic data such as list.

Avoid use of ListView. Instead you just need to put widget directly inside Multipage build context.

  1. Save the doc and get your PDF as bytes array.

Following code illustrate the sample use case of pdf generation:


Viewing a generated PDF in Mobile

We a file in mobile is easy with two packages: path_provider and open_file

We also use File class from dart:io package as mobile is concerned.

So we have 3 new imports:


 Now it takes just 4 lines of code to view pdf on mobile:


 Call the Function:


Finally, call the PdfGenerator from any other route in your app to see the output:




Viewing the generated pdf on web need to handle differently. Please have a look at part 2 of this article where I shared my experience for opening  a pdf bytes array on flutter web.

One Comment

Leave a Reply

Get started with Bloom