Blog Post

How to Use React Native for Image-to-PDF Conversion

Illustration: How to Use React Native for Image-to-PDF Conversion

In this post, you’ll learn how to use PSPDFKit and React Native to convert an image to a PDF document. Once you’ve completed this tutorial, you’ll have a sample app that will allow you to choose an image from your device and convert it into a PDF document.

PSPDFKit lets you easily add document conversion functionality to your React Native application. Our library supports converting a single image or an array of images to PDF in your workflows.

PSPDFKit React Native PDF Library

PSPDFKit offers a commercial React Native library for viewing, converting, annotating, and editing PDFs. You can use it to quickly add PDF functionality to your React Native applications.

It offers a variety of additional features and capabilities, including:

Requirements

  • A React Native development environment for running React Native projects using the React Native CLI (not the Expo CLI) and configured for the platforms you want to build on — Android, iOS, or both.

Dependencies

Information

The PSPDFKit React Native dependency is installed from the GitHub repository and not the npm registry. To install the PSPDFKit React Native dependency, run yarn add github:PSPDFKit/react-native in your project directory, or npm install github:PSPDFKit/react-native if you’re using npm.

Installing Dependencies

To create a fresh React Native project and integrate PSPDFKit as a dependency, follow our getting started on React Native guide.

To install react-native-fs and react-native-document-picker into your project, follow these steps.

  1. Add react-native-fs:

yarn add react-native-fs
  1. Add react-native-document-picker:

yarn add react-native-document-picker
  1. Install all the dependencies for the project:

yarn install
  1. For iOS, install CocoaPods dependencies:

cd ios
pod install

Implementing a File Picker

Use the DocumentPicker.pickSingle(options) API from react-native-document-picker to bring up a file explorer:

const pickerResult = await DocumentPicker.pickSingle({
	presentationStyle: 'fullScreen',
});

DocumentPicker.pickSingle returns an object containing the URI, type, size, and name of the selected file. The path to the file is made available in pickerResult.uri.

Information

presentationStyle: "fullScreen" is an iOS-only option that presents the picker in full screen. The default is set to pageSheet.

Converting an Image to a PDF Document

  1. Use the RNProcessor class to generate a PDF document from an image. It expects a configuration object, which can be used to customize your document:

const { fileURL } = await Processor.generatePDFFromImages(
	configuration,
);

Refer to this list for an overview of all the configuration options you can use with RNProcessor.

  1. Present the generated PDF document:

PSPDFKit.present(fileURL, { title: 'Generate a PDF from Images' });

This will work on Android without any issues. However, for iOS, you’ll have to write the generated PDF document to its main bundle directory. To achieve this, write a helper function:

const extractAsset = async (fileURL, fileName, callBack) => {
	try {
		await RNFS.readFile(fileURL, 'base64').then((document) => {
			let mainPath = `${RNFS.MainBundlePath}/${documentName(
				fileName,
			)}`;
			RNFS.writeFile(mainPath, document, 'base64')
				.then((success) => {
					callBack(mainPath);
				})
				.catch((e) => console.log(e));
		});
	} catch (error) {
		console.log('Error copying file', error);
	}
};

The documentName function is also a helper function that adds the .pdf extension to the document when it’s missing one:

const documentName = (fileName) => {
	if (
		fileName.toLowerCase().substring(fileName.length - 4) !== '.pdf'
	) {
		return `${fileName}.pdf`;
	}
	return fileName;
};

Putting all the pieces together results in the following code:

import { Platform, NativeModules } from 'react-native';
import RNFS from 'react-native-fs';
import DocumentPicker from 'react-native-document-picker';

const App = () => {
	initPdf();
};

async function initPdf() {
	const { RNProcessor: Processor, PSPDFKit } = NativeModules;
	try {
		const pickerResult = await DocumentPicker.pickSingle({
			presentationStyle: 'fullScreen',
		});

		const configuration = {
			name: 'ImageToPDF',
			images: [
				{
					imageUri: pickerResult.uri,
					position: 'center',
					width: 1920, // Document width.
					height: 1080, // Document height.
				},
			],
			override: true, // `true|false` — If `true`, it will override the existing file with the same name.
		};

		const { fileURL } = await Processor.generatePDFFromImages(
			configuration,
		);

		if (Platform.OS === 'android') {
			PSPDFKit.present(fileURL, {
				title: 'Generate PDF from images',
			});
			return;
		}

		await extractAsset(fileURL, 'sample.pdf', (mainpath) => {
			PSPDFKit.present(mainpath, {
				title: 'Generate a PDF from Images',
			});
		});
	} catch (e) {
		console.log(e.message, e.code);
		alert(e.message);
	}
}

const extractAsset = async (fileURL, fileName, callBack) => {
	try {
		await RNFS.readFile(fileURL, 'base64').then((document) => {
			let mainPath = `${RNFS.MainBundlePath}/${documentName(
				fileName,
			)}`;
			RNFS.writeFile(mainPath, document, 'base64')
				.then((success) => {
					callBack(mainPath);
				})
				.catch((e) => console.log(e));
		});
	} catch (error) {
		console.log('Error copying file', error);
	}
};

const documentName = (fileName) => {
	if (
		fileName.toLowerCase().substring(fileName.length - 4) !== '.pdf'
	) {
		return `${fileName}.pdf`;
	}
	return fileName;
};

export default App;
Information

Replace the code in App.js with the code above for a working example.

  1. You can now launch the application:

react-native run-android

GIF showing the result of react-native run-android

react-native run-ios

GIF showing the result of react-native run-ios

Conclusion

In this post, you learned how to convert an image to a PDF document in React Native using PSPDFKit. In case of any issues, don’t hesitate to reach out to our Support team for help.

PSPDFKit for React Native is an SDK for viewing, annotating, and editing PDFs. It offers developers the ability to quickly add PDF functionality to any React Native application. Try it for free, or visit our demo to see it in action.

Share Post
Free 60-Day Trial Try PSPDFKit in your app today.
Free Trial

Related Articles

Explore more
PRODUCTS  |  React Native • Releases

PSPDFKit 2.9 for React Native Adds Main Toolbar Customization

PRODUCTS  |  React Native • Releases

PSPDFKit 2.8 for React Native Adds TypeScript Support

CUSTOMER STORIES  |  Case Study • React Native • iOS • Android

Case Study: How Trinoor Uses PSPDFKit to Drive Operational Excellence with Flexible, Mobile Applications for the Energy and Utilities Market