Print HTML as a Document from React Native App for Android and iOS

Print a Document from React Native App

Here is an Example to Print HTML as a Document from React Native App for Android and iOS. In this example, we will see how to print HTML as a document, make pdf from HTML and print remote PDF from URL.

This is an extended example fo  Example to Make PDF in React Native from HTML Text.

Print HTML as Document means to print any HTML from our React Native application as a PDF document. We can also save the same HTML as PDF and can also print the remote PDF document.

We are using RNPrint component provided from react-native-print to trigger the default print option of the device and will use RNHTMLtoPDF component provided by react-native-html-to-pdf to make pdf from HTML.

In this example, you will see two extra options available for the iOS which are to choose the printer and silent print (Direct printing in the background). So let’s get started with the print HTML as a document example.

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 Dependencies

Open the terminal and jump into your project

cd ProjectName

1. For the printing option, we will use RNPrint component and for that install react-native-print dependency using

npm install react-native-print --save

2. To make PDF we will use RNHTMLtoPDF component and for that install react-native-html-to-pdf dependency using

npm install react-native-html-to-pdf --save

This command will copy all the dependencies into your node_module directory.

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

Addition of MultiDexEnable for Android

To handle Execution failed for task ‘:app:transformDexArchiveWithExternalLibsDexMergerForDebug’ error in Android we have to enable multiDex. To enable the multidex open Yourproject -> android -> app -> build.gradle and search for defaultConfig and dependencies and add the following lines

defaultConfig {
     .....
    multiDexEnabled true
}
..............
dependencies {
    .......
    implementation 'com.android.support:multidex:1.0.3'
}

Please follow the below screenshot for better understanding For more about multiDex you can visit Enable multidex for apps with over 64K methods This is it. 🙂 Now we are ready to go to the code section.

Code to Print HTML as a Document

Open App.js in any code editor and replace the code with the following code

App.js

// Print HTML as a Document from React Native App for Android and iOS
// https://aboutreact.com/react-native-print-html/

// Import React
import React, {useState} from 'react';
// Import required components
import {
  SafeAreaView,
  StyleSheet,
  Platform,
  Text,
  View,
  TouchableOpacity,
} from 'react-native';

// Import HTML to PDF
import RNHTMLtoPDF from 'react-native-html-to-pdf';
// Import RNPrint
import RNPrint from 'react-native-print';

const App = () => {
  const [selectedPrinter, setSelectedPrinter] = useState(null);

  // Only for iOS
  const selectPrinter = async () => {
    const selectedPrinter = 
await RNPrint.selectPrinter({x: 100, y: 100}); setSelectedPrinter(selectedPrinter); }; // Only for iOS const silentPrint = async () => { if (!selectedPrinter) { alert('Must Select Printer First'); } const jobName = await RNPrint.print({ printerURL: selectedPrinter.url, html: '<h1>Silent Print clicked</h1>', }); }; const printHTML = async () => { await RNPrint.print({ html: '<h1>Here will be Heading 1</h1>
<h2>Here will be Heading 2</h2>
<h3>Here will be Heading 3</h3>
', }); }; const printPDF = async () => { const results = await RNHTMLtoPDF.convert({ html: '<h1>Demo Text to converted to PDF</h1>', fileName: 'test', base64: true, }); await RNPrint.print({filePath: results.filePath}); }; const printRemotePDF = async () => { await RNPrint.print({ filePath: 'http://www.africau.edu/images/default/sample.pdf', }); }; const customOptions = () => { return ( <View> {selectedPrinter && ( <View> <Text>
{`Selected Printer Name: ${selectedPrinter.name}`}
</Text> <Text>
{`Selected Printer URI: ${selectedPrinter.url}`}
</Text> </View> )} <TouchableOpacity
style={styles.buttonStyle}
onPress={selectPrinter}> <Text>Click to Select Printer</Text> </TouchableOpacity> <TouchableOpacity
style={styles.buttonStyle}
onPress={silentPrint}> <Text>Click for Silent Print</Text> </TouchableOpacity> </View> ); }; return ( <SafeAreaView style={{flex: 1}}> <Text style={styles.titleText}> Print HTML as a Document from React Native App </Text> <View style={styles.container}> {Platform.OS === 'ios' && customOptions()} <TouchableOpacity
style={styles.buttonStyle}
onPress={printHTML}> <Text>Click to Print HTML</Text> </TouchableOpacity> <TouchableOpacity
style={styles.buttonStyle}
onPress={printPDF}> <Text>Click to Print PDF</Text> </TouchableOpacity> <TouchableOpacity
style={styles.buttonStyle}
onPress={printRemotePDF}> <Text>Click to Print Remote PDF</Text> </TouchableOpacity> </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, }, buttonStyle: { alignItems: 'center', backgroundColor: '#DDDDDD', padding: 10, width: 300, marginVertical: 10, }, });

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

Android

        

iOS

           

This is how you can print HTML as a document from the React Native app for Android and iOS. 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. 🙂

 

3 thoughts on “Print HTML as a Document from React Native App for Android and iOS”

  1. I have made a pdf by merging some images using the library react-native-image-to-pdf and saving it in my device. Whenever I am trying to print that pdf using react-native-print library, the pdf is showing in print preview, but problem is that pdf’s images are not fitting properly, making some blank space, in below and right side. My requirement is that Images needs to be placed in centre of the container. Any Solutions. Thanks

    Reply

Leave a Comment

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