Getting Started

Getting Started (2)

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. The downloaded product package integrates Spire.Doc for JavaScript, Spire.XLS for JavaScript, Spire.PDF for JavaScript, and Spire.Presentation for JavaScript. To use the features of Spire.Doc for JavaScript, you need to copy the corresponding files (spire.doc.js, Spire.Doc.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and the _framework folder) to the public folder of your project.

Download Spire.Doc for JavaScript library

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

npm i spire.office

Once the installation is complete, the product package files will be saved in the node_modules/spire.office path of your project. Copy the 5 files mentioned above into the "public" folder in your React project.

To ensure proper text rendering, you can add relevant font files with a custom path. In the following example, the font is added to the path: public\.

The library files installed via npm

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() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.Doc
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.doc.js`);
        const rawModule = spireModule.default || spireModule;
        window.wasmModule = typeof rawModule === 'function'
          ? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
          : rawModule;
        setWasmModule(window.wasmModule);
      } catch (error) {
        console.error('Failed to load spire.doc.js WASM module:', error);
      }
    })();
  }, []);

  // Function to generate word file
  const createWord = async () => {
    const wasmModule = window.wasmModule.spiredoc;
    if (wasmModule) {

      // Load the arial.ttf font file into the virtual file system (VFS)
      await window.spire.FetchFileToVFS('arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Specify output file name
      const outputFileName = 'HelloWorld.docx';

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

      // 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 = window.dotnetRuntime.Module.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;

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

npm start

Once the React app is successfully compiled, it will open in your default web browser, typically at http://localhost:3000.Click "Generate" to create the 'HelloWorld.docx'.

 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.

Document processing is an essential feature in many modern web applications, enabling tasks such as report generation and data management. Node.js, known for its non-blocking I/O model and extensive ecosystem, provides a powerful platform for backend development. By integrating Spire.Doc for JavaScript, you can streamline the creation and manipulation of Word documents effortlessly.

This guide will take you through the steps to integrate Spire.Doc for JavaScript into your Node.js projects, from initial setup to a basic usage example.

Benefits of Using Spire.Doc for JavaScript in Node.js Projects

Node.js is a powerful runtime environment that allows developers to build scalable network applications using JavaScript. Spire.Doc for JavaScript, on the other hand, is a versatile library designed to manipulate Word documents within JavaScript environments. It provides a wide range of features, including document creation, editing, conversion, and more, making it a valuable tool for developers working with document-based applications.

Integrating Spire.Doc for JavaScript into your Node.js project offers numerous benefits, including:

  • Efficient Document Management: Easily create, edit, and manage Word documents without the need for Microsoft Word.
  • Scalability: Leverage Node.js's non-blocking I/O model to handle large volumes of document processing tasks efficiently.
  • Cross-Platform Compatibility: Use Spire.Doc for JavaScript across various platforms, including Windows, macOS, and Linux.
  • Ease of Integration: Seamlessly integrate Spire.Doc for JavaScript with other Node.js libraries and tools.

These benefits make Spire.Doc for JavaScript an ideal choice for developers looking to enhance their Node.js projects with robust document processing capabilities.

Set Up Your Environment

Step 1

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 installed correctly, along with the version numbers, by entering the following commands in CMD:

node -v 
npm -v

Install Node.js

Step 2

Initialize a Node.js project:

npm init -y

Installation dependencies:

npm install adm-zip@^0.5.16

Configure packaging.json:

{
	"name": "nodejstest",
    "version": "1.0.0",
    "description": "Simple test project to generate HelloWorld.docx using spire.doc.js",
    "main": "index.js",
    "type": "module",
    "scripts": {
      "start": "node --experimental-modules --experimental-wasm-modules --experimental-vm-modules index.js"
    },
    "dependencies": {
      "adm-zip": "^0.5.16"
    }
  }

Customize folder in the root directory to put some font files, you can customize and add fonts based on the font used in your documents.

Add folders in Node.js project

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. The downloaded product package integrates Spire.Doc for JavaScript, Spire.XLS for JavaScript, Spire.PDF for JavaScript, and Spire.Presentation for JavaScript. To use the features of Spire.Doc for JavaScript, customize the folder in the root directory, this tutorial defined the 'wasm' folder, and copy the corresponding files (spire.doc.js, Spire.Doc.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and the _framework folder) to the “wasm” folder.

Download Spire.Doc for JavaScript library

Add the 'index.js' file to the root directory of the project and set the following content to create a simple Word file

Here is the entire JavaScript code:

  • JavaScript
//NodeJSTest----create "HelloWorld.docx"
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
import AdmZip from 'adm-zip';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

async function extractWasmFiles() {
    const wasmDir = path.join(__dirname, 'wasm');
    const frameworkDir = path.join(wasmDir, '_framework');
    await fs.mkdir(frameworkDir, { recursive: true });

    for (const zipName of ['Spire.Common.Wasm.zip', 'Spire.Doc.Wasm.zip']) {
        const zipPath = path.join(wasmDir, zipName);
        try {
            await fs.access(zipPath);
            new AdmZip(zipPath).extractAllTo(wasmDir, true);
        } catch {}
    }
}

async function main() {
    try {
        await extractWasmFiles();
        const { spiredoc } = await import('./wasm/spire.doc.js');
        const spire = globalThis.spire;
        if (!spire) throw new Error('WASM module not loaded correctly');

        const outputDir = path.join(__dirname, 'output');
        await fs.mkdir(outputDir, { recursive: true });

        const fontsPath = path.join(__dirname, 'fonts');
        try {
            await fs.access(fontsPath);
            spire.copyLocalPathToVFS(fontsPath, '/Library/Fonts/');
        } catch {}

        const document = new spiredoc.Document();
        document.AddSection().AddParagraph().AppendText('Hello World');

        const outputFileName = 'HelloWorld2.docx';
        document.SaveToFile({ fileName: outputFileName, fileFormat: spiredoc.FileFormat.Docx2013 });

        const outputFile = path.join(outputDir, outputFileName);
        spire.copyFileFromFSToLocalStorage(outputFileName, outputFile);
        document.Dispose();

        console.log(`Document saved to ${outputFile}`);
    } catch (error) {
        console.error(error);
        process.exit(1);
    }
}

main();

Using “npm start” run the program, you will find the generated Word file in the designated file path.

A Word file generated by JavaScript code

A Word file generated by JavaScript code

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.

page