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 Nutrient 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.

Nutrient 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.

Nutrient React Native PDF library

Nutrient 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 Nutrient React Native dependency is installed from the GitHub repository and not the npm registry. To install the Nutrient React Native dependency, run yarn add react-native-pspdfkit@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 Nutrient 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 Nutrient. In case of any issues, don’t hesitate to reach out to our Support team for help.

Nutrient React Native SDK 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.

FAQ

Here are a few frequently asked questions about using Nutrient and React Native.

How do I install Nutrient React Native SDK?

You can install Nutrient React Native SDK by running yarn add react-native-pspdfkit@github:PSPDFKit/react-native or npm install github:PSPDFKit/react-native.

Can I use Nutrient with Expo CLI?

No, Nutrient React Native SDK requires using the React Native CLI, as Expo doesn’t fully support native modules like Nutrient.

Does Nutrient support converting multiple images to PDF?

Yes, Nutrient allows you to convert a single image or multiple images into a PDF document.

Is Nutrient available for both Android and iOS?

Yes, Nutrient supports both Android and iOS, but certain platform-specific configurations are required for each.

Do I need to write additional code for handling PDFs on iOS?

Yes, for iOS, you need to write the generated PDF file to the main bundle directory using a file system module like react-native-fs.

Explore related topics

Share post
Free trial Ready to get started?
Free trial