Skip to main content

document_camera_frame 2.6.16 copy "document_camera_frame: ^2.6.16" to clipboard
document_camera_frame: ^2.6.16 copied to clipboard

Flutter package for capturing and cropping document images with a customizable camera interface.

Document Camera Frame #

Pub Version Pub Points Likes

A Flutter widget for photographing documents such as ID cards, passports and receipts. It shows a camera frame, crops the photo to it, can capture automatically once the document is lined up, and can read the text on the device. Results come back as JPG, PNG, PDF or TIFF.

Demo #

Default Mode Export Example
Default Mode
Default UI mode — live camera preview with frame, progress bar, side indicators, and auto-capture
Export Example
Export in action — capturing and exporting documents as JPG, PNG, PDF, or TIFF
UI Modes CamScanner Mode
UI Modes
All built-in UI modes — default, minimal, overlay, kiosk, and textExtract
CamScanner Mode
Native CamScanner mode — delegates to the platform's built-in document scanner

Features #

📸 Capture #

  • Live camera preview with a document frame you size yourself (frameWidth, frameHeight), and the capture is cropped to that frame.
  • Auto-capture: once the document is steady and lined up inside the frame, it takes the photo for you.
  • Front and back in one flow (an ID card, a driver's license), with an animated flip between sides.
  • camScanner mode hands the whole scan to the platform's own scanner (ML Kit on Android, VisionKit on iOS), which gives you its edge detection and perspective correction.
  • Haptic feedback while the user lines up the document.

🔍 Detection and guidance #

  • Edge detection with ML Kit to find the document in the frame.
  • Live hints such as "Move closer" or "Move right" while the user aims.
  • The frame you see on screen maps to the full-resolution sensor image, so the crop doesn't cut off the edges.

📝 Text extraction (OCR) #

  • Set enableExtractText: true and the recognized text comes back with the result. It runs on the device, with no API key and no network call.
  • Latin-script text only. Arabic is not supported.

📄 Output #

  • JPG (default), PNG, PDF or TIFF, with adjustable JPG quality.
  • PDFs can have several pages (front and back) in A4 or Letter.

🎨 UI and styling #

  • Six UI modes: defaultMode, minimal, overlay, kiosk, textExtract and camScanner.
  • Style classes for the frame, buttons, titles, progress bar and instructions.
  • Callbacks: onDocumentSaved, onFrontCaptured, onBackCaptured, onRetake, onCameraError.

🔒 Privacy #

  • Everything runs on the device and the package makes no network calls. Images are written to the app's temporary directory, and what happens to them after that is up to you.

📱 What each UI mode shows #

The DocumentCameraUIMode enum decides which parts of the UI are shown and how capture behaves:

Feature default minimal overlay kiosk textExtract camScanner
Dark cutout overlay ✅ ❌ ❌ ✅ ✅ Native
Frame border + corners ✅ ✅* ✅ ✅ ✅ Native
Bottom frame container ✅ ❌ ✅ ✅ ✅ Native
Progress bar and dots ✅ ❌ ❌ ✅ ✅ Native
Static instructions (top) ✅ ❌ ❌ ✅ ✅ Native
Live alignment hints** ✅ ❌ ✅ ✅ ✅ Native
Screen title / close button ✅ ❌ ✅ ✅ ✅ Native
Camera switcher ✅ ✅ ✅ ❌ ✅ Native
Capture button ✅ ✅ ✅ ❌ ✅ Native
Save / Retake buttons ✅ ✅ ✅ ✅ ✅ Native
Auto-capture ✅ ❌ ✅ ✅ ✅ Native
On-device OCR (by default) ❌ ❌ ❌ ❌ ✅ ❌
Platform scanner UI ❌ ❌ ❌ ❌ ❌ ✅

* Minimal draws CornerBox corners instead of a full frame border.

** Hints change with the document's position, for example "Move closer" or "Move right".

Installation #

Add the package to your Flutter project using:

flutter pub add document_camera_frame

Quick Start #

Minimal Example #

The package follows the Flutter-standard await Navigator.push(...) pattern — identical to showDatePicker, ImagePicker, and other Flutter APIs. Push the camera, await the result, then navigate forward. onDocumentSaved is optional — the package always pops with the result automatically.

import 'package:document_camera_frame/document_camera_frame.dart';
import 'package:flutter/material.dart';

Future<void> launchCamera(BuildContext context) async {
  final DocumentCaptureData? result = await Navigator.push<DocumentCaptureData>(
    context,
    MaterialPageRoute(
      builder: (_) => DocumentCameraFrame(
        frameWidth: 320,
        frameHeight: 200,
        requireBothSides: true,
        // onDocumentSaved is optional — use it for side effects like
        // analytics or intermediate processing. Navigation is already
        // handled: the package pops with the result automatically.
      ),
    ),
  );

  if (result != null && context.mounted) {
    // Navigate to your result screen — or do anything else with the data.
    print('Front image: ${result.frontImagePath}');
    print('Back image:  ${result.backImagePath}');
  }
}

Common Use Cases #

Driver's License (Both Sides) #

DocumentCameraFrame(
  frameWidth: 320,
  frameHeight: 200,
  titleStyle: DocumentCameraTitleStyle(
    frontSideTitle: Text('Scan Front of License', 
      style: TextStyle(color: Colors.white)),
    backSideTitle: Text('Scan Back of License',
      style: TextStyle(color: Colors.white)),
  ),
  requireBothSides: true,
  enableAutoCapture: true,
  onFrontCaptured: (imagePath) => print('Front: $imagePath'),
  onBackCaptured: (imagePath) => print('Back: $imagePath'),
  // onDocumentSaved is optional — use it for side effects like
  // analytics or intermediate processing. Navigation is already
  // handled: the package pops with the result automatically.
)

Passport (Single Side) #

DocumentCameraFrame(
  frameWidth: 300,
  frameHeight: 450,
  titleStyle: DocumentCameraTitleStyle(
    title: Text('Scan Passport', style: TextStyle(color: Colors.white)),
  ),
  requireBothSides: false,
  sideIndicatorStyle: DocumentCameraSideIndicatorStyle(
    showSideIndicator: false,
  ),
  enableAutoCapture: false, // Manual capture only
  instructionStyle: DocumentCameraInstructionStyle(
    showInstructionText: true,
    frontSideInstruction: "Position passport within the frame",
  ),
  // onDocumentSaved is optional — use it for side effects like
  // analytics or intermediate processing. Navigation is already
  // handled: the package pops with the result automatically.
)

ID Card with Custom Styling #

DocumentCameraFrame(
  frameWidth: 320,
  frameHeight: 200,
  requireBothSides: true,
  enableAutoCapture: true,
  buttonStyle: DocumentCameraButtonStyle(
    captureButtonText: "Take Photo",
    saveButtonText: "Done",
    retakeButtonText: "Try Again",
  ),
  progressStyle: DocumentCameraProgressStyle(
    progressIndicatorColor: Colors.blue,
  ),
  frameStyle: DocumentCameraFrameStyle(
    outerFrameBorderRadius: 16.0,
  ),
  // onDocumentSaved is optional — use it for side effects like
  // analytics or intermediate processing. Navigation is already
  // handled: the package pops with the result automatically.
)

UI modes #

Pick a layout with the uiMode parameter:

// Kiosk Mode (Auto-capture only, no capture button)
DocumentCameraFrame(
  uiMode: DocumentCameraUIMode.kiosk,
  enableAutoCapture: true,
  // onDocumentSaved is optional — use it for side effects like
  // analytics or intermediate processing. Navigation is already
  // handled: the package pops with the result automatically.
)

// Minimal Mode (Clean view, only corners and buttons)
DocumentCameraFrame(
  uiMode: DocumentCameraUIMode.minimal,
)

// Native CamScanner Mode (Delegates to the OS's native document scanner)
DocumentCameraFrame(
  uiMode: DocumentCameraUIMode.camScanner,
  requireBothSides: true, // Guides user to scan front then back separately
)

Note: In camScanner mode, all custom frame and styling properties (borders, colors, buttons) are ignored as the platform's native scanner UI takes over.


Export Formats #

Choose the output format for your captured documents. The package supports 4 formats: JPG (default), PNG, PDF, and TIFF.

Supported Formats #

Format Description Best For
JPG Default format, adjustable quality General purpose, backward compatible
PNG Lossless compression High-quality images, transparency support
PDF Multi-page document Professional documents, archival
TIFF High-quality archival format Professional archival, maximum quality

Basic Usage #

// JPG (default - backward compatible)
DocumentCameraFrame(
  frameWidth: 320,
  frameHeight: 200,
)

// PNG format
DocumentCameraFrame(
  frameWidth: 320,
  frameHeight: 200,
  outputFormat: DocumentOutputFormat.png,
)

PDF Generation #

Generate multi-page PDFs from captured documents with configurable page sizes.

DocumentCameraFrame(
  frameWidth: 320,
  frameHeight: 200,
  outputFormat: DocumentOutputFormat.pdf,
  pdfPageSize: PdfPageSize.a4, // or PdfPageSize.letter
  requireBothSides: true, // Creates 2-page PDF
)

PDF Features:

  • Multi-page support: Front and back images become separate pages
  • Page sizes: A4 (210×297mm) or Letter (8.5×11 inches)
  • Automatic compression: Optimized file size while maintaining quality
  • Single-page PDFs: Works with requireBothSides: false for passports, etc.
  • Automatic Cleanup: Temporary JPG files are automatically deleted after PDF generation to save disk space.

Format Parameters #

Parameter Type Description Default
outputFormat DocumentOutputFormat Output format (jpg, png, pdf, tiff) DocumentOutputFormat.jpg
pdfPageSize PdfPageSize PDF page size (a4 or letter) PdfPageSize.a4
imageQuality int Compression quality for JPG (1-100) 90
initialFlashMode FlashMode Initial camera flash mode FlashMode.auto

DocumentCaptureData Fields #

When using different formats, the DocumentCaptureData object contains:

class DocumentCaptureData {
  final String? frontImagePath;    // Path to front image (.jpg, .png, etc.)
  final String? backImagePath;     // Path to back image (if captured)
  final String? frontPreviewPath;  // Path to displayable JPG (especially for TIFF)
  final String? backPreviewPath;   // Path to displayable JPG (especially for TIFF)
  final String? pdfPath;           // Path to PDF (only when outputFormat is PDF)
  final String? frontOcrText;      // OCR text (if enableExtractText is true)
  final String? backOcrText;       // OCR text (if enableExtractText is true)
  
  bool get hasPdf => pdfPath != null && pdfPath!.isNotEmpty;
  bool get hasFrontText => frontOcrText != null && frontOcrText!.isNotEmpty;
  bool get hasBackText => backOcrText != null && backOcrText!.isNotEmpty;
}

Complete Example #

DocumentCameraFrame(
  frameWidth: 320,
  frameHeight: 200,
  outputFormat: DocumentOutputFormat.pdf,
  pdfPageSize: PdfPageSize.a4,
  imageQuality: 90,
  initialFlashMode: FlashMode.auto,
  requireBothSides: true,
  enableAutoCapture: true,
  enableExtractText: true,
  titleStyle: DocumentCameraTitleStyle(
    frontSideTitle: Text('Scan Front', style: TextStyle(color: Colors.white)),
    backSideTitle: Text('Scan Back', style: TextStyle(color: Colors.white)),
  ),
  // onDocumentSaved is optional — use it for side effects like
  // analytics or intermediate processing. Navigation is already
  // handled: the package pops with the result automatically.
)

Note: All format parameters are optional. Existing code continues to work without changes (JPG is the default format).


OCR (Text Extraction) #

Note: OCR is Latin-only (no Arabic). The on-device ML Kit model supports English and other Latin-script languages only.

Extract text from captured documents using on-device OCR. No API key or internet required.

Basic OCR Usage #

Set enableExtractText: true to run on-device text recognition after capture:

final result = await Navigator.push<DocumentCaptureData>(
  context,
  MaterialPageRoute(
    builder: (_) => DocumentCameraFrame(
      frameWidth: 320,
      frameHeight: 200,
      enableExtractText: true,
      // onDocumentSaved is optional — use it for side effects like
      // analytics or intermediate processing. Navigation is already
      // handled: the package pops with the result automatically.
    ),
  ),
);

if (result != null) {
  print('Front text: ${result.frontOcrText}');
  print('Back text:  ${result.backOcrText}');
}

Custom OCR #

For custom OCR (e.g., from file paths elsewhere), use the exported OcrService class:

import 'package:document_camera_frame/document_camera_frame.dart';

final ocrService = OcrService();
final text = await ocrService.extractText('/path/to/image.jpg');
print('Extracted text: $text');

Native Scanning (Direct Access) #

If you want to launch the native scanner directly without the DocumentCameraFrame widget, you can use the CamScannerService:

import 'package:document_camera_frame/document_camera_frame.dart';

final service = CamScannerService();
final List<String> paths = await service.scan(maxPages: 2);

if (paths.isNotEmpty) {
  print('Scanned files: $paths');
}

Setup Requirements #

iOS Setup #

  1. Set the minimum iOS deployment target to 15.5 or higher in your ios/Podfile:
platform :ios, '15.5'  # or newer version
  1. Add the following keys to your ios/Runner/Info.plist file to request camera and microphone permissions:

<plist version="1.0">
    <dict>
        <!-- Add the following keys inside the <dict> section -->
        <key>NSCameraUsageDescription</key>
        <string>We need camera access to capture documents.</string>
        <key>NSMicrophoneUsageDescription</key>
        <string>We need microphone access for audio-related features.</string>
    </dict>
</plist>

Android Setup #

  1. Update your android/app/build.gradle to set compileSdk to 36 and minSdk to 24. On Flutter 3.41, flutter.compileSdkVersion and flutter.minSdkVersion already have these values:
android {
    compileSdk 36

    defaultConfig {
        minSdk 24
        targetSdk 35
    }
}

Important: The camera plugin this package uses now ships CameraX 1.6, which requires compileSdk 36 or higher, and it needs minSdk 23 or higher. With compileSdk 35, your build fails with:

Dependency 'androidx.camera:camera-core:1.6.0' requires libraries and applications that
depend on it to compile against version 36 or later of the Android APIs.

Also make sure Android 16 (API 36) is installed via Android Studio → SDK Manager.

  1. Add these permissions to your AndroidManifest.xml file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

    <application android:label="MyApp" android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher">
        <!-- Activities and other components -->
    </application>

</manifest>

Handling Camera Access Permissions #

Permission errors may occur when initializing the camera. You must handle them appropriately. Below are the possible error codes:

Error Code Description
CameraAccessDenied User denied camera access permission.
CameraAccessDeniedWithoutPrompt iOS only. User previously denied access and needs to enable it manually via Settings.
CameraAccessRestricted iOS only. Camera access is restricted (e.g., parental controls).
AudioAccessDenied User denied microphone access permission.
AudioAccessDeniedWithoutPrompt iOS only. User previously denied microphone access and needs to enable it manually via Settings.
AudioAccessRestricted iOS only. Microphone access is restricted (e.g., parental controls).

Widget Parameters #

Core Parameters #

Parameter Type Description Required Default Value
frameWidth double Width of the document capture frame. Yes —
frameHeight double Height of the document capture frame. Yes —
outputFormat DocumentOutputFormat Output format: jpg, png, pdf, or tiff. No DocumentOutputFormat.jpg
pdfPageSize PdfPageSize PDF page size (a4 or letter) when outputFormat is PDF. No PdfPageSize.a4
imageQuality int Compression quality for JPG formats (1-100). No 90
enableAutoCapture bool Enables automatic capture when a document is properly aligned in the frame. No false
requireBothSides bool Whether to require both sides (if false, can save with just front side). No true
showCloseButton bool Flag to control the visibility of the CloseButton (optional). No false
cameraIndex int? Index to specify which camera to use (e.g., 0 for back, 1 for front) (optional). No 0 (back)
bottomFrameContainerChild Widget? Custom content for the bottom container (optional). No null
bottomHintText String? Optional bottom hint text shown in the bottom container. No null
sideInfoOverlay Widget? Optional widget shown on the right (e.g. a check icon). No null
showDetectionStatusText bool Show the (dynamic) live detection status text (e.g. "Move closer"). No true
initialFlashMode FlashMode Initial camera flash mode: auto, off, on, torch. No FlashMode.auto
uiMode DocumentCameraUIMode Controls which UI elements are rendered (see UI Mode Visibility Matrix). No defaultMode

Styling Classes #

Parameter Type Description Required Default Value
animationStyle DocumentCameraAnimationStyle Animation styling configuration for the camera widget. No DocumentCameraAnimationStyle()
frameStyle DocumentCameraFrameStyle Frame styling configuration for borders and appearance. No DocumentCameraFrameStyle()
buttonStyle DocumentCameraButtonStyle Button styling configuration for all buttons. No DocumentCameraButtonStyle()
titleStyle DocumentCameraTitleStyle Title styling configuration for screen titles. No DocumentCameraTitleStyle()
sideIndicatorStyle DocumentCameraSideIndicatorStyle Side indicator styling configuration. No DocumentCameraSideIndicatorStyle()
progressStyle DocumentCameraProgressStyle Progress indicator styling configuration. No DocumentCameraProgressStyle()
instructionStyle DocumentCameraInstructionStyle Instruction text styling configuration. No DocumentCameraInstructionStyle()

Callbacks #

Parameter Type Description Required Default Value
onFrontCaptured Function(String)? Callback triggered when front side is captured. No null
onBackCaptured Function(String)? Callback triggered when back side is captured. No null
onDocumentSaved Function(DocumentCaptureData)? Callback when document is saved (one-sided e.g. passport, or both sides). Optional — use await Navigator.push to receive the result instead. No null
onBothSidesSaved Function(DocumentCaptureData)? Deprecated. Use onDocumentSaved instead. Still supported for backward compatibility. No null
enableExtractText bool When true, runs on-device OCR and sets documentData.frontOcrText / backOcrText before the callback. No false
onRetake VoidCallback? Callback triggered when the "Retake" button is pressed. No null
onCameraError void Function(Object error)? Callback triggered when a camera-related error occurs (e.g., initialization, streaming, or capture failure). No null

Navigation note: onDocumentSaved is an optional side-channel for analytics or intermediate processing. The package pops itself with the result automatically — use await Navigator.push<DocumentCaptureData>(...) to receive the data, identical to showDatePicker or ImagePicker.

Styling Classes Details #

DocumentCameraAnimationStyle #

Property Type Description Default Value
capturingAnimationDuration Duration? Duration for the capturing animation (optional). null
capturingAnimationColor Color? Color for the capturing animation (optional). null
capturingAnimationCurve Curve? Curve for the capturing animation (optional). null
frameFlipDuration Duration Duration for the flip animation between sides. Duration(milliseconds: 1200)
frameFlipCurve Curve Curve for the flip animation between sides. Curves.easeInOut

DocumentCameraFrameStyle #

Property Type Description Default Value
outerFrameBorderRadius double Radius of the outer border of the frame. 12.0
innerCornerBorderRadius double Radius of the inner corners of the frame. 8.0
frameBorder BoxBorder? Border for the displayed frame (optional). null

Breaking change (v2.5.7): innerCornerBorderRadius was previously misnamed innerCornerBroderRadius. Update any references in your code if upgrading from v2.5.6 or earlier.

DocumentCameraButtonStyle #

Property Type Description Default Value
captureOuterCircleRadius double? Radius of the outer circle of the capture button. null
captureInnerCircleRadius double? Radius of the inner circle of the capture button. null
captureButtonText String? Text for the "Capture" button. null
captureFrontButtonText String? Text for capture button when capturing front side. null
captureBackButtonText String? Text for capture button when capturing back side. null
saveButtonText String? Text for the "Save" button. null
nextButtonText String? Text for "Next" button (when moving from front to back). null
previousButtonText String? Text for "Previous" button (when going back to front). null
retakeButtonText String? Text for the "Retake" button. null
captureButtonStyle ButtonStyle? Style for the "Capture" button (optional). null
actionButtonStyle ButtonStyle? Style for action buttons (optional). null
retakeButtonStyle ButtonStyle? Style for the "Retake" button (optional). null
captureButtonAlignment Alignment? Alignment of the "Capture" button (optional). null
captureButtonPadding EdgeInsets? Padding for the "Capture" button (optional). null
captureButtonWidth double? Width for the "Capture" button (optional). null
captureButtonHeight double? Height for the "Capture" button (optional). null
actionButtonAlignment Alignment? Alignment of action buttons (optional). null
actionButtonPadding EdgeInsets? Padding for action buttons (optional). null
actionButtonWidth double? Width for action buttons (optional). null
actionButtonHeight double? Height for action buttons (optional). null
captureButtonTextStyle TextStyle? Text style for the "Capture" button text (optional). null
actionButtonTextStyle TextStyle? Text style for action buttons (optional). null
retakeButtonTextStyle TextStyle? Text style for the "Retake" button text (optional). null

DocumentCameraTitleStyle #

Property Type Description Default Value
showScreenTitle bool Show or hide the screen title area at the top of the frame. true
title Widget? Widget to display as the screen's title (optional). null
frontSideTitle Widget? Title for the front side. Defaults to white "Front Side" text. White "Front Side"
backSideTitle Widget? Title for the back side. Defaults to white "Back Side" text. White "Back Side"
screenTitleAlignment Alignment? Alignment of the screen title (optional). null
screenTitlePadding EdgeInsets? Padding for the screen title (optional). null

DocumentCameraSideIndicatorStyle #

Property Type Description Default Value
showSideIndicator bool Show the side indicator. Set true to enable. false
topPosition double? Side indicator position from the top (optional). null
rightPosition double? Side indicator position from the right (optional). null
sideIndicatorBackgroundColor Color? Background color for side indicator. null
sideIndicatorBorderColor Color? Border color for side indicator. null
sideIndicatorActiveColor Color? Active color for side indicator. null
sideIndicatorInactiveColor Color? Inactive color for side indicator. null
sideIndicatorCompletedColor Color? Completed color for side indicator. null
sideIndicatorTextStyle TextStyle? Text style for side indicator text. null

DocumentCameraProgressStyle #

Property Type Description Default Value
progressIndicatorColor Color? Color for the progress indicator (optional). null
progressIndicatorHeight double Height of the progress indicator. 4.0

DocumentCameraInstructionStyle #

Property Type Description Default Value
showInstructionText bool Show the (static) top instruction banner. Hidden by default. false
frontSideInstruction String? Instruction text for front side capture. null
backSideInstruction String? Instruction text for back side capture. null
instructionTextStyle TextStyle? Text style for instruction text (optional). null

🛠️ Troubleshooting #

The camera doesn't start

  • Check that the app has camera permission in the device settings.
  • On Android, minSdk must be at least 24 and compileSdk at least 36.
  • On iOS, make sure the camera usage description is in Info.plist.

Android build fails with "compile against version 36"

  • Set compileSdk 36 in android/app/build.gradle.
  • Install Android 16 (API 36) from Android Studio's SDK Manager.
  • Run flutter clean && flutter pub get.

Other build errors

  • Run flutter clean && flutter pub get.
  • Go through the platform setup above again.
  • On iOS, the deployment target in ios/Podfile has to be 15.5 or higher.

Permission denied

  • Show the user a clear message and point them to the settings page where they can turn the permission back on. The error codes are listed in Handling camera access permissions.

The package opens and releases the camera for you. Images go to the temporary directory, so copy them somewhere permanent if you need to keep them.


Full example #

For a bigger example with several document types, see example/lib/main.dart.

Contributing #

Pull requests are welcome. For anything bigger than a small fix, open an issue first so we can talk it through.

🙌 Support #

Found a bug? Open an issue. Ideas and questions go in Discussions. If the package saves you some time, a ⭐ on GitHub or a like on pub.dev helps others find it.

License #

This project is licensed under the MIT License. See the LICENSE file for details.