React Native Generate Pdf File Example

Jun 29, 2022 . Admin

Hi Guys,

I am going to explain you example of how to implement pdf file in react native. This article will give you simple example of how to build pdf file in react native. In this article, we will implement a how to create pdf file in react native. This article will give you simple example of how to make pdf file in react native. Here, Creating a basic example of how to generate pdf file in react native.

Let's start following example:

Step 1: Download Project

In the first step run the following command to create a project.

expo init ExampleApp
Step 2: Install and Setup

You can install expo-print to create Pdf:

expo install expo-print

You can install expo-sharing to allows you to share files directly with other compatible applications:

expo install expo-sharing
Step 3: App.js

In this step, You will open the App.js file and put the code.

import React from 'react';
import { StatusBar, StyleSheet, View, Button } from 'react-native';
import { printToFileAsync } from 'expo-print';
import { shareAsync } from 'expo-sharing';

const data = {
    name: 'Divyesh Barad',
    email: 'divyesh@gmail.com',
    address: 'Rajkot',
}

const App = () => {
    const html = `
        <html>
            <body>
                <h2>Hi ${data.name}</h2>
                <h4>Email: ${data.email}</h4>
                <h4>Address: ${data.address}</h4>
            </body>
        </html>
    `;

    const generatePdf = async () => {
        const file = await printToFileAsync({
            html: html,
            base64: false,
        });
        await shareAsync(file.uri);
    }

    return (
        <View style={styles.container}>
            <Button
                title='generate Pdf'
                onPress={generatePdf}
            />
            <StatusBar />
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
})

export default App;
Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output :

It will help you...

#React Native