How to Edit PDF in React JS

How to Edit PDF in React JS

Editing PDFs in a web application can be a complex task, but with the help of ReactJS and some external libraries, it’s definitely possible. In this article, we’ll explore the steps to edit PDFs in ReactJS and provide a comprehensive overview of the process.

What You’ll Need

Before we dive into the code, make sure you have the following installed:

  • Node.js (for running ReactJS)
  • yarn (for managing dependencies)
  • A code editor or IDE of your choice (such as Visual Studio Code or IntelliJ IDEA)
  • A PDF file you’d like to edit

Step 1: Set up your ReactJS Project

Create a new ReactJS project using create-react-app:

npx create-react-app my-pdf-editor

This will setup a new ReactJS project called my-pdf-editor with the necessary files and directories.

Step 2: Choose a PDF Editor Library

There are several libraries available that can help you edit PDFs in ReactJS. Some popular options include:

  • pdf-lib: A pure JavaScript PDF library for creating, editing, and manipulating PDFs.
  • jsPDF: A JavaScript library that allows you to generate and edit PDFs.
  • pdfmake: A library that allows you to generate PDFs from scratch.

For this example, we’ll use pdf-lib.

Step 3: Install pdf-lib

In your project directory, run the following command to install pdf-lib:

yarn add pdf-lib

Step 4: Load the PDF File

Create a new file called PDFEditor.js and add the following code to load the PDF file:

import { pdf } from 'pdf-lib';

const PDFEditor = () => {
  const [pdfFile, setPdfFile] = useState(null);

  const handlePdfLoad = (event) => {
    const pdfBytes = event.target.files[0];
    setPdfFile(pdfBytes);
  };

  return (
    <div>
      <input type="file" onChange={handlePdfLoad} />
      {pdfFile && <PDFViewer pdfFile={pdfFile} />}
    </div>
  );
};

export default PDFEditor;

This code uses the useState hook to store the loaded PDF file in state. The handlePdfLoad function is called when a new PDF file is selected. The PDFViewer component will be rendered once the PDF file is loaded.

Step 5: Create the PDF Viewer

Create a new file called PDFViewer.js and add the following code to render the PDF file:

import { PDFDocument } from 'pdf-lib';
import React, { useEffect, useState } from 'react';

const PDFViewer = ({ pdfFile }) => {
  const [pdf, setPdf] = useState(null);

  useEffect(() => {
    if (pdfFile) {
      const pdfBytes = new Uint8Array(pdfFile);
      const pdfDoc = new PDFDocument();
      pdfDoc.load(pdfBytes);
      setPdf(pdfDoc);
    }
  }, [pdfFile]);

  return (
    <div>
      {pdf && (
        <canvas
          width={pdf.getNumPages() * 100}
          height={pdf.getPage(0).getHeight()}
          ref={(canvas) => {
            const canvasContext = canvas.getContext('2d');
            pdf.getPages().forEach((page, index) => {
              canvasContext.drawImage(
                page.scaleCanvas({
                  width: page.getWidth() * 100,
                  height: page.getHeight(),
                }),
                index * page.getWidth() * 100,
                0
              );
            });
          }}
        />
      )}
    </div>
  );
};

export default PDFViewer;

This code uses the PDFDocument class from pdf-lib to load the PDF file. The PDFViewer component is rendered once the PDF file is loaded. It uses the useEffect hook to load the PDF file and scale the pages to fit within the canvas element.

Step 6: Add Editing Capabilities

To add editing capabilities, you can use the drawImage method of the canvas element to draw shapes, text, and other objects on top of the PDF pages.

For example, you can add a button to add a text annotation to the PDF page:

import React, { useState } from 'react';

const AddAnnotationButton = ({ pdf, canvas }) => {
  const [annotationText, setAnnotationText] = useState('');

  const handleAnnotationTextChange = (event) => {
    setAnnotationText(event.target.value);
  };

  const handleAnnotationSubmit = () => {
    const ctx = canvas.getContext('2d');
    ctx.font = '15px Arial';
    ctx.fillStyle = 'red';
    ctx.textAlign = 'left';
    ctx.textBaseAlign = 'top';
    ctx.fillText(annotationText, 10, 10);
    pdf.getPages().forEach((page) => {
      page.scaleCanvas({
        width: page.getWidth() * 100,
        height: page.getHeight(),
      });
    });
  };

  return (
    <div>
      <input
        type="text"
        value={annotationText}
        onChange={handleAnnotationTextChange}
      />
      <button onClick={handleAnnotationSubmit}>Add Annotation</button>
    </div>
  );
};

export default AddAnnotationButton;

This code adds a text input field and a button to add a text annotation to the PDF page. When the button is clicked, the annotation text is drawn on the canvas element using the fillText method.

Conclusion

In this article, we covered the steps to edit a PDF file in ReactJS using pdf-lib. We created a new ReactJS project, installed pdf-lib, loaded the PDF file, created a PDF viewer component, and added editing capabilities to the PDF pages. With these steps, you can now create a PDF editor in ReactJS.