← Flutter / Dart

Flutter / Dart · 14 / 18

Coordinate photos, files and PDF output

Create a PDF and distinguish file storage, database references and deliberate export.

  • Medium
  • Intermediate
  • 45 min

Prerequisites: Understand SQL and place Drift/SQLite in context

A photo or PDF consists of bytes. A database record usually holds a reference and metadata rather than the entire file contents. This separation avoids unnecessary database load but creates a coordination task. Files must not be deleted while records use them. We start with a small PDF report. The app then adds private storage, preview and sharing.

01Prepare a separate Dart project

Create a console project with dart create -t console pdf_demo. Replace pubspec.yaml with the sample and run dart pub get. It pins the checked PDF, image and archive package versions. Copy report.dart to bin/report.dart. This example uses dart:io and runs as a local console program.

report.dart · dartOpen file
import 'dart:io';
import 'package:pdf/widgets.dart' as pw;

Future<void> main() async {
  final doc = pw.Document();
  doc.addPage(
    pw.Page(
      build: (_) => pw.Column(
        children: [
          pw.Text('Family car'),
          pw.Text('Service'),
          pw.Text('129.90 EUR'),
        ],
      ),
    ),
  );
  await File('report.pdf').writeAsBytes(await doc.save(), flush: true);
  print('report.pdf written');
}

Run / check

dart run bin/report.dart

02Separate contents from output

Document holds the new PDF report. Page contains the layout. Text and Column come from the PDF widget package rather than Flutter Material. doc.save produces the final bytes. Only File.writeAsBytes writes them to disk.

03Manage references reliably

The app uses DocumentRepository and photo repositories as separate boundaries. A workflow imports a file, checks limits, stores metadata and assigns it to a draft. A failed write must not leave a valid reference pointing at a lost file.

04Check report and export

Open report.pdf and inspect the contents. The sample writes only to its current working directory. In the Android app, reports initially remain private. The user chooses export or sharing. A written report alone does not prove all attachments were included.

Expected result

report.pdf contains Family car, Service and 129.90 EUR.

Your exercise

Add the date and mileage. Then check the PDF contents using a PDF text tool.

Show the solution and explanation

Add two further pw.Text widgets. pdftotext report.pdf - checks text independently of the viewer. Photos and page layout also require visual or semantic checks.

Project context and sources

The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.