Document Operation
Document Operation

Document Operation (2)

Creating dynamic documents is essential for many applications. This guide will explore how to generate a Word document using Spire.Doc for JavaScript within a React environment. We will cover the essential features needed for effective document creation, including adding titles, headings, and paragraphs to structure your content effectively.

You'll also learn how to enhance your documents by incorporating images, creating lists for organized information, and adding tables to present data clearly. By the end of this tutorial, you'll be equipped with the skills to produce professional documents directly from your React applications.

Install Spire.Doc for JavaScript

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

npm i spire.doc

After that, copy the "Spire.Doc.Base.js" and "Spire.Doc.Base.wasm" files to the public folder of your project. Additionally, include the required font files to ensure accurate text rendering.

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

Add Titles, Headings, and Paragraphs to Word in React

To add a title, headings, and paragraphs to a Word document, you primarily utilize the Document and Section classes provided by Spire.Doc for JavaScript. The AddParagraph() method creates new paragraphs, while AppendText() allows you to insert text into those paragraphs.

Paragraphs can be formatted using built-in styles (e.g., Title, Heading 1-4) for consistent structure, or customized with specific fonts, sizes, and colors through user-defined styles for tailored document design.

Steps for adding titles, headings, and parargraphs to a Word documents in React:

  • Import the necessary font files into the virtual file system (VFS).
  • Create a Document object using wasmModule.Document.Create().
  • Include a new section in the document with Document.AddSection().
  • Add paragraphs to the document using Section.AddParagraph().
  • Use Paragraph.ApplyStyle() to apply built-in styles (Title, Heading1, Heading2, Heading3) to specific paragraphs.
  • Define a custom paragraph style with wasmModule.ParagraphStyle.Create() and apply it to a designated paragraph.
  • Save the document as a DOCX file and initiate the download.
  • 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 add text to word
  const AddText = async () => {
    if (wasmModule) {

      // Load the font files into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('times.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbd.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      
      // Create a new document
      const doc= wasmModule.Document.Create();

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

      // Set page margins
      section.PageSetup.Margins.All = 60;

      // Add a title paragraph
      let title_para = section.AddParagraph();
      title_para.AppendText('This is title');
      title_para.ApplyStyle({builtinStyle: wasmModule.BuiltinStyle.Title});

      // Add heading paragraphs
      let heading_one = section.AddParagraph();
      heading_one.AppendText('This is heading 1');
      heading_one.ApplyStyle({builtinStyle: wasmModule.BuiltinStyle.Heading1});

      let heading_two = section.AddParagraph();
      heading_two.AppendText('This is heading 2');
      heading_two.ApplyStyle({builtinStyle: wasmModule.BuiltinStyle.Heading2});

      let heading_three = section.AddParagraph();
      heading_three.AppendText('This is heading 3');
      heading_three.ApplyStyle({builtinStyle: wasmModule.BuiltinStyle.Heading3});

      let heading_four = section.AddParagraph();
      heading_four.AppendText('This is heading 4');
      heading_four.ApplyStyle({builtinStyle: wasmModule.BuiltinStyle.Heading4});

      // Add a normal paragraph
      let normal_para = section.AddParagraph();
      normal_para.AppendText('This is a paragraph.');

      // Create a paragraph style,specifying font name, font size, and text color
      let paragraph_style = wasmModule.ParagraphStyle.Create(doc);
      paragraph_style.Name = 'newStyle';
      paragraph_style.CharacterFormat.FontName = 'Times New Roman'
      paragraph_style.CharacterFormat.FontSize = 13;
      paragraph_style.CharacterFormat.TextColor = wasmModule.Color.get_Blue();

      // Add the style to the document
      doc.Styles.Add(paragraph_style);

      // Apply the style to the paragraph
      normal_para.ApplyStyle(paragraph_style.Name);

      // Save the document
      const outputFileName = 'output.docx';
      doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013});
 
      // Create a Blob for the downloaded file
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
      const url = URL.createObjectURL(modifiedFile);

      // Trigger file 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); 

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Add Text to a Word Document in React</h1>
      <button onClick={AddText} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Click "Generate", and a "Save As" window will appear, prompting you to save the output file in your chosen folder.

React app to create a Word document

Below is a screenshot of the generated Word file that includes a title, several headings, and a normal paragraph:

Add text to a Word document in React

Add an Image to Word in React

Inserting images into a Word document involves using the AppendPicture() method, which allows you to add a picture to a specific paragraph. The process begins by loading the image file into the virtual file system (VFS), ensuring that the image is accessible for insertion.

Steps for adding an image to a Word doucment in React:

  • Load an image file into the virtual file system (VFS).
  • Create a Document object using wasmModule.Document.Create().
  • Add a new section to the document with Document.AddSection().
  • Insert a new paragraph in the section using Section.AddParagraph().
  • Use the Paragraph.AppendPicture() method to add the loaded image to the paragraph.
  • Save the document as a DOCX file and trigger the download.
  • 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 add image to word
  const AddImage = async () => {
    if (wasmModule) {

      // Load an image file into the virtual file system (VFS)
      const inputImageFile = 'logo.png';
      await wasmModule.FetchFileToVFS(inputImageFile, '', `${process.env.PUBLIC_URL}/`);

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

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

      // Set page margins
      section.PageSetup.Margins.All = 60;

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

      // Add an image to the paragraph
      image_para.AppendPicture({imgFile: inputImageFile});

      // Save the document
      const outputFileName = 'output.docx';
      doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013});
 
      // Create a Blob for the downloaded file
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
      const url = URL.createObjectURL(modifiedFile);

      // 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); 

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

  return (
    

Add an Image to a Word Document in React

); } export default App;

Add an image to a Word document in React

Add a List to Word in React

To create lists in your Word document, utilize the ListStyle class to define the appearance of your lists, such as bulleted or numbered formats. The ApplyStyle() method associates paragraphs with the defined list style, enabling consistent formatting across multiple items.

Steps for adding a list to a Word document in React:

  • Load the required font files into the virtual file system (VFS).
  • Create a Document object using wasmModule.Document.Create().
  • Add a section to the document with Document.AddSection().
  • Define a list style using wasmModule.ListStyle.Create().
  • Insert several paragraphs in the section using Section.AddParagraph().
  • Apply the defined list style to the paragraphs using Paragraph.ListFormat.ApplyStyle().
  • Save the document as a DOCX file and trigger the download.
  • 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 add list to word
  const AddList = async () => {
    if (wasmModule) {

      // Load the font files into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('times.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbd.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      
      // Create a new document
      const doc= wasmModule.Document.Create();

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

      // Set page margins
      section.PageSetup.Margins.All = 60;

      // Define a bullet list style
      let list_style = wasmModule.ListStyle.Create(doc, wasmModule.ListType.Bulleted);
      list_style.Name = 'bulletedList';
      list_style.Levels.get_Item(0).BulletCharacter = '\u00B7';
      list_style.Levels.get_Item(0).CharacterFormat.FontName = 'Symbol';
      list_style.Levels.get_Item(0).CharacterFormat.FontSize = 14;
      list_style.Levels.get_Item(0).TextPosition = 20;

      // Add the list style to the document
      doc.ListStyles.Add(list_style);

      // Add title paragraph
      let paragraph = section.AddParagraph();
      let text_range = paragraph.AppendText('Fruits:');
      paragraph.Format.AfterSpacing = 5;
      text_range.CharacterFormat.FontName = 'Times New Roman'
      text_range.CharacterFormat.FontSize = 14;

      // Add items to the bullet list
      const fruits = ['Apple', 'Banana', 'Watermelon', 'Mango'];
      fruits.forEach(fruit => {
        paragraph = section.AddParagraph();
        let text_range = paragraph.AppendText(fruit);
        paragraph.ListFormat.ApplyStyle(list_style.Name);
        paragraph.ListFormat.ListLevelNumber = 0;
        text_range.CharacterFormat.FontName = 'Times New Roman'
        text_range.CharacterFormat.FontSize = 14;
      });

      // Save the document
      const outputFileName = 'output.docx';
      doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013});
 
      // Create a Blob for the downloaded file
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
      const url = URL.createObjectURL(modifiedFile);

      // Trigger file 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); 

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Add Lists to a Word Document in React</h1>
      <button onClick={AddList} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

Add a list to a Word document in React

Add a Table to Word in React

To create tables, use the AddTable() method where you can specify the number of rows and columns with ResetCells(). Once the table is created, you can populate individual cells by using the AddParagraph() and AppendText() methods to insert text content. Additionally, the AutoFit() method can be employed to automatically adjust the table layout based on its contents, ensuring a clean and organized presentation of your data.

Steps for adding a table to a Word document in React:

  • Load the required font files into the virtual file system (VFS).
  • Create a Document object using wasmModule.Document.Create().
  • Add a section to the document with Document.AddSection().
  • Create a two-dimensional array to hold the table data, including headers and values.
  • Use Section.AddTable() to create a table, specifying visibility options like borders.
  • Call Table.ResetCells() to define the number of rows and columns in the table based on your data.
  • Iterate through the data array, adding text to each cell using the TableCell.AddParagraph() and Paragraph.AppendText() methods.
  • Use the Table.AutoFit() method to adjust the table size according to the content.
  • Save the document as a DOCX file and trigger the download.
  • 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 add table to word
  const AddTable = async () => {
    if (wasmModule) {

      // Load the font files into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('times.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbd.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      
      // Create a new document
      const doc= wasmModule.Document.Create();

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

      // Set page margins
      section.PageSetup.Margins.All = 60;

      // Define table data
      let data =
        [
            ['Product', 'Unit Price', 'Quantity', 'Sub Total'],
            ['A', '$29', '120', '$3,480'],
            ['B', '$35', '110', '$3,850'],
            ['C', '$68', '140', '$9,520'],
        ];

      // Add a table
      let table = section.AddTable({showBorder: true});

      // Set row number and column number
      table.ResetCells(data.length , data[0].length);

      // Write data to cells
      for (let r = 0; r < data.length; r++) {
        let data_row = table.Rows.get(r);
        data_row.Height = 20;
        data_row.HeightType = wasmModule.TableRowHeightType.Exactly;
        data_row.RowFormat.BackColor = wasmModule.Color.Empty();
        for (let c = 0; c < data[r].length; c++) {

            let cell = data_row.Cells.get(c);
            cell.CellFormat.VerticalAlignment = wasmModule.VerticalAlignment.Middle;
            let text_range = cell.AddParagraph().AppendText(data[r][c]);
            text_range.CharacterFormat.FontName = 'Times New Roman'
            text_range.CharacterFormat.FontSize = 14;
        }
      }

      // Automatically fit the table to the cell content
      table.AutoFit(wasmModule.AutoFitBehaviorType.AutoFitToContents);

      // Save the document
      const outputFileName = 'output.docx';
      doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013});
 
      // Create a Blob for the downloaded file
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
      const url = URL.createObjectURL(modifiedFile);

      // Trigger file 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); 

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Add Tables to a Word Document in React</h1>
      <button onClick={AddTable} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

Add a table to a Word document in React

Get a Free License

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

Automatically generating a table of contents (TOC) in a Word document using JavaScript within a React application streamlines document creation by eliminating manual updates and ensuring dynamic consistency. This approach is particularly valuable in scenarios where content length, structure, or headings frequently change, such as in report-generation tools, academic platforms, or documentation systems. By leveraging Spire.Doc for JavaScript's WebAssembly module and React’s reactive state management, developers can programmatically detect headings, organize hierarchical sections, and insert hyperlinked TOC entries directly into Word files. In this article, we will explore how to use Spire.Doc for JavaScript to insert tables of contents into Word documents with JavaScript in React applications.

Install Spire.Doc for JavaScript

To get started with inserting tables of contents into Word documents in a React application, you can either download Spire.Doc for JavaScript from our website or install it via npm with the following command:

npm i spire.doc

After that, copy the "Spire.Doc.Base.js" and "Spire.Doc.Base.wasm" files into the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.

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

Insert a Default TOC into a Word Document Using JavaScript

Spire.Doc for JavaScript offers a WebAssembly module for processing Word documents in JavaScript environments. You can load a Word document from the virtual file system using the Document.LoadFromFile() method and insert a table of contents (TOC) via the Paragraph.AppendTOC() method, which auto-generates based on the document’s titles. Finally, update the TOC with the Document.UpdateTableOfContents() method.

The detailed steps are as follows:

  • Load the Spire.Doc.Base.js file to initialize the WebAssembly module.
  • Fetch the Word file to the virtual file system (VFS) using the wasmModule.FetchFileToVFS() method.
  • Create an instance of the Document class in the VFS using the wasmModule.Document.Create() method.
  • Load the Word document from the VFS using the Document.LoadFromFile() method.
  • Add a new section to the document using the Document.AddSection() method, and add a paragraph using the Section.AddParagraph() method.
  • Insert the section after the cover section using the Document.Sections.Insert() method.
  • Insert a TOC into the paragraph using the Paragraph.AppendTOC() method.
  • Update the TOC using the Document.UpdateTableOfContents() method.
  • Save the document to the VFS using the Document.SaveToFile() method.
  • Read the document from the VFS and download it.
  • 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 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 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.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 insert a default table of contents into a Word document
  const InsertTOCWord = async () => {
    if (wasmModule) {
      // Specify the input and output file names
      const inputFileName = 'Sample.docx';
      const outputFileName = 'DefaultTOC.docx';

      // Fetch the font file and add it to the VFS
      await wasmModule.FetchFileToVFS('HarmonyOS_Sans_SC_Regular.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

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

      // Create an instance of the Document class
      const doc = wasmModule.Document.Create();

      // Load the Word document
      doc.LoadFromFile({ fileName: inputFileName });

      // Create a new section
      const section = doc.AddSection();
      // Create a new paragraph
      const paragraph = section.AddParagraph();

      // Add a table of contents to the paragraph
      paragraph.AppendTOC(1, 2);

      // Insert the section after the cover section
      doc.Sections.Insert(1, section);

      // Update the table of contents
      doc.UpdateTableOfContents();

      // Save the document to the VFS
      doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2019})

      // Read the document from the VFS and create a Blob to trigger the download
      const wordArray = await wasmModule.FS.readFile(outputFileName);
      const blob = new Blob([wordArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
      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>Insert Default Table of Contents Using JavaScript in React</h1>
        <button onClick={InsertTOCWord} disabled={!wasmModule}>
          Insert and Download
        </button>
      </div>
  );
}

export default App;

Default Word TOC Inserted with JavaScript

Insert a Custom TOC into a Word Document Using JavaScript

Spire.Doc for JavaScript also enables users to create a custom table of contents. By creating an instance of the TableOfContent class, you can customize title and page number display using switches. For instance, the switch "{\o "1-3" \n 1-1}" configures the TOC to display titles from level 1 to 3 while omitting page numbers for level 1 titles. After creating the instance, insert it into the document and assign it as the TOC of the document using the Document.TOC property.

The detailed steps are as follows:

  • Load the Spire.Doc.Base.js file to initialize the WebAssembly module.
  • Fetch the Word file to the virtual file system (VFS) using the wasmModule.FetchFileToVFS() method.
  • Create an instance of the Document class in the VFS using the wasmModule.Document.Create() method.
  • Load the Word document from the VFS using the Document.LoadFromFile() method.
  • Add a new section to the document using the Document.AddSection() method, and add a paragraph using the Section.AddParagraph() method.
  • Insert the section after the cover section using the Document.Sections.Insert() method.
  • Create an instance of the TableOfContent class in the VFS using the wasmModule.TableOfContent.Create() method and specify the switch.
  • Insert the TOC into the new paragraph using the Paragraph.Items.Add() method.
  • Append the field separator and field end marks to complete the TOC field using the Paragraph.AppendFieldMark() method.
  • Set the new TOC as the document’s TOC through the Document.TOC property.
  • Update the TOC using the Document.UpdateTableOfContents() method.
  • Save the document to the VFS using the Document.SaveToFile() method.
  • Read the document from the VFS and download it.
  • 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 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 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.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 insert a custom table of contents into a Word document
  const InsertTOCWord = async () => {
    if (wasmModule) {
      // Specify the input and output file names
      const inputFileName = 'Sample.docx';
      const outputFileName = 'CustomTOC.docx';

      // Fetch the font file and add it to the VFS
      await wasmModule.FetchFileToVFS('HarmonyOS_Sans_SC_Regular.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

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

      // Create an instance of the Document class
      const doc = wasmModule.Document.Create();

      // Load the Word document
      doc.LoadFromFile({ fileName: inputFileName });

      // Add a new section and paragraph
      const section = doc.AddSection();
      const para = section.AddParagraph();

      // Insert the section after the cover section
      doc.Sections.Insert(1, section)

      // Create an instance of the TableOfContent class and specify the switch
      const toc = wasmModule.TableOfContent.Create(doc, '{\\o \”1-3\” \\n 1-1}');

      // Add the table of contents to the new paragraph
      para.Items.Add(toc);

      // Insert a field separator mark to the paragraph
      para.AppendFieldMark(wasmModule.FieldMarkType.FieldSeparator);

      // Insert a field end mark to the paragraph
      para.AppendFieldMark(wasmModule.FieldMarkType.FieldEnd);

      // Set the new TOC as the TOC of the document
      doc.TOC = toc;

      // Update the TOC
      doc.UpdateTableOfContents();

      // Save the document to the VFS
      doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2019});

      // Read the document from the VFS and create a Blob to trigger the download
      const wordArray = await wasmModule.FS.readFile(outputFileName);
      const blob = new Blob([wordArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
      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>Insert a Custom Table of Contents Using JavaScript in React</h1>
        <button onClick={InsertTOCWord} disabled={!wasmModule}>
          Insert and Download
        </button>
      </div>
  );
}

export default App;

Custom Word TOC using JavaScript in React

Remove the Table of Contents from a Word Document

Since TOC paragraphs have style names that start with "TOC", you can locate them by matching a regular expression on the paragraph style and then remove those paragraphs.

The detailed steps are as follows:

  • Load the Spire.Doc.Base.js file to initialize the WebAssembly module.
  • Fetch the Word file to the virtual file system (VFS) using the wasmModule.FetchFileToVFS() method.
  • Create an instance of the Document class in the VFS using the wasmModule.Document.Create() method.
  • Load the Word document from the VFS using the Document.LoadFromFile() method.
  • Create an instance of the Regex class with the pattern "TOC\w+".
  • Iterate through each section in the document and access its body using the Document.Sections.get_Item().Body property.
  • Loop through the paragraphs in each section body and retrieve each paragraph's style via the Paragraph.StyleName property.
  • Identify paragraphs whose style matches the regex using the Regex.IsMatch() method and remove them using the Section.Body.Paragraphs.RemoveAt() method.
  • Save the document to the VFS using the Document.SaveToFile() method.
  • Read the document from the VFS and download it.
  • 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 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 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.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 remove the table of contents from a Word document
  const InsertTOCWord = async () => {
    if (wasmModule) {
      // Specify the input and output file names
      const inputFileName = 'CustomTOC.docx';
      const outputFileName = 'RemoveTOC.docx';

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

      // Create an instance of the Document class
      const doc = wasmModule.Document.Create();

      // Load the Word document
      doc.LoadFromFile({ fileName: inputFileName });

      // Create a regex pattern to match the style name of TOC
      const regex = wasmModule.Regex.Create("TOC\\w+", wasmModule.RegexOptions.None);

      // Iterate through each section
      for (let i = 0; i < doc.Sections.Count; i++) {
        // Iterate through each paragraph in the section body
        const sectionBody = doc.Sections.get_Item(i).Body;
        for (let j = 0; j < sectionBody.Paragraphs.Count; j++) {
          // Check if the style name matches the regex pattern
          const paragraph = sectionBody.Paragraphs.get_Item(j);
          if (regex.IsMatch(paragraph.StyleName)) {
            // Remove the paragraph
            sectionBody.Paragraphs.RemoveAt(j)
            // Or remove the section
            //doc.Sections.RemoveAt(i)
            //i--
            j--
          }
        }
      }

      // Save the document to the VFS
      doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2019});

      // Read the document from the VFS and create a Blob to trigger the download
      const wordArray = await wasmModule.FS.readFile(outputFileName);
      const blob = new Blob([wordArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
      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>Insert a Custom Table of Contents Using JavaScript in React</h1>
        <button onClick={InsertTOCWord} disabled={!wasmModule}>
          Insert and Download
        </button>
      </div>
  );
}

export default App;

Get a Free License

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

page