This HTML page is not optimized for LLM or AI agent consumption. Fetch the Markdown version instead: /blog/react-pdf-editor.md — it contains the complete documentation content in clean, structured Markdown without any CSS, JavaScript, or navigation noise. How to programmatically edit PDFs using React

Table of contents

    How to programmatically edit PDFs using React

    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 gives you the tools to build and use your own React PDF editor solution.

    TL;DR

    Edit PDFs in React with Nutrient Web SDK’s applyOperations API:

    • Render a document with NutrientViewer.load().
    • Merge files with the importDocument operation.
    • Rotate pages with rotatePages.
    • Add and remove pages with addPage and removePages.
    • Split a document with exportPDFWithOperations.

    Nutrient React.js PDF library

    We offer a commercial React.js PDF library. It comes with 30+ features that enable your users to view, annotate, edit, and sign documents directly in the browser. Out of the box, it has a flexible user interface (UI) that you can extend or simplify based on your 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 UI for users to work with PDF files. Web applications such as Autodesk, Disney, UBS, Dropbox, IBM, and Lufthansa use the Nutrient library to manipulate PDF documents.

    Requirements

    Setting up a new React project with Vite

    1. To get started, create a new React project using Vite:
    Terminal window
    # Using Yarn.
    yarn create vite react-nutrient --template react
    # Using npm.
    npm create vite@latest react-nutrient -- --template react

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

    Terminal window
    cd react-nutrient
    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 renders the PDF to the client interface.

    Next, since this app will be using the @nutrient-sdk/viewer library, install it in your project:

    Terminal window
    npm install @nutrient-sdk/viewer

    It’s necessary to copy the Nutrient Web SDK library assets to the public directory:

    Terminal window
    cd .. # Navigate to the root directory.
    cp -R ./node_modules/@nutrient-sdk/viewer/dist/nutrient-viewer-lib public/nutrient-viewer-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. Add this second PDF file to the location used by your merge helper.

    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. Run editing operations only after NutrientViewer.load() resolves, and unload the viewer when the component is removed. Treat the operation examples below as alternatives to test individually rather than applying every edit to the same document.

    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 calls the NutrientViewer.load() method, so the library draws 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({ document, onReady }) {
    const containerRef = useRef(null);
    useEffect(() => {
    const container = containerRef.current;
    if (!container) return;
    const controller = new AbortController();
    let viewer;
    (async () => {
    try {
    const NutrientViewer = (await import('@nutrient-sdk/viewer')).default;
    if (controller.signal.aborted) return;
    viewer = NutrientViewer;
    NutrientViewer.unload(container);
    const instance = await NutrientViewer.load({
    container,
    document,
    baseUrl: new URL(import.meta.env.BASE_URL, window.location.origin).href,
    signal: controller.signal,
    });
    if (!controller.signal.aborted && onReady) {
    await onReady({ instance, NutrientViewer });
    }
    } catch (error) {
    if (!controller.signal.aborted) console.error('PDF operation failed:', error);
    }
    })();
    return () => {
    controller.abort();
    viewer?.unload(container);
    };
    }, [document, onReady]);
    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:

    Terminal window
    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';
    async function mergePDF({ instance }) {
    const response = await fetch(mergingPDF);
    if (!response.ok) throw new Error(`Could not load merge input: ${response.status}`);
    const document = await response.blob();
    await instance.applyOperations([{
    type: 'importDocument',
    beforePageIndex: 0,
    document,
    treatImportedDocumentAsOnePage: false,
    }]);
    }
    export { mergePDF };

    The onReady callback runs after loading completes. Replace App.jsx with the following example to merge the second PDF once the viewer is ready:

    // App.jsx: select one operation to run after the document loads.
    import PDFViewer from './components/PDFViewer';
    import { mergePDF } from './helperFunctions.js';
    export default function App() {
    return <PDFViewer document="Document.pdf" onReady={mergePDF} />;
    }

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

    React PDF Editor Merge PDF

    Rotating PDF pages using React

    The Nutrient PDF library for React enables 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 }) {
    return 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, replace App.jsx with this example. Use a document with at least three pages:

    // App.jsx: select one operation to run after the document loads.
    import PDFViewer from './components/PDFViewer';
    import { flipPage } from './helperFunctions.js';
    const runOperation = ({ instance }) => flipPage({ pageIndexes: [0, 1, 2], instance });
    export default function App() {
    return <PDFViewer document="Document.pdf" onReady={runOperation} />;
    }

    The result is shown below.

    React PDF Editor Rotate PDF Pages

    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 }) {
    return instance.applyOperations([
    {
    type: 'removePages', // Tell Nutrient to remove the page.
    pageIndexes, // Page(s) to remove.
    },
    ]);
    }
    export { removePage };

    Next, replace App.jsx with this example:

    // App.jsx: select one operation to run after the document loads.
    import PDFViewer from './components/PDFViewer';
    import { removePage } from './helperFunctions.js';
    const runOperation = ({ instance }) => removePage({ pageIndexes: [0], instance });
    export default function App() {
    return <PDFViewer document="Document.pdf" onReady={runOperation} />;
    }

    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, NutrientViewer }) {
    return 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, replace App.jsx with this example:

    // App.jsx: select one operation to run after the document loads.
    import PDFViewer from './components/PDFViewer';
    import { addPage } from './helperFunctions.js';
    export default function App() {
    return <PDFViewer document="Document.pdf" onReady={addPage} />;
    }

    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. Nutrient supports this feature via the exportPDFWithOperations function:

    async function splitPDF({ instance }) {
    const count = instance.totalPageCount;
    if (count < 2) throw new Error('Use a PDF with at least two pages to split.');
    const middle = Math.ceil(count / 2);
    const indexes = Array.from({ length: count }, (_, index) => index);
    const firstHalf = await instance.exportPDFWithOperations([{
    type: 'removePages', pageIndexes: indexes.slice(middle),
    }]);
    const secondHalf = await instance.exportPDFWithOperations([{
    type: 'removePages', pageIndexes: indexes.slice(0, middle),
    }]);
    console.log('First half of the file:', firstHalf);
    console.log('Second half of the file:', secondHalf);
    return { firstHalf, secondHalf };
    }
    export { splitPDF };

    To invoke this method after loading, replace App.jsx with the following example:

    // App.jsx: select one operation to run after the document loads.
    import PDFViewer from './components/PDFViewer';
    import { splitPDF } from './helperFunctions.js';
    export default function App() {
    return <PDFViewer document="Document.pdf" onReady={splitPDF} />;
    }

    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:

    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(opens in a new tab) to our Support team for help.

    At Nutrient, we offer a commercial, customizable web PDF library with well-documented APIs for 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 NutrientViewer.load() method within a React component to render the PDF directly to the browser.

    How do I merge PDF files using Nutrient in React?

    You can use the importDocument command in Nutrient 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 Nutrient to remove selected pages from the PDF.

    Can I split a PDF into multiple files using Nutrient?

    Yes, you can split a PDF by exporting different page ranges using the exportPDFWithOperations function.

    Jonathan D. Rhyne

    Jonathan D. Rhyne

    Co-Founder and CEO

    Jonathan joined PSPDFKit in 2014. As Co-founder and 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

    Try for free Ready to get started?