react-native-document-scanner-plugin

repository·master·Indexed 19 days ago

https://github.com/websitebeaver/react-native-document-scanner-plugin

A React Native plugin for Android and iOS that enables scanning of rectangular objects such as notes, receipts, and business cards. It provides the DocumentScanner.scanDocument() method to capture images, with configurable options for image quality, response types (file paths or base64), and a maximum document limit on Android. The library includes an Expo Config Plugin for automated native configuration in development builds.

Tokens
3.2K
Snippets
14
Records
16
Agent score
63%

What's inside react-native-document-scanner-plugin

  1. Setup with Expo

    master

    This plugin does not run in Expo Go. To use it with Expo, you must use a development build. Follow these steps:

    1. Install the plugin: npx expo install react-native-document-scanner-plugin

    2. Add the plugin to your app.json or app.config.json to configure permissions:

    {
      "name": "my expo app",
      "plugins": [
        [
          "react-native-document-scanner-plugin",
          {
            "cameraPermission": "We need camera access, so you can scan documents"
          }
        ]
      ]
    }
    1. Rebuild your project using npx expo prebuild or eas build.
    npx expo install react-native-document-scanner-plugin
  2. Install react-native-document-scanner-plugin

    master

    Install the package using npm:

    npm install react-native-document-scanner-plugin

    iOS Setup

    1. Add the NSCameraUsageDescription (Privacy - Camera Usage Description) key to your Info.plist file with a descriptive string explaining why the app needs camera access.
    2. Install pods:
    cd ios && pod install && cd ..

    Android Setup

    No additional manual permission configuration is required for this plugin to work, unless you are already using another plugin that manages camera permissions.

  3. Use the Expo Config Plugin for automatic configuration

    master

    The react-native-document-scanner-plugin provides an Expo Config Plugin to automate the native configuration required for the library. You can use this plugin in your app.json or app.config.js to ensure the native modules are correctly linked and configured during the Expo prebuild process.

    // Example usage in app.config.js
    module.exports = {
      expo: {
        name: 'My App',
        plugins: ['react-native-document-scanner-plugin'],
        // ... other config
      }
    };
  4. Troubleshoot Android Camera Permissions

    master

    If you are using another camera plugin that adds <uses-permission android:name="android.permission.CAMERA" /> to your AndroidManifest.xml, you must manually request camera permissions in your code. Failure to do so will result in the following error:

    Error: error - error opening camera: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE

    To prevent this, use PermissionsAndroid to request the camera permission before calling scanDocument().

    import { Platform, PermissionsAndroid, Alert } from 'react-native';
    import DocumentScanner from 'react-native-document-scanner-plugin';
    
    const scanDocument = async () => {
      if (Platform.OS === 'android' && await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.CAMERA
      ) !== PermissionsAndroid.RESULTS.GRANTED) {
        Alert.alert('Error', 'User must grant camera permissions to use document scanner.');
        return;
      }
    
      const { scannedImages } = await DocumentScanner.scanDocument();
      // ... handle images
    };
  5. Limit the number of scans on Android

    master

    On Android, you can restrict the number of documents a user can scan in a single session by passing the maxNumDocuments option to DocumentScanner.scanDocument(). This is useful for specific use cases like scanning both sides of a business card.

    Note: This option only works on Android.

    import DocumentScanner from 'react-native-document-scanner-plugin'
    
    const scanDocument = async () => {
      const { scannedImages } = await DocumentScanner.scanDocument({
        maxNumDocuments: 2
      })
    
      if (scannedImages.length > 0) {
        // handle scanned images
      }
    }
  6. Handle ScanDocumentResponse results

    master

    The ScanDocumentResponse object is returned upon completion of the scanDocument() call. It contains the scanned data and the outcome of the operation.

    PropTypeDescription
    scannedImagesstring[]An array containing either file paths or base64 encoded images of the scanned documents.
    statusScanDocumentResponseStatusIndicates if the scan was successful or if the user cancelled the operation.
  7. Use DocumentScanner.scanDocument() for basic scanning

    master

    To start the document scanner, call DocumentScanner.scanDocument(). This method returns a Promise that resolves to an object containing an array of scanned image file paths under the scannedImages key.

    Note: The returned paths can be used directly as a uri in a React Native Image component.

    import DocumentScanner from 'react-native-document-scanner-plugin'
    
    const scanDocument = async () => {
      // start the document scanner
      const { scannedImages } = await DocumentScanner.scanDocument()
    
      // scannedImages is an array of scanned image file paths
      if (scannedImages.length > 0) {
        // use scannedImages[0] as a URI for an Image component
      }
    }
  8. Use scanDocument() to start scanning

    master

    The scanDocument() method opens the camera interface and initiates the document scanning process. It returns a Promise that resolves to a ScanDocumentResponse object containing the results of the scan.

    Signature: scanDocument(options?: ScanDocumentOptions) => Promise<ScanDocumentResponse>

    const response = await DocumentScanner.scanDocument(options);
  9. Configure scanDocument with ScanDocumentOptions

    master

    You can pass an optional ScanDocumentOptions object to scanDocument() to customize the scanning behavior.

    PropTypeDescriptionDefault
    croppedImageQualitynumberThe quality of the cropped image from 0 - 100. 100 is the best quality.100
    maxNumDocumentsnumberAndroid only: The maximum number of photos a user can take (not counting photo retakes).undefined
    responseTypeResponseTypeDetermines if the response contains file paths or base64 strings.ResponseType.ImageFilePath
    const options: ScanDocumentOptions = {
      croppedImageQuality: 90,
      responseType: ResponseType.Base64,
    };
    const { scannedImages, status } = await DocumentScanner.scanDocument(options);
  10. Configure scanDocument options

    master

    Use the ScanDocumentOptions object to customize the scanning experience. Supported options are:

    • croppedImageQuality (number, optional): The quality of the cropped image from 0 to 100. Defaults to 100.
    • maxNumDocuments (number, optional): Android only. The maximum number of photos a user can take (excluding retakes). Defaults to undefined.
    • responseType (ResponseType, optional): Determines the format of the returned images. Defaults to ResponseType.ImageFilePath.
    const options: ScanDocumentOptions = {
      croppedImageQuality: 80,
      maxNumDocuments: 5, // Android only
      responseType: ResponseType.Base64
    };