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 will give you all the tools required to easily 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 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

    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 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:

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

    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 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:

    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'; // 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 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:

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

    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 }) {
    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:

    components/PDFViewer.jsx
    import { addPage } from '../helperFunctions.js';
    useEffect(() => {
    // More code...
    addPage({ instance, NutrientViewer });
    }, []);

    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:

    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:

    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.

    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?