DEV Community

Cover image for How to Generate PDF from Images and Views in React Native: A Complete Guide for Mobile Developers
Benjamin Eruvieru
Benjamin Eruvieru

Posted on

How to Generate PDF from Images and Views in React Native: A Complete Guide for Mobile Developers

PDF generation is a crucial feature for many mobile applications, whether you’re building a document scanner, creating reports, or allowing users to save content for offline viewing. In this comprehensive guide, we’ll explore two powerful approaches to generating PDFs in React Native: converting images directly to PDF and capturing views as images before converting them to PDF format.

Method 1: Converting Images to PDF Using react-native-pdf-from-image

Let’s start with the straightforward approach of converting images to PDF using the react-native-pdf-from-image library.

Installation

First, install the required dependency:

npm install react-native-pdf-from-image
# or using yarn
yarn add react-native-pdf-from-image
Enter fullscreen mode Exit fullscreen mode

For iOS, you’ll need to install the pods:

cd ios && pod install
Enter fullscreen mode Exit fullscreen mode

Basic Implementation

Here’s a simple example of converting multiple images to a single PDF:

import { createPdf } from 'react-native-pdf-from-image';

const images = ['path/to/image1.jpg'];

const { filePath } = createPdf({
  imagePaths: images,
  name: 'myPdf',
  paperSize: 'A4'
});
Enter fullscreen mode Exit fullscreen mode

Note: When using the old architecture, make sure to await the createPdf function as it returns a Promise.

import { createPdf } from 'react-native-pdf-from-image';

// Old Architecture
const generatePdf = async () => {
  const images = ['path/to/image1.jpg'];
  const { filePath } = await createPdf({
    imagePaths: images,
    name: 'myPdf'
  });
};
Enter fullscreen mode Exit fullscreen mode

Method 2: Converting Views to PDF Using react-native-view-shot

Sometimes you need to convert an actual React Native view into a PDF. This requires a two-step process: first capturing the view as an image using react-native-view-shot, then converting that image to PDF.

Installation

Install both required libraries:

npm install react-native-view-shot react-native-pdf-from-image
# or using yarn
yarn add react-native-view-shot react-native-pdf-from-image
Enter fullscreen mode Exit fullscreen mode

Implementation

Here’s a complete example showing how to capture a view and convert it to PDF:

import ViewShot from 'react-native-view-shot';
import { createPdf } from 'react-native-pdf-from-image';

const ViewToPDFComponent = () => {
  // Reference to the ViewShot component
  const viewShotRef = useRef(null);

  const generatePDFFromView = async () => {
    try {
      // Step 1: Capture the view as an image
      const imageURI = await viewShotRef.current.capture();


      // No need to await if on new arch
      const { filePath } = await createPDF({
        imagePaths: [imageURI],
        name:'MyPdf',
        pageSize: 'A4' // Optional
      });

      console.log('View successfully converted to PDF:', pdfFile);
    } catch (error) {
      console.error('Error converting view to PDF:', error);
    }
  };

  return (
    <View>
      <ViewShot ref={viewShotRef} options={{ format: 'jpg', quality: 0.9 }}>
        {/* Your view content goes here */}
        <View style={styles.container}>
          <Text style={styles.title}>This will be converted to PDF</Text>
          <Image source={require('./your-image.png')} />
          {/* Add any other components you want in the PDF */}
        </View>
      </ViewShot>

      <Button 
        title="Generate PDF" 
        onPress={generatePDFFromView} 
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 20,
    backgroundColor: 'white'
  },
  title: {
    fontSize: 24,
    marginBottom: 16
  }
});
Enter fullscreen mode Exit fullscreen mode

How It Works

  1. Capture the View: The ViewShot component wraps the view you wish to convert to PDF. When the button is pressed, it calls capture(), which returns the file URI of the captured image.

  2. Generate the PDF: Using the createPdf function from react‑native‑pdf‑from‑image, the captured image URI is passed as an array. The PDF is generated and stored at the returned file path.

This method is especially useful when you want to export a complex view — such as a summary screen, report, or custom layout — as a PDF document.

Conclusion

Generating PDFs in React Native doesn’t have to be complicated. With react-native-pdf-from-image for direct image conversion and react-native-view-shot for dynamic views, you can easily create professional PDFs tailored to your app’s needs. Start implementing these solutions today and enhance your app’s functionality!

Like this guide? Share it with your network and stay tuned for more React Native tutorials!

Top comments (0)