React Native HTML to PDF
Here is an Example to Make PDF in React Native from HTML Text. In this example, we will create a PDF file from the HTML text after the click of a button in our App. To complete this task we will use react-native-html-to-pdf
library. So let’s get started.
You can also visit Print HTML as a Document from React Native App for Android and iOS.
To Make a React Native App
Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
This will make a project structure with an index file named App.js in your project directory.
Installation of Dependency
To use RNHTMLtoPDF
we need to install react-native-html-to-pdf
package. To install this
Open the terminal and jump into your project
cd ProjectName
Run the following command
npm install react-native-html-to-pdf --save
This command will copy all the dependencies into your node_module directory, You can find the directory in node_module
the directory named react-native-html-to-pdf
.
CocoaPods Installation
After the updation of React Native 0.60, they have introduced autolinking so we do not require to link the library but need to install pods. So to install pods use
cd ios && pod install && cd ..
Permission for Android
We are accessing external storage so we need to add some permission in AndroidManifest.xml
file.
We are going to add the following permissions in the AndroidMnifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
- WRITE_EXTERNAL_STORAGE: To store the PDF in the SD card.
- READ_EXTERNAL_STORAGE: To read the SD card.
For more about the permission, you can see this post.
Addition of MultiDexEnable for Android
To enable the multidex which is required by HTML to PDF converter library open Yourproject -> android -> app -> build.gradle and search for defaultConfig which comes under android and add
multiDexEnabled true
Please follow the below screenshot for a clear understanding.
This is it. 🙂 Now we are ready to go to the code section.
Code to Make PDF in React Native from HTML Text
Open App.js in any code editor and replace the code with the following code
App.js
// Example to Make PDF in React Native from HTML Text
// https://aboutreact.com/make-pdf-in-react-native-from-html-text/
// Import React
import React, {useState} from 'react';
// Import required components
import {
SafeAreaView,
Text,
TouchableOpacity,
View,
StyleSheet,
Image,
PermissionsAndroid,
Platform,
} from 'react-native';
// Import HTML to PDF
import RNHTMLtoPDF from 'react-native-html-to-pdf';
const App = () => {
const [filePath, setFilePath] = useState('');
const isPermitted = async () => {
if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: 'External Storage Write Permission',
message: 'App needs access to Storage data',
},
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
} catch (err) {
alert('Write permission err', err);
return false;
}
} else {
return true;
}
};
const createPDF = async () => {
if (await isPermitted()) {
let options = {
//Content to print
html:
'<h1 style="text-align: center;"><strong>Hello Guys</strong></h1><p style="text-align: center;">Here is an example of pdf Print in React Native</p><p style="text-align: center;"><strong>Team About React</strong></p>',
//File Name
fileName: 'test',
//File directory
directory: 'docs',
};
let file = await RNHTMLtoPDF.convert(options);
console.log(file.filePath);
setFilePath(file.filePath);
}
};
return (
<SafeAreaView style={{flex: 1}}>
<Text style={styles.titleText}>
Example to Make PDF in React Native from HTML Text
</Text>
<View style={styles.container}>
<TouchableOpacity onPress={createPDF}>
<View>
<Image
//We are showing the Image from online
source={{
uri:
'https://raw.githubusercontent.com/AboutReact/sampleresource/master/pdf.png',
}}
style={styles.imageStyle}
/>
<Text style={styles.textStyle}>Create PDF</Text>
</View>
</TouchableOpacity>
<Text style={styles.textStyle}>{filePath}</Text>
</View>
</SafeAreaView>
);
};
export default App;
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 10,
backgroundColor: '#fff',
alignItems: 'center',
},
titleText: {
fontSize: 22,
fontWeight: 'bold',
textAlign: 'center',
paddingVertical: 20,
},
textStyle: {
fontSize: 18,
padding: 10,
color: 'black',
textAlign: 'center',
},
imageStyle: {
width: 150,
height: 150,
margin: 5,
resizeMode: 'stretch',
},
});
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshots
Asking for permission while opening the app for the first time
Click on create PDF to create PDF
Have a look at the location in internal/external storage where we have created PDF from HTML
This is how you can make PDF from your React Native Application. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!
Hope you liked it. 🙂
how to print text to new line if the width of page is not enough to print whole text ?
As we can not use bootstrap or any other way to auto adjust the text width. So you have to define the width of the text manually in HTML. First you have to find the width of the page in px like for “A4″ page the size is 595px 842px so we have to define the width of the external div to width=”595px” which will restrict the width and text will automatically goes to the next line. If you are still facing the issue then can you share your content so that I can try once.
Hi! greeting’s im trying it with the expo for the same code it is asking for external write storage how i can provide it in expo can you please eloborate this
Sorry this kind of native feature will only work in ejected project, will not work for Expo. You need something else for Expo not only this library.
Thank you 🙂
I found a way by using Expo-print and expo-sharing we can actually do it.!
Thanks for sharing. 🙂
how we ca add images inside pdf like headers and footer can you please elaborate with example please !?
Hi Pavan, I tried to add image in HTML but it didn’t worked, You can see last comments to get more updates.
How to convert a listview data to pdf
Is it a simple list or the custom component list?
If you are willing to make a single list then you have to create the Dynamic HTML from the Array of elements like
1. you have an array
2. make a varriable
3. add the element using for loop
4. and at last add the closer of ul
Hope this will help you.
how do I style the html outside the div tag using a css or a css file
To make a PDF you have to use inline CSS and you have to use some tag to treat the string as a HTML. You can use Span tag if you don’t want div
is there a way to modifying an existing document that was created
Not with this library. (By the way, you can not modify PDF :p )
Hi, Snehal
How can I give an image path in HTML String? I want to give an image path that is in the project folder. Folder Structure is like Module/assets/imageName.png.
Sorry, I haven’t tried it yet but I don’t think it is possible.
Hi snehal,
i am creating a table that has 17 columns and it doesn’t fit and the last few columns are not seen, i tried to add width but its not working,
In Case of PDF you need to adjust the content according to the A4 size paper. For that make a HTML Div with 2480 pixels x 3508 pixels and then adjust the HTML table and then try to print.
Hi, how to pass data and recieve data to html.
I don’t think it is possible. If you want to change the HTML then use your RN logic to change the HTML and it will auto-update the view but if you want to take the input from HTML and want to use it in RN then I can’t help.
1. i have created a table in the html which shows some data when pdf is generated.
2. in RN i have made a api call and i want to send the response of that api call to html so that i can display it in the table contents.
can i know how to achieve it ?
Thanks,
Yes, You can. See there is nothing magical in it you just have to call an API and have to set the value of html options in before passing options in RNHTMLtoPDF.convert(options)
Excellent post. It is working perfectly. Thank you sir.
Hi I have multiple pages data, can you please let me know ho do i create multiple pages from that data, and I want to make header and footer static on every page.
Thanks in advance, I know you will solve my problem for sure.
How to display dynamic table under html tag?? I m trying to display liat of products with their prices but not able to display in that html tag as syntax is going wrong somewhere. Could you please provide the basic example of displaying table under html.
Hello
if am using react-native-Html-to-pdf and in my HTML styles in include color and the background-color styles, the pdf is not printed at all.
In other words, it shows nothing at all if I include the color and background-color styles.
I need your help with this.
Am a big fan of your work, appreciate greatly
Thnak you
Guys I’ll update this post with all of your requirements in the comment give me some time
hlo , i am working on images to pdf generate i try my best and i easily generate pdf but its not supporting means pdf does not open ,even i try your html to pdf but
every time on run function i get this
Possible Unhandled Promise Rejection (id: 0):
Error: RNHTMLtoPDF error: Could not create folder structure.
please help me
Hi Piyush,
In the first line you can see “Could not create folder structure.” which means it is unable to create the destination directory in the file system, so first create the destination directory and then create the PDF in it.
I have used this library’s but when create ipa build saying error UIwebview don’t support why give me answer.
Can you please look into the following thread?
Deprecated API Usage – New apps that use UIWebView are no longer accepted. Instead, use WKWebView for improved security
How to add image through html code which will be added into pdf
I tried a whole day but tried of doing that. Give me some more time I am looking for something else.
Hello Snehal,
is it possible if i want to send user data from API in options html ?
since html type data are string.
for example
const [user, setUser] = useState();
//i set user from API response
and on options = {
html : ‘user name{user}’,
…
}
I need your help thanks
Yeah we can do that.
Hello Snehal,
I try to generate pdf in android device and the pdf have paddings (for each page)
do you get any idea why and what i should do?
We can’t do anything of the default padding of the PDF
How to Create multipage pdf Any idea?
Hi boss,
I want to add multiple images in pdf generator
Can you please help me?
Thanks
I have tried images but didn’t get any success till now 🙁
I am trying to export to PDF with hyperlinks included in the PDF.
Is this something that is possible?
I don’t think it is possible. This library is not that feature reach, instead you can use server to create one and download the same in your mobile device.
for (let i = 0; i < arr.length; i++) this give me an error when i used it it inside script tags.
Can u provide an example of how to loof in side of its html
Thanks
Need to join strings for the same like this
I m using this library react-native-html-to-pdf pdf file creating properly. can we download pdf file on app screen. pls reply