Example to Make PDF in React Native from HTML Text

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. 🙂

 

46 thoughts on “Example to Make PDF in React Native from HTML Text”

    • 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

      arr =[Coffee, Tea, Milk];

      2. make a varriable

      var  x= '<ul>';

      3. add the element using for loop

      for (let i = 0; i < arr.length; i++) {
          x = x + '<li>' + arr[i] + '</li>';
      }

      4. and at last add the closer of ul

      x = x + '</ul>';

      Hope this will help you.

      Reply
  1. 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.

    Reply
  2. 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,

    Reply
    • 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.

      Reply
    • 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.

      Reply
      • 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,

        Reply
        • 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)

          Reply
  3. 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.

    Reply
  4. 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.

    Reply
  5. 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

    Reply
  6. 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

    Reply
    • 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.

      Reply
  7. 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

    Reply
  8. 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?

    Reply
  9. 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

    Reply
    • Need to join strings for the same like this

      
      let dummy = '<html><body><select>'
      for (let i = 0; i < arr.length; i++){
        dummy = dummy + '<option>arr[i].value</option>'
      }
      dummy = dummy + '</select></body></html>'
      
      Reply
  10. I m using this library react-native-html-to-pdf pdf file creating properly. can we download pdf file on app screen. pls reply

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.