Extract Text from PDF Documents with JavaScript in React

Extracting text from PDF documents directly within a React application using JavaScript provides a streamlined, self-contained solution for handling dynamic content. Given that PDFs remain a ubiquitous format for reports, forms, and data sharing, parsing their contents on the client side enables developers to build efficient applications without relying on external services. By integrating Spire.PDF for JavaScript into React, development teams gain full control over data processing, reduce latency by eliminating server-side dependencies, and deliver real-time user experiences—all while ensuring that sensitive information remains secure within the browser.

In this article, we explore how to use Spire.PDF for JavaScript to extract text from PDF documents in React applications, simplifying the integration of robust PDF content extraction features.

Install Spire.PDF for JavaScript

To get started with extracting text from PDF documents with JavaScript 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

General Steps for Extracting PDF Text Using JavaScript

Spire.PDF for JavaScript provides a WebAssembly module that enables PDF document processing using simple JavaScript code in React applications. Developers can utilize the PdfTextExtractor class to handle text extraction tasks efficiently. The general steps for extracting text from PDF documents using Spire.PDF for JavaScript in React are as follows:

  • Load the Spire.Pdf.Base.js file to initialize the WebAssembly module.
  • Fetch the PDF files into the Virtual File System (VFS) using the wasmModule.FetchFileToVFS() method.
  • Create an instance of the PdfDocument class using the wasmModule.PdfDocument.Create() method.
  • Load the PDF document from the VFS into the PdfDocument instance using the PdfDocument.LoadFromFile() method.
  • Create an instance of the PdfTextExtractOptions class using the wasmModule.PdfTextExtractOptions.Create() method and configure the text extraction options.
  • Retrieve a PDF page using the PdfDocument.Pages.get_Item() method or iterate through the document's pages.
  • Create an instance of the PdfTextExtractor class with the page object using the wasmModule.PdfTextExtractor.Create() method.
  • Extract text from the page using the PdfTextExtractor.ExtractText() method.
  • Download the extracted text or process it as needed.

The PdfTextExtractOptions class allows customization of extraction settings, supporting features such as simple extraction, extracting specific page areas, and retrieving hidden text. The following table outlines the properties of the PdfTextExtractOptions class and their functions:

Property Description
IsSimpleExtraction Specifies whether to perform simple text extraction.
IsExtractAllText Specifies whether to extract all text.
ExtractArea Defines the extraction area.
IsShowHiddenText Specifies whether to extract hidden text.

Extract PDF Text with Layout Preservation

Using the PdfTextExtractor.ExtractText() method with default options enables text extraction while preserving the original text layout of the PDF pages. Below is a code example and the corresponding extraction result:

  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to store 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 module loading
        console.error('Failed to load the 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 extract all text from a PDF document
  const ExtractPDFText = async () => {
    if (wasmModule) {
      // Specify the input and output file names
      const inputFileName = 'Sample.pdf';
      const outputFileName = 'PDFTextWithLayout.txt';

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

      // Create an instance of the PdfDocument class
      const pdf = wasmModule.PdfDocument.Create();

      // Load the PDF document from the VFS
      pdf.LoadFromFile(inputFileName);

      // Create a string object to store the extracted text
      let text = '';

      // Create an instance of the PdfTextExtractOptions class
      const extractOptions = wasmModule.PdfTextExtractOptions.Create();

      // Iterate through each page of the PDF document
      for (let i = 0; i < pdf.Pages.Count; i++) {
        // Get the current page
        const page = pdf.Pages.get_Item(i);
        // Create an instance of the PdfTextExtractor class
        const textExtractor = wasmModule.PdfTextExtractor.Create(page);
        // Extract the text from the current page and add it to the text string
        text += textExtractor.ExtractText(extractOptions);
      }

      // Create a Blob object from the text string and download it
      const blob = new Blob([text], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      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>Extract Text from PDF Using JavaScript in React</h1>
        <button onClick={ExtractPDFText} disabled={!wasmModule}>
          Extract and Download
        </button>
      </div>
  );
}

export default App;

 Text Extracted from PDF with Layout Using Spire.PDF for JavaScript

Extract PDF Text without Layout Preservation

Setting the PdfTextExtractOptions.IsSimpleExtraction property to true enables a simple text extraction strategy, allowing text extraction from PDF pages without preserving the layout. In this approach, blank spaces are not retained. Instead, the program tracks the Y position of each text string and inserts line breaks whenever the Y position changes.

Below is a code example demonstrating text extraction without layout preservation using Spire.PDF for JavaScript, along with the extraction result:

  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to store 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 module loading
        console.error('Failed to load the 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 extract all text from a PDF document without layout preservation
  const ExtractPDFText = async () => {
    if (wasmModule) {
      // Specify the input and output file names
      const inputFileName = 'Sample.pdf';
      const outputFileName = 'PDFTextWithoutLayout.txt';

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

      // Create an instance of the PdfDocument class
      const pdf = wasmModule.PdfDocument.Create();

      // Load the PDF document from the VFS
      pdf.LoadFromFile(inputFileName);

      // Create a string object to store the extracted text
      let text = '';

      // Create an instance of the PdfTextExtractOptions class
      const extractOptions = wasmModule.PdfTextExtractOptions.Create();

      // Enable simple text extraction to extract text without preserving layout
      extractOptions.IsSimpleExtraction = true;

      // Iterate through each page of the PDF document
      for (let i = 0; i < pdf.Pages.Count; i++) {
        // Get the current page
        const page = pdf.Pages.get_Item(i);
        // Create an instance of the PdfTextExtractor class
        const textExtractor = wasmModule.PdfTextExtractor.Create(page);
        // Extract the text from the current page and add it to the text string
        text += textExtractor.ExtractText(extractOptions);
      }

      // Create a Blob object from the text string and download it
      const blob = new Blob([text], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      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>Extract Text from PDF Without Layout Preservation Using JavaScript in React</h1>
        <button onClick={ExtractPDFText} disabled={!wasmModule}>
          Extract and Download
        </button>
      </div>
  );
}

export default App;

Text Extracted from PDF Without Layout Using JavaScript in React

Extract PDF Text from Specific Page Areas

The PdfTextExtractOptions.ExtractArea property allows users to define a specific area using a RectangleF object to extract only the text within that area from a PDF page. This method helps exclude unwanted fixed content from the extraction process. The following code example and extraction result illustrate this functionality:

  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to store 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 module loading
        console.error('Failed to load the 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 extract text from a specific area of a PDF page
  const ExtractPDFText = async () => {
    if (wasmModule) {
      // Specify the input and output file names
      const inputFileName = 'Sample.pdf';
      const outputFileName = 'PDFTextPageArea.txt';

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

      // Create an instance of the PdfDocument class
      const pdf = wasmModule.PdfDocument.Create();

      // Load the PDF document from the VFS
      pdf.LoadFromFile(inputFileName);

      // Create a string object to store the extracted text
      let text = '';

      // Get a page from the PDF document
      const page = pdf.Pages.get_Item(0);

      // Create an instance of the PdfTextExtractOptions class
      const extractOptions = wasmModule.PdfTextExtractOptions.Create();

      // Set the page area to extract text from using a RectangleF object
      extractOptions.ExtractArea = wasmModule.RectangleF.Create({ x: 0, y: 500, width: page.Size.Width, height: 200});

      // Create an instance of the PdfTextExtractor class
      const textExtractor = wasmModule.PdfTextExtractor.Create(page);

      // Extract the text from specified area of the page
      text = textExtractor.ExtractText(extractOptions);

      // Create a Blob object from the text string and download it
      const blob = new Blob([text], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      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>Extract Text from a PDF Page Area Using JavaScript in React</h1>
        <button onClick={ExtractPDFText} disabled={!wasmModule}>
          Extract and Download
        </button>
      </div>
  );
}

export default App;

PDF Text Extracted from Page Areas Using JavaScript

Extract Highlighted Text from PDF

Text highlighting in PDF documents is achieved using annotation features. With Spire.PDF for JavaScript, we can retrieve all annotations on a PDF page via the PdfPageBase.Annotations property. By checking whether each annotation is an instance of the PdfTextMarkupAnnotationWidget class, we can identify highlight annotations. Once identified, we can use the PdfTextExtractOptions.Bounds property to obtain the bounding rectangles of these annotations and set them as extraction areas, thereby extracting only the highlighted text.

The following code example demonstrates this process along with the extracted result:

  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to store 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 module loading
        console.error('Failed to load the 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 extract highlighted text from PDF
  const ExtractPDFText = async () => {
    if (wasmModule) {
      // Specify the input and output file names
      const inputFileName = 'Sample.pdf';
      const outputFileName = 'PDFTextHighlighted.txt';

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

      // Create an instance of the PdfDocument class
      const pdf = wasmModule.PdfDocument.Create();

      // Load the PDF document from the VFS
      pdf.LoadFromFile(inputFileName);

      // Create a string object to store the extracted text
      let text = '';

      // Iterate through each page of the PDF document
      for (const page of pdf.Pages) {
        // Iterate through each annotation on the page
        for (let i = 0; i < page.Annotations.Count; i++) {
          // Get the current annotation
          const annotation = page.Annotations.get_Item(i)
          // Check if the annotation is an instance of PdfTextMarkupAnnotation
          if (annotation instanceof wasmModule.PdfTextMarkupAnnotationWidget) {
            // Get the bounds of the annotation
            const bounds = annotation.Bounds;
            // Create an instance of PdfTextExtractOptions
            const extractOptions = wasmModule.PdfTextExtractOptions.Create();
            // Set the bounds of the highlight annotation as the extraction area
            extractOptions.ExtractArea = bounds;
            //
            const textExtractor = wasmModule.PdfTextExtractor.Create(page)
            // Extract the highlighted text and append it to the text string
            text += textExtractor.ExtractText(extractOptions);
          }
        }
      }

      // Create a Blob object from the text string and download it
      const blob = new Blob([text], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      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>Extract Highlighted Text from PDF Using JavaScript in React</h1>
        <button onClick={ExtractPDFText} disabled={!wasmModule}>
          Extract and Download
        </button>
      </div>
  );
}

export default App;

Highlighted Text Extracted from PDF in React

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.