I have this component that allows the user to pick a file from their device:
import React, { useState } from "react"
import { StyleSheet, Text, View, Button, TouchableOpacity } from "react-native"
import * as DocumentPicker from "expo-document-picker"
const UploadFile = () => {
const pickDocument = async () => {
try {
const res = await DocumentPicker.getDocumentAsync({
type: "*/*",
copyToCacheDirectory: true,
multiple: false,
})
console.log(res)
var lastThree = res.name.substr(res.name.length - 3)
if (res == undefined) {
return
} else if (
lastThree == "pdf" ||
lastThree == "epub" ||
lastThree == "doc"
) {
if (res.type == "success") {
//Do Something here
}
} else {
alert("Please select supported file type")
}
} catch (error) {
//alert(error)
}
}
return (
<View style={styles.background}>
<Text style={styles.file}>Upload PDF, EPUB, or DOC file.</Text>
<View style={styles.button}>
<TouchableOpacity>
<Button
title="upload your file"
color="black"
onPress={pickDocument}
/>
</TouchableOpacity>
</View>
</View>
)
}
const styles = StyleSheet.create({
background: {
backgroundColor: "#5ff5fa",
},
file: {
color: "black",
marginHorizontal: 145,
},
button: {
marginHorizontal: 60,
},
})
export default UploadFile
And can successfully use this to get the uri of a PDF, EPUB or DOC file, but I have no idea how to extract the text from these files. I tried something called react-native-pdf-extractor, but I couldn't get it to work. No idea what to try.
Note: I don't simply need to VIEW the pdf, I need the text from it so the app can style it a certain way.
Related
I'm doing this tutorial: https://docs.amplify.aws/start/getting-started/auth/q/integration/react-native#create-login-ui
I followed it completely and did everything they told me to do. The Todo works, but when I added Auth, and wrapped it. The project will start. Users can create accounts. But when you try to sign in on iOS it won't work. Strangely, when I tested it on web, users could sign in. Leading me to think it is a problem with iOS. I tested it on my iPhone with expo installed and it failed there too.
Here is a link to my issue: https://github.com/aws-amplify/amplify-js/issues/8113#issuecomment-830995508
This is my app.js
import config from './aws-exports'
Amplify.configure(config)
import { withAuthenticator } from 'aws-amplify-react-native'
import React, { useEffect, useState } from 'react'
import {
View, Text, StyleSheet, TextInput, Button
} from 'react-native'
import { API, graphqlOperation } from 'aws-amplify'
import { createTodo } from './graphql/mutations'
import { listTodos } from './graphql/queries'
const initialState = { name: '', description: '' }
const App = () => {
const [formState, setFormState] = useState(initialState)
const [todos, setTodos] = useState([])
useEffect(() => {
fetchTodos()
}, [])
function setInput(key, value) {
setFormState({ ...formState, [key]: value })
}
async function fetchTodos() {
try {
const todoData = await API.graphql(graphqlOperation(listTodos))
const todos = todoData.data.listTodos.items
setTodos(todos)
} catch (err) { console.log('error fetching todos') }
}
async function addTodo() {
try {
const todo = { ...formState }
setTodos([...todos, todo])
setFormState(initialState)
await API.graphql(graphqlOperation(createTodo, {input: todo}))
} catch (err) {
console.log('error creating todo:', err)
}
}
return (
<View style={styles.container}>
<TextInput
onChangeText={val => setInput('name', val)}
style={styles.input}
value={formState.name}
placeholder="Name"
/>
<TextInput
onChangeText={val => setInput('description', val)}
style={styles.input}
value={formState.description}
placeholder="Description"
/>
<Button title="Create Todo" onPress={addTodo} />
{
todos.map((todo, index) => (
<View key={todo.id ? todo.id : index} style={styles.todo}>
<Text style={styles.todoName}>{todo.name}</Text>
<Text>{todo.description}</Text>
</View>
))
}
</View>
)
}
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', padding: 20 },
todo: { marginBottom: 15 },
input: { height: 50, backgroundColor: '#ddd', marginBottom: 10, padding: 8 },
todoName: { fontSize: 18 }
})
export default withAuthenticator(App)```
I feel like the problem might be with the ./aws-exports potentially. There was a bug where you had to move it out of src, etc. Anyone have any ideas?
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/1Wt6J.png
I found out that the login error was due to a bug with expo deprecating a file. See this issue for more. https://github.com/aws-amplify/amplify-js/issues/8113#issuecomment-830995508
CameraRoll.getAlbums({
assetType:"All"
}).then( list => {
console.log(list.length)
}).catch((err) => {
console.log(err)
})
I tried this from CameraRoll but it returns an empty list.
First make sure that you add the correct permissions and build it afterwards.
Also check if your device has any files.
Then you can follow that logic:
import React from 'react';
import {
PermissionsAndroid,
Platform,
View,
TouchableOpacity,
Text,
} from 'react-native';
import {getAlbums} from '#react-native-community/cameraroll';
const hasAndroidPermission = async () => {
const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE;
const hasPermission = await PermissionsAndroid.check(permission);
if (hasPermission) {
return true;
}
const status = await PermissionsAndroid.request(permission);
return status === 'granted';
};
const handleGetAlbums = async () => {
if (Platform.OS === 'android' && !(await hasAndroidPermission())) {
return;
}
try {
const albums = await getAlbums({assetType: 'All'});
console.log(albums); // returns an object like [{"count": 4, "title": "Downloads"}]
return albums;
} catch (error) {
return error;
}
};
const App = () => {
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<TouchableOpacity onPress={handleGetAlbums}>
<Text>Press Me</Text>
</TouchableOpacity>
</View>
);
};
export default App;
How to print receipt or document from wifi with react native?
I already search about print in react native, but most of them show an option print from bluetooth, but i want to print from wifi, how can I do that?
check it if helps
import React, { Component } from 'react';
import {
AppRegistry,
Button,
StyleSheet,
NativeModules,
Platform,
Text,
View
} from 'react-native';
import RNHTMLtoPDF from 'react-native-html-to-pdf';
import RNPrint from 'react-native-print';
export default class RNPrintExample extends Component {
state = {
selectedPrinter: null
}
// #NOTE iOS Only
selectPrinter = async () => {
const selectedPrinter = await RNPrint.selectPrinter({ x: 100, y: 100 })
this.setState({ selectedPrinter })
}
// #NOTE iOS Only
silentPrint = async () => {
if (!this.state.selectedPrinter) {
alert('Must Select Printer First')
}
const jobName = await RNPrint.print({
printerURL: this.state.selectedPrinter.url,
html: '<h1>Silent Print</h1>'
})
}
async printHTML() {
await RNPrint.print({
html: '<h1>Heading 1</h1><h2>Heading 2</h2><h3>Heading 3</h3>'
})
}
async printPDF() {
const results = await RNHTMLtoPDF.convert({
html: '<h1>Custom converted PDF Document</h1>',
fileName: 'test',
base64: true,
})
await RNPrint.print({ filePath: results.filePath })
}
async printRemotePDF() {
await RNPrint.print({ filePath: 'https://graduateland.com/api/v2/users/jesper/cv' })
}
customOptions = () => {
return (
<View>
{this.state.selectedPrinter &&
<View>
<Text>{`Selected Printer Name: ${this.state.selectedPrinter.name}`}</Text>
<Text>{`Selected Printer URI: ${this.state.selectedPrinter.url}`}</Text>
</View>
}
<Button onPress={this.selectPrinter} title="Select Printer" />
<Button onPress={this.silentPrint} title="Silent Print" />
</View>
)
}
render() {
return (
<View style={styles.container}>
{Platform.OS === 'ios' && this.customOptions()}
<Button onPress={this.printHTML} title="Print HTML" />
<Button onPress={this.printPDF} title="Print PDF" />
<Button onPress={this.printRemotePDF} title="Print Remote PDF" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
more details:
https://www.npmjs.com/package/react-native-print
I'm new to React Native & I'm using NativeBase to build my demo app. I'm not able to create AutoComplete Searchbox using nativebase. Can anyone help me to give any example? My Requirement:
1. Rounded Search Box
2. Once Click it should show cancel button
3. After typing 2 letter it should give provide option to user for select
4. Select the option.
I searched in Google. However unable to find anything which suffice my requirement. Can anyone please help.
for your exact requirement you can write your own code. I tried to write autocomplete functionality. You can check in Expo.
This is basic code for react-native autocomplete functionality.
import React, { Component } from 'react';
import { FlatList, StyleSheet, Text, TextInput, View, TouchableOpacity } from 'react-native';
export default class AutoCompleteBasics extends Component {
constructor(props) {
super(props);
this.state = {
text: '',
textInputFocus: false,
arrayList: ['Apple', 'Mango', 'Guava', 'Muskmelon', 'Watermelon', 'Orange', 'Sapota']
};
}
componentDidMount() {
this.updateDataWithKey();
}
updateDataWithKey() {
const { arrayList } = this.state;
const dataWithKey = arrayList.map(data => {
return {'key': data}
});
this.setState({dataWithKey, filterData: dataWithKey});
}
changeText(text) {
this.setState({text});
const { dataWithKey } = this.state;
if (text !== '') {
let filterData = dataWithKey.filter(obj => {
return obj.key.toLowerCase().indexOf(text.trim().toLowerCase()) > -1;
});
if (filterData.length === 0) {
filterData = [{key: 'No Filter Data'}];
}
this.setState({filterData});
} else {
this.setState({filterData: dataWithKey});
}
}
onListItemClicked(text) {
this.setState({
text,
textInputFocus: false,
filterData: [{key: text}]
});
}
renderRow(item) {
return (
<TouchableOpacity
onPress={() => this.onListItemClicked(item.key)}
style={styles.listItem}
>
<Text style={styles.item}>{item.key}</Text>
</TouchableOpacity>
);
}
handleInputFocus() {
this.setState({textInputFocus: true});
}
handleInputBlur() {
this.setState({textInputFocus: false});
}
render() {
const { filterData, textInputFocus } = this.state;
return (
<View style={styles.container}>
<TextInput
style={styles.textInput}
onFocus={() => this.handleInputFocus()}
onBlur={() => this.handleInputBlur()}
placeholder="Search & Select List!"
onChangeText={(text) => this.changeText(text)}
value={this.state.text}
/>
{textInputFocus &&
<FlatList
data={filterData}
renderItem={({item}) => this.renderRow(item)}
/>
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingHorizontal: 8,
paddingTop: 12
},
textInput: {
height: 40,
marginLeft: 5,
},
item: {
padding: 10,
fontSize: 18,
height: 44,
},
})
you may use native-base-autocomplete the api is taken from react-native-auto-complete. check out snack example of how to use it.
I am new in react native. I have two pages in my app. When i press the back button, i want to open the previous page but when i press the back button, app get close. What can be done to solve this issue ?
My code is :
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TextInput,
TouchableHighlight
} from 'react-native';
import ToolbarAndroid from 'ToolbarAndroid';
import ActionButton from 'react-native-action-button';
import backAndroid from 'react-native-back-android';
import {hardwareBackPress} from 'react-native-back-android';
class AwesomeProject extends Component {
renderScene(route, navigator) {
if(route.name == 'HomePage') {
return <HomePage navigator={navigator} {...route.passProps} />
}
if(route.name == 'FormBuilderPage') {
return <FormBuilderPage navigator={navigator} {...route.passProps} />
}
}
render() {
return (
<Navigator
style={{ flex:1 }}
initialRoute={{ name: 'HomePage' }}
renderScene={ this.renderScene } />
)
}
}
class BackButtonEvent extends React.Component{
handleHardwareBackPress(){
if(this.sate.isOpen()){
this.handleClose();
return true;
}
}
}
var HomePage = React.createClass({
_navigate(name) {
this.props.navigator.push({
name: 'FormBuilderPage',
passProps: {
name: name
}
})
},
render() {
return (
<View style={styles.container}>
<ToolbarAndroid style = {styles.toolbar}>
<Text style = {styles.titleText}> Data Collector </Text>
</ToolbarAndroid>
<ActionButton
source = {require('./icon_container/ic_plus_circle_add_new_form.png')}
onPress = {this._navigate}
>
</ActionButton>
</View>
)
}
})
var FormBuilderPage = React.createClass({
render() {
return (
<View style={styles.container}>
<ToolbarAndroid style = {styles.toolbar}>
<TextInput placeholder = "Text here"/>
</ToolbarAndroid>
</View>
)
}
})
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
toolbar: {
height: 56,
backgroundColor: '#3F51B5'
},
titleText: {
color: '#fff',
}
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
You need to use BackAndroid API of React Native. This is the snippet from my example project.
BackAndroid.addEventListener('hardwareBackPress', () => {
var flag = false;
if(_route.name==="newbooking"){
Alert.alert(
"Confirmation",
"Are you sure you want to cancel?",
[
{text: 'No', onPress: () => console.log('OK Pressed!')},
{text: 'Yes', onPress: () => {_navigator.pop();}}
]
);
return true;
}
else{
flag = true;
}
if (_navigator.getCurrentRoutes().length === 1 ) {
return false;
}
if(flag){
_navigator.pop();
return true;
}
});
You can see how I have implemented that here!