Flutter Invoice Scanner: Simpler Approach
While Flutter doesn't have native access to ARKit or Core Image, we can still build a robust invoice scanner using:
- Camera Plugin for capture.
- Google ML Kit (free, on-device) for rectangle detection & OCR.
- Image Processing (simple filters) for enhancement.
- PDF Generation via
pdf package.
Here's a streamlined workflow (less precise than the iOS-native method, but 90% as good with half the effort):
Step 1: Capture Invoice (Camera Plugin)
Add camera: ^0.10.5+2 to pubspec.yaml. Use CameraController to capture images:
import 'package:camera/camera.dart';
class ScanPage extends StatefulWidget {
@override
_ScanPageState createState() => _ScanPageState();
}
class _ScanPageState extends State<ScanPage> {
CameraController? _controller;
List<CameraDescription>? _cameras;
Future<void> _initCamera() async {
_cameras = await availableCameras();
_controller = CameraController(_cameras!.first, ResolutionPreset.high);
await _controller!.initialize();
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Scan Invoice')),
body: _controller == null
? Center(child: CircularProgressIndicator())
: CameraPreview(_controller!),
floatingActionButton: FloatingActionButton(
onPressed: () async {
final XFile file = await _controller!.takePicture();
_processImage(file.path); // Next step
},
child: Icon(Icons.camera),
),
);
}
}
Step 2: Detect Document Edges (Google ML Kit)
Add google_ml_kit: ^0.16.0 for document scanning:
import 'package:google_ml_kit/google_ml_kit.dart';
Future<void> _processImage(String path) async {
final inputImage = InputImage.fromFilePath(path);
final scanner = GoogleMlKit.vision.documentScanner();
final result = await scanner.processImage(inputImage);
if (result.pages.isNotEmpty) {
final croppedImage = result.pages.first.image; // Cropped & warped invoice
_enhanceImage(croppedImage.path); // Next step
} else {
print("Failed to detect document");
}
}
ML Kit’s DocumentScanner does:
- Auto-crop
- Perspective correction
- Noise reduction (basic)
Step 3: Simple Image Enhancement
Use image: ^3.2.0 for lightweight processing:
import 'package:image/image.dart' as img;
Future<void> _enhanceImage(String path) async {
img.Image? image = img.decodeImage(File(path).readAsBytesSync())!;
// 1. Contrast & Brightness
image = img.adjustColor(
image,
brightness: 0.1, // Slightly brighter
contrast: 1.2, // A bit more punch
);
// 2. Sharpen (careful not to overdo)
image = img.copyResize(image, width: 1500); // Upscale for clarity
img.gaussianBlur(image, radius: 1); // Soften noise
img.unsharpen(image, radius: 1.5, amount: 1.5);
// Save enhanced image
final enhancedPath = '${path}_enhanced.jpg';
File(enhancedPath).writeAsBytesSync(img.encodeJpg(image));
_createPdf(enhancedPath); // Final step
}
Why not over-engineer?
- CLAHE, advanced deblurring, and color calibration are overkill for 95% of invoices.
- Users tolerate minor imperfections if the workflow is fast & foolproof.
Step 4: Generate PDF (pdf Package)
Add pdf: ^3.8.1 and printing: ^5.9.3 (for saving/sharing):
import 'package:pdf/pdf.dart';
import 'package:printing/printing.dart';
import 'dart:io';
import 'dart:typed_data';
Future<void> _createPdf(String imagePath) async {
final pdfDoc = pw.Document();
final imageBytes = File(imagePath).readAsBytesSync();
final image = pw.MemoryImage(imageBytes);
pdfDoc.addPage(pw.Page(
build: (context) => pw.Center(
child: pw.Image(image, width: PdfPageFormat.a4.width),
),
));
// Save/share PDF
await Printing.layoutPdf(
onLayout: (format) async => pdfDoc.save(),
);
}
Full Workflow Code (Minimal Example)
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:google_ml_kit/google_ml_kit.dart';
import 'package:image/image.dart' as img;
import 'package:pdf/pdf.dart';
import 'package:printing/printing.dart';
class InvoiceScanner extends StatefulWidget {
@override
_InvoiceScannerState createState() => _InvoiceScannerState();
}
class _InvoiceScannerState extends State<InvoiceScanner> {
CameraController? _controller;
Future<void> _initCamera() async {
final cameras = await availableCameras();
_controller = CameraController(cameras.first, ResolutionPreset.high);
await _controller!.initialize();
setState(() {});
}
Future<void> _captureAndProcess() async {
final XFile file = await _controller!.takePicture();
final inputImage = InputImage.fromFilePath(file.path);
final scanner = GoogleMlKit.vision.documentScanner();
final result = await scanner.processImage(inputImage);
if (result.pages.isNotEmpty) {
final croppedPath = result.pages.first.image.path;
await _enhanceAndPdf(croppedPath);
}
}
Future<void> _enhanceAndPdf(String path) async {
img.Image image = img.decodeImage(File(path).readAsBytesSync())!;
image = img.adjustColor(image, brightness: 0.1, contrast: 1.2);
img.gaussianBlur(image, radius: 1);
img.unsharpen(image, radius: 1.5, amount: 1.5);
final enhancedPath = '${path}_enhanced.jpg';
File(enhancedPath).writeAsBytesSync(img.encodeJpg(image));
final pdfDoc = pw.Document();
final imageBytes = File(enhancedPath).readAsBytesSync();
pdfDoc.addPage(pw.Page(
build: (context) => pw.Center(
child: pw.Image(pw.MemoryImage(imageBytes), width: PdfPageFormat.a4.width),
),
));
await Printing.layoutPdf(onLayout: (format) async => pdfDoc.save());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Scan Invoice')),
body: _controller == null
? Center(child: CircularProgressIndicator())
: CameraPreview(_controller!),
floatingActionButton: FloatingActionButton(
onPressed: _captureAndProcess,
child: Icon(Icons.camera),
),
);
}
}
Pros of This Simpler Approach:
- Fast Development: 1–2 weeks (vs. 3–6 months for native).
- Cross-Platform: Works on Android/iOS (ML Kit handles platform quirks).
- Low Maintenance: Google updates ML Kit; you get free improvements.
- Good Enough Quality: 300 DPI, readable text, decent contrast.
Cons:
- Less Control: No AR guidance, manual capture only.
- Poorer Edge Cases: Bent papers, extreme glare might fail.
When to Use This:
- MVP or Small App: You need "works well enough" fast.
- Internal Tools: Employees scan invoices; perfection isn’t critical.
- Budget Constraints: Hire one Flutter dev instead of iOS + Android teams.
Upgrade Path:
- If users complain about glare/bent papers, add a "Re-take" button with hints (e.g., "Lay flat").
- For premium users, integrate OpenCV via native modules (better warping).
- If volume grows, switch to server-side processing (e.g., AWS Textract for OCR).
This Flutter workflow gives you 80% of the quality with 20% of the effort. Perfect for most business apps! 🚀