How to Integrate Spire.Doc for JavaScript in a React Project

Integrating document processing capabilities is crucial for enhancing user experience in many web applications, allowing for efficient report generation and data handling. React, with its component-based architecture, is an excellent choice for frontend development. By integrating Spire.Doc for JavaScript, you can effortlessly create and manage Word documents within your React application.

This guide will walk you through the steps to integrate Spire.Doc for JavaScript into your React projects, covering both setup and a usage example.

Benefits of Using Spire.Doc for JavaScript in React

React, a popular JavaScript library for building user interfaces, has become a cornerstone in modern web development. On the other hand, Spire.Doc for JavaScript is a powerful library designed to simplify document processing in web applications.

By integrating Spire.Doc for JavaScript into your React project, you can add advanced Word document processing capabilities to your application. Here are some of the key advantages:

  • Seamless Document Creation: Spire.Doc for JavaScript enables document creation and editing directly in React, streamlining management without external tools.
  • Cross-Platform Compatibility: Spire.Doc for JavaScript allows document creation compatible with multiple platforms, enabling users to access and edit documents from anywhere.
  • Rich Features: Spire.Doc for JavaScript offers extensive capabilities like text formatting, table creation, and image insertion, ideal for applications needing document manipulation.
  • Seamless Integration: Compatible with various JavaScript frameworks, including React, Spire.Doc for JavaScript integrates easily into existing projects without disrupting your workflow.

Set Up Your Environment

Step 1. Install React and npm

Download and install Node.js from the official website. Make sure to choose the version that matches your operating system.

After the installation is complete, you can verify that Node.js and npm are working correctly by running the following commands in your terminal:

Check the versions of node.js and npm

Step 2. Create a New React Project

Create a new React project named my-app using Create React App from terminal:

npx create-react-app my-app

Create a react project

If your React project is compiled successfully, the app will be served at http://localhost:3000, allowing you to view and test your application in a browser.

React app opens at localhost 3000

To visually browse and manage the files in your project, you can open the project using VS Code.

Open React project in VS Code

Integrate Spire.Doc for JavaScript in Your Project

Download Spire.Doc for JavaScript from our website and unzip it to a location on your disk. Inside the lib folder, you will find the Spire.Doc.Base.js and Spire.Doc.Base.wasm files.

Download Spire.Doc for JavaScript library

You can also install Spire.Doc for JavaScript using npm. In the terminal within VS Code, run the following command:

npm i spire.doc

Install Spire.Doc for JavaScript from npm

This command will download and install the Spire.Doc package, including all its dependencies. Once the installation is complete, the Spire.Doc.Base.js and Spire.Doc.Base.wasm files will be saved in the node_modules/spire.doc path of your project.

The library files installed via npm

Copy these two files into the "public" folder in your React project.

Copy library to React project

Add font files you plan to use to the "public" folder in your project.

Add font files to React project

Create and Save Word Files Using JavaScript

Modify the code in the "App.js" file to generate a Word file using the WebAssembly (WASM) module. Specifically, utilize the Spire.Doc for JavaScript library for Word file manipulation.

Modify app.js file

Here is the entire code:

  • 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 spiredoc from the global window object
        const { Module, spiredoc } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spiredoc);
        };
      } 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.Doc.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 generate word file
  const createWord = async () => {
    if (wasmModule) {

      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      
      // Specify output file name
      const outputFileName = 'HelloWorld.docx';

      // Create a new document
      const doc = wasmModule.Document.Create();

      // Add a section
      let section = doc.AddSection();

      // Add a paragraph
      let paragraph = section.AddParagraph();

      // Append text to the paragraph
      paragraph.AppendText('Hello, World!');

      // Save the document to a Word file
      doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013});
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

      // Clean up resources
      doc.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Create a Word File Using JavaScript in React</h1>
      <button onClick={createWord} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

Save the changes by clicking "File" - "Save".

Save changes

Start the development server by entering the following command in the terminal within VS Code:

npm start

Start your react project by running npm start

Once the React app is successfully compiled, it will open in your default web browser, typically at http://localhost:3000.

 React app opens at local host 3000

Click "Generate" and a "Save As" window will prompt you to save the output file in the designated folder.

Save the generated Word at the specified folder

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.