As the react native world grows there are more opportunities comes for react native developer. In current development world you can perform any type of mobile functionality in react native which we can do in JAVA android development. In today’s tutorial we would make a react native application which would convert all the HTML(Hyper Text Markup Language) text directly into PDF content file and also store the file into our mobile phone storage. This type of functionality is mostly used to store HTML we pages in PDF format directly into our mobile phone storage same as downloading HTML pages. We would use a React Native NPM library named as react-native-html-to-pdf in our tutorial to perform this functionality. So in this tutorial we would Create PDF File using HTML Text in React Native Android iOS Example Tutorial.
Content in this project Create PDF File using HTML Text in React Native Android iOS Example Tutorial:
1. Before getting started we have to install the react-native-html-to-pdf library in our current react native project. So open your react native project’s root folder in Command Prompt or Terminal and execute below command. One more thing sometimes it cannot install the library in one attempt so just try one more time to install it.
1
|
npm install react–native–html–to–pdf —save
|
Screenshot :
Screenshot after done installing the library :
2. After done installing the library next step is to link the library to our react native project index. You can also use the CocoaPods installation for auto-linking but i preferred the old simple way using link command. So execute the below command to link the react-native-html-to-pdf library.
1
|
react–native link react–native–html–to–pdf
|
Screenshot:
3. Now the installation part has done. Next step is to add the Read and Write permissions for Android. So GoTo Your_React_Native_Project -> android -> app -> src -> main -> AndroidManifest.xml file. Add below Read and Write permissions.
1
2
|
<uses–permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE”/>
<uses–permission android:name=“android.permission.READ_EXTERNAL_STORAGE”/>
|
Complete Source code for AndroidManifest.xml file :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<manifest xmlns:android=“http://schemas.android.com/apk/res/android”
package=“com.project”>
<uses–permission android:name=“android.permission.INTERNET” />
<uses–permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE”/>
<uses–permission android:name=“android.permission.READ_EXTERNAL_STORAGE”/>
<application
android:name=“.MainApplication”
android:label=“@string/app_name”
android:icon=“@mipmap/ic_launcher”
android:roundIcon=“@mipmap/ic_launcher_round”
android:allowBackup=“false”
android:theme=“@style/AppTheme”>
<activity
android:name=“.MainActivity”
android:label=“@string/app_name”
android:configChanges=“keyboard|keyboardHidden|orientation|screenSize”
android:windowSoftInputMode=“adjustResize”>
<intent–filter>
<action android:name=“android.intent.action.MAIN” />
<category android:name=“android.intent.category.LAUNCHER” />
</intent–filter>
</activity>
<activity android:name=“com.facebook.react.devsupport.DevSettingsActivity” />
</application>
</manifest>
|
4. Now we have to add MultiDexEnable for android devices. The android APK installation file can only generate Single dex file with 65,536 methods in a single link file but after enabling MultiDexEnable true we can past this limit. So GoTo Your_React_Native_Project -> android -> app -> build.gradlew file. Find defaultConfig code scope and add
multiDexEnabled true like i did in below code.
1
2
3
4
5
6
7
8
|
defaultConfig {
applicationId “com.project”
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName “1.0”
multiDexEnabled true
}
|
5. All the major configuration has been done now. Now its time to start coding for application. Open your project’s App.js file and import Alert, PermissionsAndroid, Platform, Text, TouchableOpacity, View and StyleSheet component.
1
2
3
|
import React, { Component } from ‘react’;
import { Alert, PermissionsAndroid, Platform, Text, TouchableOpacity, View, StyleSheet } from ‘react-native’;
|
6. Import RNHTMLtoPDF from ‘react-native-html-to-pdf‘ library in your react native project.
1
|
import RNHTMLtoPDF from ‘react-native-html-to-pdf’;
|
7. Create our main export default class named as App extends with Component.
1
2
3
4
|
export default class App extends Component {
}
|
8. Create constructor in App class and make State named as filePath. We would use this State to store the saved PDF file path.
1
2
3
4
5
6
|
constructor(props) {
super(props);
this.state={
filePath : ”
}
}
|
9. Create a function named as requestRunTimePermission(). In this function first we would ask for Android’s runtime permission for accessing WRITE_EXTERNAL_STORAGE permission and if user enables permission then Generate the PDF file using HTML content and store the file into given docs folder. We would call this function on button click event.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
requestRunTimePermission=()=> {
var that = this;
async function externalStoragePermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: ‘External Storage Write Permission’,
message:‘App needs access to Storage data.’,
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
that.createPDF_File();
} else {
alert(‘WRITE_EXTERNAL_STORAGE permission denied’);
}
} catch (err) {
Alert.alert(‘Write permission err’, err);
console.warn(err);
}
}
if (Platform.OS === ‘android’) {
externalStoragePermission();
} else {
this.createPDF_File();
}
}
|
10. Create a ASYNC function named as createPDF_File(). In this function we would use the react-native-html-to-pdf library to convert all the HTML text into pdf file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
async createPDF_File() {
let options = {
// HTML Content for PDF.
// I am putting all the HTML code in Single line but if you want to use large HTML code then you can use + Symbol to add them.
html:
‘<h1 style=”text-align: center;”><strong>Welcome Guys</strong></h1><p style=”text-align: center;”>In This Tutorial we would learn about creating PDF File using HTML Text.</p><p style=”text-align: center;”><strong>ReactNativeCode.com</strong></p>’,
// Setting UP File Name for PDF File.
fileName: ‘test’,
//File directory in which the PDF File Will Store.
directory: ‘docs’,
};
let file = await RNHTMLtoPDF.convert(options);
console.log(file.filePath);
Alert.alert(file.filePath);
this.setState({filePath:file.filePath});
}
|
11. Create a Touchable Opacity button and 1 Text component in render’s return block.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
render() {
return (
<View style={styles.MainContainer}>
<TouchableOpacity
onPress={this.requestRunTimePermission}
activeOpacity={0.6}
style={styles.button}>
<Text style={styles.text}>Click Here To Create PDF File</Text>
</TouchableOpacity>
<Text style={styles.text}>{‘Save File Path = ‘ + this.state.filePath}</Text>
</View>
);
}
|
12. Creating Style.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’,
padding: 20
},
button: {
width: ‘100%’,
paddingTop:10,
paddingBottom:10,
backgroundColor: ‘#00E676’,
borderRadius:9,
},
text: {
color: ‘#000’,
textAlign:‘center’,
fontSize: 21
}
});
|
13. Complete Source Code for App.js file class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
import React, { Component } from ‘react’;
import { Alert, PermissionsAndroid, Platform, Text, TouchableOpacity, View, StyleSheet } from ‘react-native’;
import RNHTMLtoPDF from ‘react-native-html-to-pdf’;
export default class App extends Component {
constructor(props) {
super(props);
this.state={
filePath : ”
}
}
requestRunTimePermission=()=> {
var that = this;
async function externalStoragePermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: ‘External Storage Write Permission’,
message:‘App needs access to Storage data.’,
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
that.createPDF_File();
} else {
alert(‘WRITE_EXTERNAL_STORAGE permission denied’);
}
} catch (err) {
Alert.alert(‘Write permission err’, err);
console.warn(err);
}
}
if (Platform.OS === ‘android’) {
externalStoragePermission();
} else {
this.createPDF_File();
}
}
async createPDF_File() {
let options = {
// HTML Content for PDF.
// I am putting all the HTML code in Single line but if you want to use large HTML code then you can use + Symbol to add them.
html:
‘<h1 style=”text-align: center;”><strong>Welcome Guys</strong></h1><p style=”text-align: center;”>In This Tutorial we would learn about creating PDF File using HTML Text.</p><p style=”text-align: center;”><strong>ReactNativeCode.com</strong></p>’,
// Setting UP File Name for PDF File.
fileName: ‘test’,
//File directory in which the PDF File Will Store.
directory: ‘docs’,
};
let file = await RNHTMLtoPDF.convert(options);
console.log(file.filePath);
Alert.alert(file.filePath);
this.setState({filePath:file.filePath});
}
render() {
return (
<View style={styles.MainContainer}>
<TouchableOpacity
onPress={this.requestRunTimePermission}
activeOpacity={0.6}
style={styles.button}>
<Text style={styles.text}>Click Here To Create PDF File</Text>
</TouchableOpacity>
<Text style={styles.text}>{‘Save File Path = ‘ + this.state.filePath}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’,
padding: 20
},
button: {
width: ‘100%’,
paddingTop:10,
paddingBottom:10,
backgroundColor: ‘#00E676’,
borderRadius:9,
},
text: {
color: ‘#000’,
textAlign:‘center’,
fontSize: 21
}
});
|
Screenshots: