Learn about generating PDF files with React Native Expo using the react-native-html-to-pdf library!

I'm currently attempting to execute a 'Hello World' code utilizing the react-native-html-to-pdf library in order to generate a PDF, but I am encountering difficulties setting it up in Expo. Would you be able to provide assistance? I have tried using the command react-native link.

package.json

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "expo": "^35.0.0",
    "react": "16.8.3",
    "react-dom": "16.8.3",
    "react-native": "https://github.com/expo/react-native/archive/sdk-35.0.0.tar.gz",
    "react-native-html-to-pdf": "^0.8.0",
    "react-native-pdf-lib": "^0.2.1",
    "react-native-web": "^0.11.7"
  },
  "devDependencies": {
    "babel-preset-expo": "^7.1.0"
  },
  "private": true
}

App.js

import React, { Component } from 'react';

import {
  Text,
  TouchableHighlight,
  View,
  StyleSheet,
} from 'react-native';

import RNHTMLtoPDF from 'react-native-html-to-pdf';

export default class App extends Component {
  async createPDF() {
    let options = {
      html: '<h1>PDF TEST</h1>',
      fileName: 'test',
      directory: 'Documents',
    };

    let file = await RNHTMLtoPDF.convert(options)
    // console.log(file.filePath);
    alert(file.filePath);
  }

  render() {
    return(
      <View style={styles.container}>
        <TouchableHighlight onPress={this.createPDF}>
          <Text>Create PDF</Text>
        </TouchableHighlight>
      </View>
    )
  }
}

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

});

Answer №1

If you're working with Expo, linking libraries is not possible due to Expo's limitations. To achieve the desired functionality, consider transitioning to a bare React Native application by ejecting from Expo, as linking is not supported in Expo. This is a significant constraint of Expo.

Alternatively, you can refer to the Expo Print documentation at expo link, where they have provided a print function for saving HTML to PDF.

Print.printToFileAsync(options)
Prints HTML to PDF file and saves it to app's cache directory.
Arguments
options (object) -- A map of options:
html (string) -- HTML string to print into PDF file.
width (number) -- Width of the single page in pixels. Defaults to 612 which is a width of US Letter paper format with 72 PPI.
height (number) -- Height of the single page in pixels. Defaults to 792 which is a height of US Letter paper format with 72 PPI.
base64 (boolean) -- Whether to include base64 encoded string of the file in the returned object.
Returns
Resolves to an object with following keys:
uri (string) -- A URI to the printed PDF file.
numberOfPages (number) -- Number of pages that were needed to render given content.
base64 (string) -- Base64 encoded string containing the data of the PDF file. Available only if base64 option is truthy. It doesn't include data URI prefix data:application/pdf;base64,.

Hope this information proves helpful. If you have any questions, don't hesitate to ask.

Answer №2

To utilize the functionality for exporting PDFs, you will first need to import these two dependencies from Expo:

import * as Print from 'expo-print';
import { shareAsync } from 'expo-sharing';

Afterwards, you can implement a function like the one below to export a PDF document:

const generatePDF = async () => {
    const htmlContent = `
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
  </head>
  <body style="text-align: center;">
    <h1 style="font-size: 50px; font-family: Helvetica Neue; font-weight: normal;">
      Hello Expo!
    </h1>
    <img
      src="https://example.com/image.jpg"
      style="width: 90vw;" />
  </body>
</html>
`;
    // This method prints the provided HTML on iOS/android platforms, while printing the current webpage's HTML on web.
    const { uri } = await Print.printToFileAsync({ html: htmlContent });
    console.log('The file has been saved at:', uri);
    await shareAsync(uri, { UTI: '.pdf', mimeType: 'application/pdf' });
  };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to ensure that Vue data is updated to accurately reflect any modifications made by user input in the HTML

I'm currently using Vue to develop a small application that involves copying dynamic HTML content to the user's clipboard once they have completed a form. While everything seems to be functioning correctly, I am encountering an issue where the ch ...

What seems to be the issue with the data initialization function not functioning properly within this Vue component?

In my Vue 3 component, the script code is as follows: <script> /* eslint-disable */ export default { name: "BarExample", data: dataInitialisation, methods: { updateChart, } }; function dataInitialisation() { return { c ...

Step-by-step guide to rapidly resolve all issues in VS Code using TypeScript

After extensive searching in VS code, I have not been able to find a quick fix all solution in the documentation or plugins. Is this feature actually non-existent, or is it possible that I am overlooking a keybinding? (I am currently utilizing typescript s ...

Selecting a language by clicking on it

I recently designed a bootstrap navigation bar for my website and incorporated a language selection dropdown menu into it. <li class="nav-item dropdown"> <a class="nav-link dropright" href="#" id="navbarDropdown" role="button" data-toggle="dr ...

The React-native application initialized using npx create-react-app encountered an error and could not launch

Hello there, A couple of months back, I developed an app using create-react-app. However, when I tried to run it with npm start, I encountered the following error message: react-scripts start It seems like there's an issue with the project depende ...

Problem with Bootstrap 3 navbar on mobile devices - not tappable or responsive

After years of using Bootstrap, I've come across a new issue with my implementation of a Bootstrap 3 Nav. While testing on a desktop browser with device emulation, the nav collapses and functions properly. However, when tapping on the header on an ac ...

Click to open a Swipeable Drawer using an onClick event handler in Material UI

Issue Encountered: Currently, in the provided documentation code (https://codesandbox.io/s/cnvp4i?file=/demo.tsx), the drawer opens when the "Open" button is clicked at the top. However, I am looking to have the drawer triggered and opened when it is direc ...

FitText.js malfunctioning

I'm currently experimenting with using FitText.js to dynamically adjust the size of headlines to fit within the limits of the browser width. Interestingly, while this script successfully resizes the text in multiple sections of my website, it seems t ...

Performing an AJAX request to a form within a CSS modal

Greetings from France, and please excuse any language errors in my English. I am currently coding in Symfony 3 and have an entity called "book" which can have different attributes (client, student, organizer, and/or speaker) based on the selected "type" a ...

Is there a way to retrieve the selected value from a dropdown menu using vue.js?

I have a parent Vue component structured like this: <template> <form> <div class="row"> <div class="col-md-4"> <form-select id="color" name="color" :data="color">Color</form-select&g ...

Breaking apart a pipe-separated text and sending it through a JavaScript function

CSS: <div class="pageEdit" value="Update|1234567|CLOTHES=5678~-9876543?|5678"> <a href="https://host:controller">Update</a> </div> Trying to retrieve the data within the div and pass it into a JavaScr ...

Is it possible to convert a string of elements in JavaScript into JSON format?

Within my JavaScript code, a variable holds the following information: url=http://localhost quality=100 tag="4.4, 5.5" I am interested in converting this data to JSON format using JavaScript, like this: "result": { "url": "http://localhost", "qu ...

Trouble arises when attempting to use JavaScript, JSP, and JSON in conjunction with

I am in the process of creating a client-server application where I send a request from the client to the server using a JSON object for registration. However, despite receiving a JSON response with an "OK" field as expected, the client keeps triggering th ...

Twitter Bootstrap Dropdown PHP link fails to function

Recently, I designed a dropdown menu to be used on a PHP page. The main button, which contains the dropdown links, needs to still function as a link to another page. Despite following all the instructions provided on the Bootstrap website, the main button ...

Consistent value displayed by addEventListener for each event

Hey everyone, I've been experimenting with different solutions for a few hours now but I'm still stuck on this problem. I have a function that takes JSON as input - I can create an 'a' element: CHECK I can set all the element propertie ...

"Step-by-step guide on creating a dynamic clipping mask animation triggered by mouse wheel

I have developed a sample that functions just as I envision my final outcome to function, with the exception of triggering on mouse-over. Instead, I would like it to activate as a page transition when scrolling with the mouse. (move your cursor over the i ...

Retrieve weight measurements from a serial port by using Node JS

I'm a novice in node.js and I'm trying to retrieve weight data from a serial port. I have nodejs(v14.19.0) and npm(6.14.16) installed, and I'm attempting to obtain weight data using localhost:8080/get_weight. However, the script isn't f ...

Having issues with reading files in PHP using AJAX? Explore alternative methods for downloading files seamlessly

I need to store a value in a txt file and allow the user to download it. Currently, the value is successfully written to the txt file, but the readfile function does not execute, preventing the download from starting. The PHP code is on the same page as ...

JavaScript and jQuery: The Power of Dynamic Arrays

Even though my var email contains a string data, why does my array length always turn out to be 0? (I've confirmed that the data is there by using alert on var email). var emails = new Array(); //retrieve all the emails $('.emailBox ...

Enhance your Vue PWA by utilizing ServiceWorker to efficiently cache remote media assets fetched from an array of URLs

In my PWA development project, I am looking to provide users with the option to download and cache all media assets used in the application. However, the default behavior of PWAs only caches assets when they are requested during app navigation. My goal is ...