Nutrient

Home

SDK

Software Development Kits

Low-Code

IT Document Solutions

Workflow

Workflow Automation Platform

DWS API

Document Web Services

T
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Company

About

Team

Careers

Contact

Security

Partners

Legal

Resources

Blog

Events

Try for free

Contact Sales
Contact sales
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

products

Web

Web

Document Authoring

AI Assistant

Salesforce

Mobile

iOS

Android

visionOS

Flutter

React Native

MAUI

Server

Document Engine

Document Converter Services

.NET

Java

Node.js

AIDocument Processing

All products

solutions

USECASES

Viewing

Editing

OCR and Data Extraction

Signing

Forms

Scanning & Barcodes

Markup

Generation

Document Conversion

Redaction

Intelligent Doc. Processing

Collaboration

Authoring

Security

INdustries

Aviation

Construction

Education

Financial Services

Government

Healthcare

Legal

Life Sciences

All Solutions

Docs

Guides overview

Web

AIAssistant

Document Engine

iOS

Android

visionOS

Java

Node.js

.NET

Document Converter Services

Downloads

Demo

Support

Log in

Resources

Blog

Events

Pricing

Try for free

Free Trial

Company

About

Security

Partners

Legal

Contact Sales
Contact Sales
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

products

Products overview

Document Converter

Document Editor

Document Searchability

Document Automation Server

Integrations

SharePoint

Power Automate

Nintex

OneDrive

Teams

Window Servers

solutions

USECASES

Conversion

Editing

OCR Data Extraction

Tagging

Security Compliance

Workflow Automation

Solutions For

Overview

Legal

Public Sector

Finance

All Solutions

resources

Help center

Document Converter

Document Editor

Document Searchability

Document Automation Server

learn

Blog

Customer stories

Events

Support

Log in

Pricing

Try for free

Company

About

Security

Partners

Legal

Contact Sales
Contact Sales
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Product

Product overview

Process Builder

Form Designer

Document Viewer

Office Templating

Customization

Reporting

solutions

Industries

Healthcare

Financial

Manufacturing

Pharma

Education

Construction

Nonprofit

Local Government

Food and Beverage

Departments

ITServices

Finance

Compliance

Human Resources

Sales

Marketing

Services

Overview

Capex-accelerator

Process Consulting

Workflow Prototype

All Solutions

resources

Help center

guides

Admin guides

End user guides

Workflow templates

Form templates

Training

learn

Blog

Customer stories

Events

Support

Pricing

Support

Company

About

Security

Partners

Legal

Try for Free
Contact Sales
Try for Free
Contact Sales
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Services

Generation

Editing

Conversion

Watermarking

OCR

Table Extraction

Pricing

Docs

Log in

Try for Free
Try for Free

Free trial

Blog post

How to Programmatically Edit PDFs Using React

Jonathan D. Rhyne Jonathan D. Rhyne

Table of contents

  • PSPDFKit React.js PDF Library
    • Requirements
  • Setting Up a New React Project with Vite
    • Rendering a PDF Page Using React
    • Merging PDF Pages Using React
    • Rotating PDF Pages Using React
    • Removing PDF Pages Using React
    • Adding PDF Pages Using React
    • Splitting PDFs Using React
  • Additional Resources
  • Conclusion
  • FAQ
Illustration: How to Programmatically Edit PDFs Using React

In this article, you’ll learn how to programmatically edit PDF files using React and PSPDFKit. More specifically, it’ll cover rendering, merging, and rotating PDFs; removing and adding PDF pages; and splitting PDFs. This will give you all the tools required to easily build and use your own React PDF editor solution.

PSPDFKit React.js PDF Library

We offer a commercial React.js PDF library that’s easy to integrate. It comes with 30+ features that allow your users to view, annotate, edit, and sign documents directly in the browser. Out of the box, it has a polished and flexible user interface (UI) that you can extend or simplify based on your unique use case.

  • A prebuilt and polished UI
  • 15+ annotation tools
  • Support for multiple file types
  • Dedicated support from engineers

PSPDFKit has developer-friendly documentation and offers a beautiful UI for users to work with PDF files easily. Web applications such as Autodesk, Disney, UBS, Dropbox, IBM, and Lufthansa use the PSPDFKit library to manipulate PDF documents.

Requirements

  • Node.js — Learn more about installing Node.js on the official website.

  • A package manager — Yarn or npm

Setting Up a New React Project with Vite

  1. To get started, create a new React project using Vite:

# Using Yarn
yarn create vite react-pspdfkit --template react

# Using npm
npm create vite@latest react-pspdfkit -- --template react

After the project is created, navigate to the project directory:

cd react-pspdfkit
cd src
mkdir components
cd components
touch PDFViewer.jsx # Will render your document to the client's browser.
cd .. # Go back to the `src` directory.

Here, you created a new file called PDFViewer.jsx within the components directory. This file will be used to render the PDF to the client interface.

Next, since this app will be using the pspdfkit library, install it in your project:

npm install pspdfkit

It’s necessary to copy the PSPDFKit for Web library assets to the public directory:

cd .. # Navigate to the root directory.

cp -R ./node_modules/pspdfkit/dist/pspdfkit-lib public/pspdfkit-lib

When that’s done, navigate to your public directory. Here, add a PDF file of your choice. You can use this demo document as an example.

You’ll need two files to merge PDFs in React, so you can add this PDF file within your src folder.

As the last step, create a new file within your src folder called helperFunctions.js. As the name suggests, this file will hold the utility methods needed to carry out the outlined tasks in your project.

Your file structure will now look like what’s shown in the image below.

React PDF Editor folder structure

Now you can start working with PDFs.

Rendering a PDF Page Using React

In this section, you’ll learn how render a PDF to the client interface using React. To do this, use this code in helperFunctions.js:

async function loadPDF({ PSPDFKit, container, document, baseUrl }) {
	const instance = await PSPDFKit.load({
		// Container where PSPDFKit should be mounted.
		container,
		// The document to open.
		document,
		baseUrl,
	});
	return instance;
}
export { loadPDF }; // Link this function with your project.

When React invokes the loadPDF function, the app will call the PSPDFKit.load() method. As a result, the library will now draw the PDF to the UI.

All that’s left is to use your newly created function within your app. To do so, go to the components/PDFViewer.jsx file and paste this snippet:

import { useEffect, useRef } from 'react';

export default function PDFViewer(props) {
	const containerRef = useRef(null);

	useEffect(() => {
		const container = containerRef.current;
		let PSPDFKit;

		(async function () {
			PSPDFKit = await import('pspdfkit');

			if (PSPDFKit) {
				PSPDFKit.unload(container); // Ensure that there's only one PSPDFKit instance.
			}
			const instance = await PSPDFKit.load({
				container,
				document: props.document,
				baseUrl: `${window.location.protocol}//${
					window.location.host
				}/${import.meta.env.BASE_URL}`,
			});
		})();

		return () => {
			// Unload PSPDFKit instance when the component is unmounted
			PSPDFKit && PSPDFKit.unload(container);
		};
	}, [props.document]);

	return (
		<div
			ref={containerRef}
			style={{ width: '100%', height: '100vh' }}
		/>
	);
}

As the last step, you’ll render the PDFViewer component to the Document Object Model (DOM). To do so, replace the contents of App.jsx with this code:

import PDFViewer from './components/PDFViewer';

function App() {
	return (
		<div className="App" style={{ width: '100vw' }}>
			<PDFViewer document={'Document.pdf'} />{' '}
			{/*Render the Document.pdf file*/}
		</div>
	);
}
export default App;

Make sure to replace Document.pdf with the name of your PDF file.

To run your app, use this command:

npm run dev

The result is shown below.

React PDF Editor Rendering a PDF

Merging PDF Pages Using React

In this section, you’ll use the importDocument command to merge two documents.

To implement merge functionality in your app, add this block of code in helperFunctions.js:

import mergingPDF from './examplePDF.pdf'; // Bring in your PDF file.

async function mergePDF({ instance }) {
	fetch(mergingPDF) // Fetch the contents of the file to merge.
		.then((res) => {
			if (!res.ok) {
				throw res; // If an error occurs, use the `console.log()` function.
			}
			return res;
		})
		.then((res) => res.blob()) // Return its blob data.
		.then((blob) => {
			instance.applyOperations([
				{
					type: 'importDocument', // Tell the program that you'll merge a document.
					beforePageIndex: 0, // Merge the document at the first page.
					document: blob, // Use the document's blob data for merging.
					treatImportedDocumentAsOnePage: false,
				},
			]);
		});
}
export { mergePDF };

The last step is to invoke the mergePDF method:

// components/PDFViewer.jsx

import { mergePDF } from '../helperFunctions.js';

useEffect(() => {
	// More code...
	mergePDF({ instance }); // Merge the PDF with your current instance.
}, []);

This final result will look like what’s shown below.

React PDF Editor Merge PDF

Rotating PDF Pages Using React

The PSPDFKit PDF library for React allows users to rotate page content via the rotatePages command.

To rotate a page, add this block of code in helperFunctions.js:

function flipPage({ pageIndexes, instance }) {
	instance.applyOperations([
		{
			type: 'rotatePages', // Tell PSPDFKit to rotate the page.
			pageIndexes, // Page number(s) to select and rotate.
			rotateBy: 180, // Rotate by 180 degrees. This will flip the page.
		},
	]);
}
export { flipPage };

All that’s left is to use it in your project. To do so, add this piece of code in the PDFViewer.jsx module:

// components/PDFViewer.jsx
import { flipPage } from '../helperFunctions.js';
//..
useEffect(() => {
	// More code...
	// Flip the first, second, and third page of the PDF:
	flipPage({ pageIndexes: [0, 1, 2], instance });
}, []);

The result is shown below.

React PDF Editor Rotate PDF Pages

Removing PDF Pages Using React

To remove pages from a PDF, use PSPDFKit’s removePages operation. Type this snippet in helperFunctions.js:

function removePage({ pageIndexes, instance }) {
	instance.applyOperations([
		{
			type: 'removePages', // Tell PSPDFKit to remove the page.
			pageIndexes, // Page(s) to remove.
		},
	]);
}
export { removePage };

Next, write this in PDFViewer.jsx:

import { removePage } from '../helperFunctions.js';

useEffect(() => {
	// More code.
	// Only remove the first page from this document:
	removePage({ pageIndexes: [0], instance });
}, []);

This will remove the selected pages from a PDF.

React PDF Editor Remove PDF Page

Adding PDF Pages Using React

To add a page to a document, use the addPage command:

// helperFunctions.js
function addPage({ instance, PSPDFKit }) {
	instance.applyOperations([
		{
			type: 'addPage', // Add a page to the document.
			afterPageIndex: instance.totalPageCount - 1, // Append the page at the end.
			backgroundColor: new PSPDFKit.Color({
				r: 100,
				g: 200,
				b: 255,
			}), // Set the new page background color.
			pageWidth: 750, // Dimensions of the page:
			pageHeight: 1000,
		},
	]);
}
export { addPage };

Next, use this function in your app:

// components/PDFViewer.jsx

import { addPage } from '../helperFunctions.js';

useEffect(() => {
	// More code...
	addPage({ instance, PSPDFKit });
}, []);

The result is shown below.

React PDF Editor Adding PDF Pages

Splitting PDFs Using React

In some cases, users might want to split their documents into separate files. PSPDFKit supports this feature via the exportPDFWithOperation function:

// helperFunctions.js
async function splitPDF({ instance }) {
	// Export the `ArrayBuffer` data of the first half of the document.
	const firstHalf = await instance.exportPDFWithOperations([
		{
			type: 'removePages',
			pageIndexes: [0, 1, 2], // Split the first, second, and third page.
		},
	]);
	// Export the `ArrayBuffer` data of the second half of the document.
	const secondHalf = await instance.exportPDFWithOperations([
		{
			type: 'removePages',
			pageIndexes: [3, 4], // Extract the fourth and fifth pages.
		},
	]);
	// Log the `ArrayBuffer` data of both of these files:
	console.log('First half of the file:', firstHalf);
	console.log('Second half of the file:', secondHalf);
}
export { splitPDF };

To invoke this method, write this code within your PDFViewer.jsx method:

// components/PDFViewer.jsx

import { splitPDF } from '../helperFunctions.js';

useEffect(() => {
	// More code...
	splitPDF({ instance });
}, []);

The result is shown below.

React PDF Editor Remove PDF Page

Additional Resources

For more information, here are a few guides to help you get started editing PDFs:

  • Overview to PDF editing with PSPDFKit

  • Headless editing

  • Editing page labels

  • Customizing the PDF editing toolbar and UI

Conclusion

In this article, you learned about editing PDFs using React and PSPDFKit. If you encountered any difficulties, we encourage you to deconstruct and play with the code so you can fully understand its inner workings. If you hit any snags, don’t hesitate to reach out to our Support team for help.

At PSPDFKit, we offer a commercial, feature-rich, and completely customizable web PDF library that’s easy to integrate and comes with well-documented APIs to handle advanced use cases. Try it for free, or visit our demo to see it in action.

FAQ

How can I render a PDF in a React application? Use the PSPDFKit.load() method within a React component to render the PDF directly to the browser.
How do I merge PDF files using PSPDFKit in React? You can use the importDocument command in PSPDFKit to merge two or more PDF files programmatically.
Is it possible to rotate pages in a PDF with React? Yes, you can rotate pages using the rotatePages command by specifying the page indices and rotation angle.
How can I remove specific pages from a PDF in React? Use the removePages operation in PSPDFKit to remove selected pages from the PDF.
Can I split a PDF into multiple files using PSPDFKit? Yes, you can split a PDF by exporting different page ranges using the exportPDFWithOperations function.
Author
Jonathan D. Rhyne
Jonathan D. Rhyne Co-Founder and CEO

Jonathan joined Nutrient in 2014. As CEO, Jonathan defines the company’s vision and strategic goals, bolsters the team culture, and steers product direction. When he’s not working, he enjoys being a dad, photography, and soccer.

Explore related topics

React How To
Free trial Ready to get started?
Free trial

Related articles

Explore more
SDKDEVELOPMENTPDF ViewerReactTipsDevelopment

Comparing the best React PDF viewers for developers

SDKTUTORIALSWebReactHow To

How to export to PDF using React

SDKTUTORIALSWebJavaScriptHow Tohtml2pdfReact

HTML to PDF in React: Convert HTML to PDF using html2pdf.js

Company
About
Security
Team
Careers
We're hiring
Partners
Legal
Products
SDK
Low-Code
Workflow
DWS API
resources
Blog
Events
Customer Stories
Tutorials
News
connect
Contact
LinkedIn
YouTube
Discord
X
Facebook
Popular
Java PDF Library
Tag Text
PDF SDK Viewer
Tag Text
React Native PDF SDK
Tag Text
PDF SDK
Tag Text
iOS PDF Viewer
Tag Text
PDF Viewer SDK/Library
Tag Text
PDF Generation
Tag Text
SDK
Web
Tag Text
Mobile/VR
Tag Text
Server
Tag Text
Use Cases
Tag Text
Industries
Tag Text
Resources
Blog
Tag Text
Events
Customer Stories
Tag Text
Tutorials
Tag Text
Features List
Tag Text
Compare
Tag Text
community
Free Trial
Tag Text
Documentation
Tag Text
Nutrient Portal
Tag Text
Contact Support
Tag Text
Company
About
Tag Text
Security
Tag Text
Careers
Tag Text
Legal
Tag Text
Pricing
Tag Text
Partners
Tag Text
connect
Contact
Tag Text
LinkedIn
Tag Text
YouTube
Tag Text
Discord
Tag Text
X
Tag Text
Facebook
Tag Text
low-code
Document Converter
Tag Text
Document Editor
Tag Text
Document Automation Server
Tag Text
Document Searchability
Tag Text
Use Cases
Tag Text
Industries
Tag Text
Resources
Blog
Tag Text
Events
Customer Stories
Tag Text
Support
Help Center
Tag Text
Contact Support
Tag Text
Log In
Tag Text
Company
About
Tag Text
Careers
Tag Text
Security
Tag Text
Legal
Tag Text
Pricing
Tag Text
Partners
Tag Text
connect
Contact
Tag Text
LinkedIn
Tag Text
YouTube
Tag Text
Discord
Tag Text
X
Tag Text
Facebook
Tag Text
Popular
Approvals matrix
Tag Text
BPMS
Tag Text
Budgeting process
Tag Text
CapEx approval
Tag Text
CapEx automation
Tag Text
Document approval
Tag Text
Task automation
Tag Text
workflow
Overview
Tag Text
Services
Tag Text
Industries
Tag Text
Departments
Tag Text
Resources
Blog
Tag Text
Events
Customer Stories
Tag Text
Support
Help Center
Tag Text
FAQ
Tag Text
Troubleshooting
Tag Text
Contact Support
Tag Text
Company
About
Tag Text
Careers
Tag Text
Security
Tag Text
Legal
Tag Text
Pricing
Tag Text
Partners
Tag Text
connect
Contact
Tag Text
LinkedIn
Tag Text
YouTube
Tag Text
Discord
Tag Text
X
Tag Text
Facebook
Tag Text
DWS api
PDF Generator
Tag Text
Editor
Tag Text
Converter API
Tag Text
Watermark
Tag Text
OCR
Tag Text
Table Extraction
Tag Text
Resources
Log in
Tag Text
Help Center
Tag Text
Support
Tag Text
Blog
Tag Text
Company
About
Tag Text
Careers
Tag Text
Security
Tag Text
Pricing
Tag Text
Legal
Privacy
Tag Text
Terms
Tag Text
connect
Contact
Tag Text
X
Tag Text
YouTube
Tag Text
Discord
Tag Text
LinkedIn
Tag Text
Facebook
Tag Text

Copyright 2025 Nutrient. All rights reserved.

Thank you for subscribing to our newsletter!

We’re thrilled to have you join our community. You’re now one step closer to receiving the latest updates, exclusive content, and special offers directly in your inbox.

This builtin is not currently supported: DOM

PSPDFKit is now Nutrient. We've consolidated our group of trusted companies into one unified brand: Nutrient. Learn more

This builtin is not currently supported: DOM

PSPDFKit is now Nutrient. We've consolidated our group of trusted companies into one unified brand: Nutrient. Learn more

This builtin is not currently supported: DOM

New Feature Release. Tap into revolutionary AI technology to instantly complete tasks, analyze text, and redact key information across your documents. Learn More or View Showcase

This builtin is not currently supported: DOM

Aquaforest and Muhimbi are now Nutrient. We've consolidated our group of trusted companies into one unified brand: Nutrient. Learn more

This builtin is not currently supported: DOM

Integrify is now Nutrient. We've consolidated our group of trusted companies into one unified brand: Nutrient. Learn more

This builtin is not currently supported: DOM

Join us on April 15th. Join industry leaders, product experts, and fellow professionals at our exclusive user conference. Register for conference