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

Observing mutations in HTML templates with MutationObserver

It appears that the MutationObserver does not function properly with a <template> tag. Check out this JSFiddle for more information! Any suggestions on how to effectively monitor changes in a <template> element? ...

Display issue with React TypeScript select field

I am working with a useState hook that contains an array of strings representing currency symbols such as "USD", "EUR", etc. const [symbols, setSymbols] = useState<string[]>() My goal is to display these currency symbols in a select field. Currently ...

Ways to verify if a string is a number without using isNaN and with specified criteria

I am trying to determine if a string represents a valid number without relying on the isNaN function. The reason for this is that I need to be able to accept the ',' character, which isNaN ignores. Additionally, I do not want to allow negative nu ...

Angular-Loopback-SDK: The method prototype$updateAttributes is not functioning as expected

I'm currently utilizing the loopback-angular-sdk and encountering a strange error while using the updateAttributes function: MyModel.prototype$updateAttributes is not a function This issue seems to be affecting all models. I have a hunch that it mig ...

When a jQuery click event is triggered, the event.target will return the child element that was clicked within the

When I have a jQuery click event assigned to a hyperlink that contains an image, each with separate ids, I expect clicking the hyperlink to trigger the code event.target.id, returning the hyperlink's id. However, it actually returns the image's i ...

What is the best way to keep an image fixed at the bottom, but only when it's out of view in the section

There are two buttons (images with anchors) on the page: "Download from Google Play" and "Download from App Store". The request is to have them stick to the bottom, but once the footer is reached they should return to their original position. Here are two ...

Angular UI Grid failing to properly display date formatting

Currently, I am using Angular's UI Grid to showcase multiple columns. However, I am facing an issue with formatting the date column. The date is being displayed as /Date(1451346632162-0000)/, and similar formats. I have attempted to apply filters in ...

Displaying a Countdown in a Django Loop: A Step-by-Step

Hey there, I've got a Javascript countdown nested in a Django for loop that's causing some trouble by displaying multiple instances. Currently, only the first countdown works when I click on any of the start buttons. I'd like each button to ...

Open a webpage and execute JavaScript with just one click of a bookmark

I found a convenient bookmark that opens my Google Calendar page at http://www.google.com/calendar/renderOnline. Additionally, I have another bookmarklet that applies specific JavaScript to the page: javascript:document.getElementById('gadgetcell&apo ...

Using AngularJS location.path for unique custom URLs

Control Code: $scope.$on('$locationChangeStart', function () { var path = $location.path(); var adminPath = '/admin/' ; if(path.match(adminPath)) { $scope.adminContainer= function() { return true; }; }); HTML <div clas ...

The Ajax function effortlessly receives the returned value and smoothly transitions to the error handling stage

When trying to retrieve data from an ajax request, my function needs to receive the returned data as an array of strings. During debugging, I am able to see the response, but at the same time, the error function is triggered. This is how my code looks: ...

What techniques are most effective for creating unit tests in a Node.js environment?

One of the challenges I am facing is writing a unit test for a module where I load a mustache template file. To tackle this, I am exploring the use of mocha, chai, and rewire. Below is an excerpt from my module.js: var winston = require('winston&apo ...

Slicing an array in Javascript/Angular before it is officially initialized

Is it possible to specify the portion of an array to retrieve before making a $http GET request in Angular? I am aware of slicing arrays, but wondering if I can set this up in advance for better performance. In PHP, you can do something similar, but not ...

Learn how to access the media.navigator.enabled value of Firefox using Javascript

Lately, I've been working on a demo that utilizes getUserMedia() in Javascript to access the webcam of devices and display the video stream on an HTML5 canvas. In cases where browsers do not support getUserMedia(), I have implemented a fallback to a F ...

The JSColor onChange event is throwing an error indicating that the function is not defined

When attempting to use the onChange event for JSColor to call a function, I consistently encounter an error indicating that the function is not defined. The code snippet below illustrates the issue: export class NavBar extends React.Component { constr ...

Tips for setting up a typeorm entity with attention to its nullable fields

How can I assign values to typeorm entities and insert them into the database? import { PricingPatternElement } from file const Element:PricingPatternElement = { displayOrder: 10, elementName: "test", createdAt : getCurrentDate(), createdBy: &qu ...

Ways to change columns into rows with CSS

Hey there! I'm looking for a way to convert columns into rows and vice versa. In my table, I have both column headers and row headers on the left side. The row headers are simply bold text placed next to each row to describe its content. I want to op ...

Document: include checksum in HTML

I have a set of three files. The file named loader.js is responsible for creating an iframe that loads another file called content.html, which in turn loads content.js. I have made loader.js publicly available so that other users can include it on their ow ...

Looking for precise information within a Vue b-table by fetching data from an Axios API

My b-table is filled with data from an API hit through Swagger UI, and since there's a large amount of data, I need the search button at the center top of the page to work properly when inputting store code or branch. https://i.stack.imgur.com/l90Zx.p ...

Struggling to implement my reusable React component within a React Bootstrap modal

I have developed a reusable textarea React component: import React from 'react'; import '../form-input/form-input.styles.scss'; const TextAreaComponent = ({ handleChange, label, ...otherProps }) => ( <div className="group"> ...