Creating PDFs in Flutter: A Step-by-Step Guide

When it comes to sharing documents, there’s no better way than using a PDF. In this article, we’ll explore how to create PDFs in Flutter, a popular framework for building mobile apps.

Why Use PDFs?

PDFs are widely used due to their versatility and compatibility with various devices and operating systems. They’re ideal for sharing documents, invoices, and other types of content that need to be displayed consistently across different platforms.

Setting Up a Flutter App for PDF Creation

To start creating PDFs in Flutter, you’ll need to add the pdf and printing packages to your project. These packages provide the necessary functionality for generating and printing PDFs.

Configuring the pubspec.yaml File

In your pubspec.yaml file, add the following dependencies:
yaml
dependencies:
flutter:
sdk: flutter
pdf: ^2.0.0
printing: ^2.0.0

Creating a Data Model for Invoices

Next, create a data model for your invoices. This will help you store and manage the data that will be used to generate the PDFs.
“`dart
class Invoice {
String customerName;
String customerAddress;
List items;

Invoice({this.customerName, this.customerAddress, this.items});

double get totalCost {
return items.fold(0, (total, item) => total + item.cost);
}
}

class InvoiceItem {
String name;
double cost;

InvoiceItem({this.name, this.cost});
}
“`
Creating the PDF

Now, let’s create the PDF using the pdf package. We’ll use a simple example to demonstrate how to generate a PDF invoice.
“`dart
import ‘package:pdf/pdf.dart’;
import ‘package:pdf/widgets.dart’;

class PdfExport {
static Future> makePdf(Invoice invoice) async {
final pdf = Document();
pdf.addPage(
Page(
build: (context) {
return Column(
children: [
Text(invoice.customerName),
Text(invoice.customerAddress),
Table(
border: TableBorder.all(color: Colors.black),
children: [
TableRow(
children: [
Text(‘Item’),
Text(‘Cost’),
],
),
…invoice.items.map((item) {
return TableRow(
children: [
Text(item.name),
Text(‘\$${item.cost.toString()}’),
],
);
}),
],
),
Text(‘Total: \$${invoice.totalCost.toString()}’),
],
);
},
),
);
return await pdf.save();
}
}
“`
Creating the PDF Preview Page

Finally, let’s create a simple page to display the PDF preview using the printing package.
“`dart
import ‘package:flutter/material.dart’;
import ‘package:printing/printing.dart’;

class PdfPreviewPage extends StatelessWidget {
final Invoice invoice;

PdfPreviewPage({this.invoice});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(‘PDF Preview’),
),
body: PdfPreview(
build: (context) {
return PdfExport.makePdf(invoice);
},
),
);
}
}
“`
That’s it! With these steps, you should now have a basic understanding of how to create PDFs in Flutter. You can customize the PDF layout and design to suit your needs, and even add more features like printing and sharing.

Leave a Reply

Your email address will not be published. Required fields are marked *