How to programmatically edit PDFs using React
Table of contents
In this article, you’ll learn how to programmatically edit PDF files using React and Nutrient. 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.
Edit PDFs in React with Nutrient Web SDK’s applyOperations API:
- Render a document with
NutrientViewer.load(). - Merge files with the
importDocumentoperation. - Rotate pages with
rotatePages. - Add and remove pages with
addPageandremovePages. - Split a document with
exportPDFWithOperations.
Nutrient 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
Nutrient 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 Nutrient library to manipulate PDF documents.
Requirements
- Node.js(opens in a new tab) — Learn more about installing Node.js on the official website(opens in a new tab)
- A package manager — Yarn(opens in a new tab) or npm(opens in a new tab)
Setting up a new React project with Vite
- To get started, create a new React project using Vite:
# Using Yarnyarn create vite react-nutrient --template react
# Using npmnpm create vite@latest react-nutrient -- --template reactAfter the project is created, navigate to the project directory:
cd react-nutrientcd srcmkdir componentscd componentstouch 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 @nutrient-sdk/viewer library, install it in your project:
npm install @nutrient-sdk/viewerIt’s necessary to copy the Nutrient Web SDK library assets to the public directory:
cd .. # Navigate to the root directory.
cp -R ./node_modules/@nutrient-sdk/viewer/dist/nutrient-viewer-lib public/nutrient-viewer-libWhen 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(opens in a new tab) 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 to render a PDF to the client interface using React. To do this, use this code in helperFunctions.js:
async function loadPDF({ NutrientViewer, container, document, baseUrl }) { const instance = await NutrientViewer.load({ // Container where Nutrient 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 NutrientViewer.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 NutrientViewer;
(async function () { NutrientViewer = await import('@nutrient-sdk/viewer');
if (NutrientViewer) { NutrientViewer.unload(container); // Ensure that there's only one Nutrient instance. } const instance = await NutrientViewer.load({ container, document: props.document, baseUrl: `${window.location.protocol}//${ window.location.host }/${import.meta.env.BASE_URL}`, }); })();
return () => { // Unload Nutrient instance when the component is unmounted NutrientViewer && NutrientViewer.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 devThe 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:
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 Nutrient 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 Nutrient 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:
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 Nutrient’s removePages operation. Type this snippet in helperFunctions.js:
function removePage({ pageIndexes, instance }) { instance.applyOperations([ { type: 'removePages', // Tell Nutrient 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:
function addPage({ instance, NutrientViewer }) { instance.applyOperations([ { type: 'addPage', // Add a page to the document. afterPageIndex: instance.totalPageCount - 1, // Append the page at the end. backgroundColor: new NutrientViewer.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:
import { addPage } from '../helperFunctions.js';
useEffect(() => { // More code... addPage({ instance, NutrientViewer });}, []);The result is shown below.

Splitting PDFs using React
In some cases, users might want to split their documents into separate files. Nutrient supports this feature via the exportPDFWithOperations function:
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:
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:
- Overview to PDF editing with Nutrient
- Headless editing
- Editing page labels
- Customizing the PDF editing toolbar and UI
Conclusion
In this article, you learned about editing PDFs using React and Nutrient. 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 Nutrient, 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 reading
- How to display a PDF in React — Step-by-step guide to rendering PDFs in React applications
- How to build a React.js file viewer: PDF, image, MS Office — Build a multi-format file viewer in React
- Top five document viewers for developers — Compare DOCX and PDF viewer libraries side by side
- How to choose the best PDF viewer for your business — A buyer’s guide covering features, pricing, and evaluation criteria
FAQ
Use the NutrientViewer.load() method within a React component to render the PDF directly to the browser.
You can use the importDocument command in Nutrient to merge two or more PDF files programmatically.
Yes, you can rotate pages using the rotatePages command by specifying the page indices and rotation angle.
Use the removePages operation in Nutrient to remove selected pages from the PDF.
Yes, you can split a PDF by exporting different page ranges using the exportPDFWithOperations function.