Blog Post

How to Generate Custom PDF Documents in React Native with PSPDFKit

Erhard Brand
Illustration: How to Generate Custom PDF Documents in React Native with PSPDFKit

In this post, you’ll learn how to generate custom PDF documents in your React Native application using PSPDFKit. This process can be useful for creating a PDF from HTML or selecting certain pages from an existing PDF document.

PSPDFKit React Native Library

PSPDFKit offers a commercial React Native library for viewing, generating, 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:

You can view our demo to see what PSPDFKit is capable of and determine how you can use it for your project.

Getting Started

These next sections will walk you through how to get started generating PDFs in React Native.

Dependencies

The following dependencies are necessary:

Information

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

Creating a New Project

This tutorial will focus on React Native iOS, but Android can also be used. Some additional configuration, which can be found in our React Native getting started guide, is required.

In your macOS environment, open your terminal of choice. In the terminal, change your working directory to a suitable location to create your new React Native app.

  1. Create a new React Native project by running the following command:

npx react-native init PSPDFKitDemo
  1. Change your working directory to the newly created project:

cd PSPDFKitDemo
  1. Add the PSPDFKit plugin:

yarn add react-native-pspdfkit@github:PSPDFKit/react-native
  1. Add react-native-fs to the project:

yarn add react-native-fs
  1. Install all the project dependencies:

yarn install
  1. Open your project’s Podfile in a text editor to update the platform to iOS 15:

open ios/Podfile
  1. In your Podfile, update the deployment target version to iOS 15:

- platform :ios, min_ios_version_supported
+ platform :ios, '15.0'
  1. Change the location of the current working directory to the ios folder:

cd ios
  1. Install the CocoaPods dependencies:

pod install
  1. Open your project’s Workspace in XCode:

open PSPDFKitDemo.xcworkspace
  1. Change View controller-based status bar appearance to YES in your project’s Info.plist:

Running the Project

Once you’ve followed the steps above, run your application to confirm the project is correctly set up thus far. From the root of the PSPDFKitDemo project, run:

npx react-native run-ios

If you see the React Native welcome screen, you’re ready to proceed!

Information

The code supplied in the following sections can be added to your application’s App.tsx file inside the render function, prior to returning the PSPDFKitView component that will display your PDF documents.

Generating New PDF Documents in React Native

When generating a new PDF document, the required configuration properties will depend on which operation you’re performing.

Generating a Blank PDF

To generate a blank PDF document, use the BlankPDFConfiguration object to set up your configuration:

import { BlankPDFConfiguration } from 'react-native-pspdfkit';
const Processor = NativeModules.RNProcessor;

const configuration: BlankPDFConfiguration = {
	filePath: `file:///${RNFS.TemporaryDirectoryPath}/newDocument.pdf`,
	width: 595,
	height: 842,
	override: true,
};

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

Generating a PDF from Existing Documents

It might be useful to select specific pages from an existing PDF document or specific pages from different PDF documents and combine them into a new document. Use the DocumentPDFConfiguration object to set up your configuration:

import RNFS from 'react-native-fs';
import { DocumentPDFConfiguration } from 'react-native-pspdfkit';
const Processor = NativeModules.RNProcessor;

const configuration: DocumentPDFConfiguration = {
	filePath: `file:///${RNFS.TemporaryDirectoryPath}/newDocument.pdf`,
	documents: [
		{
			documentPath: 'path/to/document1.pdf',
			pageIndex: 5,
		},
		{
			documentPath: 'path/to/document2.pdf',
			pageIndex: 8,
		},
	],
	override: true,
};

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

Generating a PDF from HTML

You can also convert an HTML string or URL to a PDF document using the Processor component. Use the GeneratePDFConfiguration object to set up your configuration:

import RNFS from 'react-native-fs';
import { GeneratePDFConfiguration } from 'react-native-pspdfkit';
const Processor = NativeModules.RNProcessor;

const configuration: GeneratePDFConfiguration = {
	filePath: `file:///${RNFS.TemporaryDirectoryPath}/newDocument.pdf`,
	override: true,
};

const htmlString = `
<!DOCTYPE html>
<html>
<title>HTML Tutorial</title>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>
`;

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

Generating a PDF from an Image

You can create a PDF from a single image or a series of images. Use the ImagePDFConfiguration object to set up your configuration:

import RNFS from 'react-native-fs';
import { ImagePDFConfiguration } from 'react-native-pspdfkit';
const Processor = NativeModules.RNProcessor;

const configuration: ImagePDFConfiguration = {
	filePath: `file:///${RNFS.TemporaryDirectoryPath}/newImage.png`,
	images: [
		{
			imageUri: 'path/to/image1.png',
			position: 'center',
			pageSize: { width: 540, height: 846 },
		},
		{
			imageUri: 'path/to/image2.png',
			position: 'center',
			pageSize: { width: 540, height: 846 },
		},
	],
	override: true,
};

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

Generating a PDF from a Template

PSPDFKit allows you to generate PDF documents based on templates. Use the TemplatePDFConfiguration object to set up your configuration:

import RNFS from 'react-native-fs';
import { TemplatePDFConfiguration } from 'react-native-pspdfkit';
const Processor = NativeModules.RNProcessor;

const configuration: TemplatePDFConfiguration = {
	filePath: `file:///${RNFS.TemporaryDirectoryPath}/newDocument.pdf`,
	override: true,
	templates: [
		{
			pageSize: { width: 540, height: 846 },
			backgroundColor: 'rgba(0.871, 0.188, 0.643, 0.5)',
			template: 'lines7mm',
			rotation: 90,
			pageMargins: { top: 10, left: 10, right: 10, bottom: 10 },
		},
		{
			pageSize: { width: 540, height: 846 },
			backgroundColor: 'yellow',
			template: 'dot5mm',
		},
	],
};

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

Opening the PDF Documents

Now that you’ve created your new document, you can display it using the PSPDFKitView component and add it to your application’s view stack.

Because the Processor operations mentioned before are all asynchronous, the new PDF documents won’t be immediately available once the component mounts. One way to address this is to first show a loading spinner and use a state property to determine when the new document is available to show.

In your constructor, declare a new state property called documentPath, and call the code to generate your PDF document:

constructor(props: any) {
    super(props);
    this.pdfRef = React.createRef();

    this.state = {
        documentPath: null,
    };
    this.generatePDF();
}

After calling the relevant generate method to create your new document, update the state property with the new document path:

this.setState({ documentPath: fileURL });

Then, update your render function to the following:

render() {
    if (this.state.documentPath === null) {
      return (
        <View style={[styles.container, styles.horizontal]} ref={React.createRef()}>
          <ActivityIndicator size="large" />
        </View>
      );
    } else {
      return (
        <PSPDFKitView
          document={this.state.documentPath}
          configuration={{
            showThumbnailBar: 'scrollable',
            pageTransition: 'scrollContinuous',
            scrollDirection: 'vertical',
          }}
          ref={this.pdfRef}
          fragmentTag="PDF1"
          style={{flex: 1}}
        />
      );
    }
}

Include the following styles referenced by the example code at the end of your file:

const styles = StyleSheet.create({
	container: {
		flex: 1,
		justifyContent: 'center',
	},
	horizontal: {
		flexDirection: 'row',
		justifyContent: 'space-around',
		padding: 10,
	},
});

Conclusion

In this post, you learned how to generate custom PDF documents in React Native using PSPDFKit’s React Native SDK. If you hit any snags, don’t hesitate to reach out to us for assistance. Visit our React Native guides for more information, and try our SDK for free.

Author
Erhard Brand Hybrids Engineer

Erhard is a mobile software engineer with a focus on iOS. He enjoys working in a fast-paced environment and is a solution-focused person. In his spare time, he enjoys spending time with his family and traveling.

Related products

PSPDFKit for React Native

Product page Guides Example Projects

Share post
Free trial Ready to get started?
Free trial