Categories
React Native Answers

How to create PDF from HTML with React Native?

Spread the love

To create PDF from HTML with React Native, we use the react-native-html-to-pdf library.

To install it, we run

npm i react-native-html-to-pdf

Then we use it by writing

import React, { Component } from 'react';

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

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

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

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

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

to add the createPdf method.

We call RNHTMLtoPDF.convert with the options obnject to create the PDF.

The html property has the content of the PDF.

And then we get the PDF file path from file.filePath.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *