Blog Post

How to Programmatically Edit PDFs Using React

Hussain Arif
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, DocuSign, Dropbox, IBM, and Lufthansa use the PSPDFKit library to manipulate PDF documents.

Requirements

Project Setup

First, initialize a boilerplate React project with create-react-app:

npx create-react-app react-pspdfkit # Replace `react-pspdfkit` with your project name.

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

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

Here, you created a new file called PDFViewer.js 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.js 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}/${process.env.PUBLIC_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.js with this code:

import PDFViewer from './components/PDFViewer';

function App() {
	return (
		<div className="App">
			<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 start

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

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.js module:

// components/PDFViewer.js
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.js:

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

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.js method:

// components/PDFViewer.js

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

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

The result is shown below.

React PDF Editor Remove PDF Page

Information

Interact with the sandbox by clicking the left rectangle icon and selecting Editor > Show Default Layout. To edit, sign in with GitHub — click the rectangle icon again and choose Sign in. To preview the result, click the rectangle icon once more and choose Editor > Embed Preview. For the full example, click the Open Editor button. Enjoy experimenting with the project!

Additional Resources

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

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.

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

Related Articles

Explore more
TUTORIALS  |  Web • JavaScript • How To • html2pdf • React

How to Convert HTML to PDF in React Using html2pdf

PRODUCTS  |  Web • React • Signing • How To

How to Add Digital Signatures to PDFs Using React

TUTORIALS  |  Web • React • How To • Excel Viewer

How to Build a React.js Excel (XLS/XLSX) Viewer