Generate PDFs in Flutter: Create, Share and View

- Andrés Cruz

En español

PDFs (Portable Document Format) are the quintessential scheme for sharing texts with formats in a file, they are easy to interpret and do not require a proprietary program as in the case of Microsoft Word files. PDFs, being a ready-made format and without the possibility of modifying them (although they can be modified with some specific programs) as if they were an image, are an excellent way to share documents in mobile and desktop applications and in no way in They can generally be missing, and in Flutter we are lucky since they can be used very easily.

1. Initial Configuration

Before starting to develop, we must configure the plugin or pub in our project:

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  pdf: 
  printing: 
  • pdf: This library allows us to create and edit PDFs in Flutter.
  • printing: Allows us to preview, share and print the PDFs generated from our application.

2. Creating an Invoice Template

Let's say you want to generate invoices for your clients, which is the most common approach for wanting to share and generate PDFs in Flutter. First, create a data model to represent an invoice. You can include relevant information such as the name of the client, the invoice items and the total to be paid, this template can be anything depending on your needs such as a publication.

3. Designing the Interface

Design a user interface where users can enter invoice details. Use widgets like TextFormField, ListView, and RaisedButton to capture the necessary information. This step is optional since it may be some static data or data that comes from a database or similar, so it is not important for the creation of the pdf and depends on your needs or those of the project.

4. Generating the PDF

This step is essential and the PDF must be generated, which is the important factor in this entry so, once you have the invoice data, we are going to generate the PDF with the previous packages, using the installed PDF library Before, we created a special widget that, through a tree of widgets, allows us to generate the PDF document; you can use any type of Flutter visual widget for this task to generate texts, images, tables, etc.:

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

// ...

final pdf = pw.Document();
pdf.addPage(
  pw.Page(
    build: (context) {
      return pw.Center(
        child: pw.Text('Factura para Cliente X'),
      );
    },
  ),
);

5. Preview and Sharing

With the PDF generated, it is time to use the printing library to preview the PDF before saving it or sending it to the client. You can display it in a PdfPreview or even email it directly from your app:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
      
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
             
              final response = await http.get('http://example.com/sample.pdf');
              final pdfData = response.bodyBytes;

              await Printing.layoutPdf(onLayout: (PdfPageFormat format) async => pdfData);
            },
            child: Text('Show PDF'),
          ),
        ),
      ),
    );
  }
}
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.