Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 73 ยท Platform integration

Generating and Previewing PDFs, File Pickers

Generate PDFs with the pdf package, preview and share them with printing, save files with path_provider, pick files with file_picker, and paginate tables correctly.

Invoices, tickets, reports and certificates are all PDFs, and apps often need to read documents the user already owns. Flutter handles this with a few focused packages: pdf builds a document in Dart, printing previews, prints and shares it, path_provider finds folders where you may save files, and file_picker lets the user choose a file. The PDF is built in memory as bytes, so it works the same on mobile, desktop and web.

Real vs stand-in. The Dart is real and read-only, because the site cannot write files or open a native file chooser from Flutter. Package APIs change between versions, so confirm names on pub.dev. The live examples are JavaScript stand-ins of the logic you write yourself: money in whole cents, and splitting table rows across pages.

Building a PDF

The pdf package has its own widget tree, imported with a prefix so it does not clash with Flutter widgets (pw.Text is not Text). The document is a list of pages.

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

Future<Uint8List> buildInvoice(Invoice invoice) async {
  final doc = pw.Document();

  doc.addPage(
    pw.Page(
      pageFormat: PdfPageFormat.a4,
      margin: const pw.EdgeInsets.all(32),
      build: (pw.Context context) => pw.Column(
        crossAxisAlignment: pw.CrossAxisAlignment.start,
        children: [
          pw.Text('Invoice ${invoice.number}', style: pw.TextStyle(fontSize: 24, fontWeight: pw.FontWeight.bold)),
          pw.SizedBox(height: 16),
          pw.Text('Billed to: ${invoice.customer}'),
          pw.Divider(),
          pw.Text('Total: ${invoice.totalFormatted}'),
        ],
      ),
    ),
  );

  return doc.save();    // the PDF file's bytes
}

pw.Page fits one page; content that is too tall throws a TooManyPagesException. For long content use pw.MultiPage, whose build returns a list of widgets that the package flows across pages, with optional header and footer builders.

DART
doc.addPage(
  pw.MultiPage(
    pageFormat: PdfPageFormat.a4,
    header: (ctx) => pw.Text('Acme Ltd'),
    footer: (ctx) => pw.Align(
      alignment: pw.Alignment.centerRight,
      child: pw.Text('Page ${ctx.pageNumber} of ${ctx.pagesCount}'),
    ),
    build: (ctx) => [
      pw.Header(level: 0, child: pw.Text('Statement')),
      pw.TableHelper.fromTextArray(
        headers: ['Item', 'Qty', 'Price'],
        data: [for (final l in invoice.lines) [l.name, '${l.qty}', l.priceFormatted]],
      ),
    ],
  ),
);

Fonts and non-Latin text

The default PDF fonts cover basic Latin only. For accents, Cyrillic, Greek or CJK, embed a font; otherwise characters become blanks or errors:

DART
final data = await rootBundle.load('assets/fonts/NotoSans-Regular.ttf');
final font = pw.Font.ttf(data);
final theme = pw.ThemeData.withFont(base: font);
final doc = pw.Document(theme: theme);

Declare the font in pubspec.yaml like any asset (assets). Right-to-left scripts need extra care and a font with the right shaping.

JS Money in cents, then format once

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Previewing, printing and sharing

printing turns the bytes into something the user can see and send.

DART
// A preview screen with print, share and page-format controls:
PdfPreview(
  build: (PdfPageFormat format) => buildInvoice(invoice),
  allowPrinting: true,
  allowSharing: true,
  pdfFileName: 'invoice-${invoice.number}.pdf',
)

// Or act directly:
await Printing.layoutPdf(onLayout: (format) => buildInvoice(invoice));         // system print dialog
await Printing.sharePdf(bytes: bytes, filename: 'invoice-${invoice.number}.pdf');

PdfPreview rebuilds when the user changes the paper size, which is why build receives the format. Build the bytes once and keep them if the work is heavy. On the web, Printing opens the browser's print and download flow.

Saving a file

Mobile apps are sandboxed: you may write only to folders the OS gives you. path_provider returns them.

DART
import 'dart:io';
import 'package:path_provider/path_provider.dart';

Future<File> savePdf(Uint8List bytes, String name) async {
  final dir = await getApplicationDocumentsDirectory();   // private, backed up, survives updates
  final file = File('${dir.path}/$name');
  return file.writeAsBytes(bytes, flush: true);
}
Function Use for
getApplicationDocumentsDirectory() Files that belong to the user's data in your app
getTemporaryDirectory() Cache the OS may clear any time
getApplicationSupportDirectory() App-private support files, not shown to the user
getDownloadsDirectory() Desktop and some platforms; limited on mobile

dart:io does not exist on the web, so web code downloads through the browser instead (Printing.sharePdf or a download helper). Never build a path from user text without cleaning it; a name like ../../x is a path traversal risk (security). Local databases and key-value storage have their own lesson: Local storage.

Picking files

file_picker opens the system chooser.

DART
final result = await FilePicker.platform.pickFiles(
  type: FileType.custom,
  allowedExtensions: ['pdf'],
  allowMultiple: false,
  withData: false,          // true loads the bytes into memory (needed on web)
);

if (result == null) return;                       // user cancelled
final picked = result.files.single;
print('${picked.name}, ${picked.size} bytes');
final path = picked.path;                         // null on web: use picked.bytes instead

Recent major versions of file_picker reorganized parts of this API, so follow the README of the version you install. Check the extension and the size before you read or upload a file, and read large files as streams rather than loading them whole. To show a PDF you picked, use a viewer package such as pdfx or syncfusion_flutter_pdfviewer (read its license), or hand the file to the system with url_launcher.

JS Split table rows across pages

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Using pw.Page for long content. Use pw.MultiPage.
  • Forgetting to embed a font for accents or non-Latin text.
  • Mixing pw.Text and Text. Import the pdf widgets with a prefix and use them only inside pw trees.
  • Floating-point money. Store cents as integers.
  • Using dart:io on the web. Guard with kIsWeb or conditional imports.
  • Trusting picked file names or sizes. Validate before use.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which widget lets the pdf package flow long content across several pages?

    pw.Page holds a single page; pw.MultiPage splits its list of widgets over as many pages as needed.
  2. 2. Why embed a TTF font when generating a PDF?

    Embedding a font such as Noto Sans gives you accents and other scripts.
  3. 3. Which path_provider function is the right choice for a file the OS may delete at any time?

    The temporary directory is a cache location the system may clear.
  4. 4. What should you check before using the result of FilePicker.pickFiles?

    Cancelling returns null, so guard first, then validate name, extension and size.

Summary

  • pdf builds documents as bytes with its own pw widgets; use MultiPage for long content and embed fonts for non-Latin text.
  • printing previews, prints and shares; path_provider finds writable folders; file_picker opens the system chooser and may return null.
  • Keep money in integer cents, avoid dart:io on the web, and validate user-provided files and names.

Next: Unit and Widget Testing