How to Programmatically Edit PDFs Using React
This article was first published in March 2023 and was updated in August 2024.
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.
Setting Up a New React Project with Vite
-
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.
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.
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.
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.
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.
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.
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.
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.
FAQ
Here are a few frequently asked questions about editing PDFs in React.
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.