Add, Replace or Remove Images in PDF with JavaScript in React

PDFs are versatile documents that often contain images to enhance their visual appeal and convey information. The ability to manipulate these images - adding new ones, replacing existing ones, or removing unwanted ones - is a valuable skill. In this article, you will learn how to add, replace, or delete images in a PDF document in React using Spire.PDF for JavaScript .

Install Spire.PDF for JavaScript

To get started with manipulating images in PDF in a React application, you can either download Spire.PDF for JavaScript from our website or install it via npm with the following command:

npm i spire.pdf

After that, copy the "Spire.Pdf.Base.js" and "Spire.Pdf.Base.wasm" files to the public folder of your project.

For more details, refer to the documentation: How to Integrate Spire.PDF for JavaScript in a React Project

Add an Image to a PDF Document in JavaScript

Spire.PDF for JavaScript provides the PdfPage.Canvas.DrawImage() method to add an image at a specified location on a PDF page. The main steps are as follows.

  • Load the input image into the Virtual File System (VFS).
  • Create a PdfDocument object with the wasmModule.PdfDocument.Create() method.
  • Add a page to the PDF document using the PdfDocument.Pages.Add() method.
  • Load the image using the wasmModule.PdfImage.FromFile() method.
  • Specify the size of the image.
  • Draw the image at a specified location on the page using the PdfPageBase.Canvas.DrawImage() method.
  • Save the PDF document using PdfDocument.SaveToFile() method.
  • Trigger the download of the resulting document.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirepdf from the global window object
        const { Module, spirepdf } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirepdf);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Pdf.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to add images in PDF
  const AddPdfImage = async () => {
    if (wasmModule) {
      // Specify the input and output file paths
      const inputFileName = "JS.png";
      const outputFileName = "DrawImage.pdf";

      // Fetch the input file and add it to the VFS
      await wasmModule.FetchFileToVFS(inputFileName , '', `${process.env.PUBLIC_URL}/`);

      // Create a pdf instance
      let pdf = wasmModule.PdfDocument.Create();

      // Add a page
      let page = pdf.Pages.Add();

      // Load the image 
      let image = wasmModule.PdfImage.FromFile(inputFileName);
    
      // Calculate the scaled width and height of the image
      let width = image.Width * 0.6;
      let height = image.Height * 0.6;
    
      // Calculate the x-coordinate to center the image horizontally on the page
      let x = (page.Canvas.ClientSize.Width - width) / 2;
    
      // Draw the image at a specified location on the page
      page.Canvas.DrawImage({image:image, x:x, y: 60, width: width, height: height});

      // Save the result file
      pdf.SaveToFile({fileName: outputFileName});

      // Clean up resources
      pdf.Close();

      // Read the generated PDF file
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

      // Create a Blob object from the PDF file
      const modifiedFile = new Blob([modifiedFileArray], { type: "application/pdf" });

      // Create a URL for the Blob
      const url = URL.createObjectURL(modifiedFile);

      // Create an anchor element to trigger the download
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);  
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Add Images in PDF with JavaScript in React</h1>
      <button onClick={AddPdfImage} disabled={!wasmModule}>
        Process
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click the "Process" button to insert image in PDF:

Run the code to launch the React app at localhost:3000

Below is the result file:

Insert a picture to a specified location on a PDF page

Replace an Image in a PDF Document in JavaScript

To replace an image in PDF, you can load a new image and then replace the existing image with the new one through the PdfImageHelper.ReplaceImage() method. The main steps are as follows.

  • Load the input file and image into the Virtual File System (VFS).
  • Create a PdfDocument object with the wasmModule.PdfDocument.Create() method.
  • Load a PDF document using the PdfDocument.LoadFromFile() method.
  • Get a specific page through the PdfDocument.Pages.get_Item() method.
  • Load an image using PdfImage.FromFile() method.
  • Create a PdfImageHelper object with the wasmModule.PdfImageHelper.Create() method.
  • Get the image information on the page using the PdfImageHelper.GetImagesInfo() method.
  • Load the input image using the wasmModule.PdfImage.FromFile() method.
  • Replace an existing image in the page with the new image using the PdfImageHelper.ReplaceImage() method.
  • Save the PDF document using PdfDocument.SaveToFile() method.
  • Trigger the download of the resulting document.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirepdf from the global window object
        const { Module, spirepdf } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirepdf);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Pdf.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to replace an image in PDF
  const ReplacePdfImage = async () => {
    if (wasmModule) {
      // Specify the input and output file paths
      const inputFileName = "DrawImage.pdf";
      const inputImageName = "coding1.jpg";
      const outputFileName = "ReplaceImage.pdf";

      // Fetch the input file and image and add them to the VFS
      await wasmModule.FetchFileToVFS(inputFileName , '', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS(inputImageName , '', `${process.env.PUBLIC_URL}/`);

      // Create a pdf instance
      let pdf = wasmModule.PdfDocument.Create();
      
      // Load the PDF file
      pdf.LoadFromFile({fileName: inputFileName});

      // Get the first page
      let page = pdf.Pages.get_Item(0);

      // Create a PdfImageHelper instance 
      let helper = wasmModule.PdfImageHelper.Create();

      // Get the image information from the page
      let images = helper.GetImagesInfo(page);

      // Load a new image
      let newImage = wasmModule.PdfImage.FromFile(inputImageName);

      // Replace the first image on the page with the loaded image
      helper.ReplaceImage(images[0], newImage);

      // Save the result file
      pdf.SaveToFile({fileName: outputFileName});

      // Clean up resources
      pdf.Close();

      // Read the generated PDF file
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

      // Create a Blob object from the PDF file
      const modifiedFile = new Blob([modifiedFileArray], { type: "application/pdf" });

      // Create a URL for the Blob
      const url = URL.createObjectURL(modifiedFile);

      // Create an anchor element to trigger the download
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);  
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Replace an Image in PDF with JavaScript in React</h1>
      <button onClick={ReplacePdfImage} disabled={!wasmModule}>
        Process
      </button>
    </div>
  );
}

export default App;

Replace a specified existing image with a new image in PDF

Remove an Image from a PDF Document in JavaScript

The PdfImageHelper class also provides the DeleteImage() method to remove a specific image from a PDF page. The main steps are as follows.

  • Load the input file into the Virtual File System (VFS).
  • Create a PdfDocument object with the wasmModule.PdfDocument.Create() method.
  • Load a PDF document using the PdfDocument.LoadFromFile() method.
  • Get a specific page using the PdfDocument.Pages.get_Item() method.
  • Create a PdfImageHelper object with the wasmModule.PdfImageHelper.Create() method.
  • Get the image information on the page using the PdfImageHelper.GetImagesInfo() method.
  • Delete a specified image on the page using the PdfImageHelper.DeleteImage() method.
  • Save the PDF document using PdfDocument.SaveToFile() method.
  • Trigger the download of the resulting document.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirepdf from the global window object
        const { Module, spirepdf } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirepdf);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Pdf.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to remove images in PDF
  const DeletePdfImage = async () => {
    if (wasmModule) {
      // Specify the input and output file paths
      const inputFileName  = "DrawImage.pdf";
      const outputFileName = "DeleteImage.pdf";

      // Fetch the input file and add it to the VFS
      await wasmModule.FetchFileToVFS(inputFileName , '', `${process.env.PUBLIC_URL}/`);

      // Create a pdf instance
      let pdf = wasmModule.PdfDocument.Create();
      
      // Load the PDF file
      pdf.LoadFromFile({fileName: inputFileName});

      // Get the first page
      let page = pdf.Pages.get_Item(0);

      // Create a PdfImageHelper instance 
      let helper = wasmModule.PdfImageHelper.Create();

      // Get the image information from the page
      let images = helper.GetImagesInfo(page);

      // Delete the first image on the page
      helper.DeleteImage({imageInfo: images[0]});

      // Save the result file
      pdf.SaveToFile({fileName: outputFileName});

      // Clean up resources
      pdf.Close();

      // Read the generated PDF file
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

      // Create a Blob object from the PDF file
      const modifiedFile = new Blob([modifiedFileArray], { type: "application/pdf" });

      // Create a URL for the Blob
      const url = URL.createObjectURL(modifiedFile);

      // Create an anchor element to trigger the download
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);  
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Remove an Image from PDF with JavaScript in React</h1>
      <button onClick={DeletePdfImage} disabled={!wasmModule}>
        Process
      </button>
    </div>
  );
}

export default App;

Get a Free License

To fully experience the capabilities of Spire.PDF for JavaScript without any evaluation limitations, you can request a free 30-day trial license.