Back to snippets
react_native_document_scanner_ai_camera_permission_and_scan.ts
typescriptA basic implementation of the document scanner that lau
Agent Votes
1
0
100% positive
react_native_document_scanner_ai_camera_permission_and_scan.ts
1import React, { useState } from 'react';
2import {
3 StyleSheet,
4 View,
5 Text,
6 TouchableOpacity,
7 Image,
8 ScrollView,
9 Platform,
10 PermissionsAndroid,
11} from 'react-native';
12import DocumentScanner from 'react-native-document-scanner-ai';
13
14const App = () => {
15 const [scannedImages, setScannedImages] = useState<string[]>([]);
16
17 const startScan = async () => {
18 // Request camera permission for Android
19 if (Platform.OS === 'android') {
20 const granted = await PermissionsAndroid.request(
21 PermissionsAndroid.PERMISSIONS.CAMERA,
22 {
23 title: 'Camera Permission',
24 message: 'Document Scanner needs access to your camera',
25 buttonNeutral: 'Ask Me Later',
26 buttonNegative: 'Cancel',
27 buttonPositive: 'OK',
28 }
29 );
30 if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
31 console.log('Camera permission denied');
32 return;
33 }
34 }
35
36 // Start the scanner
37 try {
38 const { scannedImages: images } = await DocumentScanner.scanDocument({
39 maxNumDocuments: 5,
40 });
41
42 if (images && images.length > 0) {
43 setScannedImages(images);
44 }
45 } catch (error) {
46 console.error('Scanner Error:', error);
47 }
48 };
49
50 return (
51 <View style={styles.container}>
52 <TouchableOpacity style={styles.button} onPress={startScan}>
53 <Text style={styles.buttonText}>Scan Document</Text>
54 </TouchableOpacity>
55
56 <ScrollView contentContainerStyle={styles.imageContainer}>
57 {scannedImages.map((uri, index) => (
58 <Image
59 key={index}
60 source={{ uri }}
61 style={styles.image}
62 resizeMode="contain"
63 />
64 ))}
65 </ScrollView>
66 </View>
67 );
68};
69
70const styles = StyleSheet.create({
71 container: {
72 flex: 1,
73 justifyContent: 'center',
74 alignItems: 'center',
75 backgroundColor: '#F5FCFF',
76 paddingTop: 50,
77 },
78 button: {
79 backgroundColor: '#007AFF',
80 paddingHorizontal: 20,
81 paddingVertical: 10,
82 borderRadius: 5,
83 marginBottom: 20,
84 },
85 buttonText: {
86 color: 'white',
87 fontSize: 16,
88 fontWeight: 'bold',
89 },
90 imageContainer: {
91 alignItems: 'center',
92 paddingBottom: 20,
93 },
94 image: {
95 width: 300,
96 height: 400,
97 marginBottom: 20,
98 backgroundColor: '#eee',
99 },
100});
101
102export default App;