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.

When reviewing a long document, the find and highlight feature allows users to quickly locate specific information. For example, if there are multiple people working on a research paper, the find and highlight feature can be used to flag important points or areas that need attention, making it easier for others to focus on those specific parts. This article will demonstrate how to find and highlight text in a Word document in React using Spire.Doc for JavaScript.

Install the JavaScript Library

To get started with inserting images in Word 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.

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

Find and Highlight the First Instance of Specified Text in Word in JavaScript

The Document.FindString() method allows to find the first instance of a specified text and then you can set a highlight color for it through the TextRange.CharacterFormat.HighlightColor property. The following are the main steps:

  • Create a new document using the wasmModule.Document.Create() method.
  • Load a Word document using the Document.LoadFromFile() method.
  • Find the first instance of a specific text using the Document.FindString() method.
  • Get the instance as a single text range using the TextSelection.GetAsOneRange() method, and then highlight the text range with a background color using the TextRange.CharacterFormat.HighlightColor property.
  • Save the result document using Document.SaveToFile() method.
  • 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 find and higlight a specified text in Word
  const FindHighlightFirst = async () => {
    if (wasmModule) {

      // Load the sample file into the virtual file system (VFS)
      let inputFileName = 'Spire.docx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);

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

      // Load the Word document
      doc.LoadFromFile(inputFileName);

      // Find the first instance of a specific text
      let textSelection = doc.FindString('Spire.Doc for JavaScript', false, true);

      // Get the instance as a single text range
      let textRange = textSelection.GetAsOneRange();

      // Set highlight color
      textRange.CharacterFormat.HighlightColor = wasmModule.Color.get_Yellow();

      // Save the result document
      const outputFileName = 'FindHighlightFirst.docx';
      doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });

      // Release resources
      doc.Dispose();

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

      // Create a Blob object from the Word file
      const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
      
      // 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>Find and Highlight Specified Text in Word Using JavaScript in React</h1>
      <button onClick={FindHighlightFirst} disabled={!wasmModule}>
      Execute
      </button>
    </div>
 );
}
     
export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Execute" button to download the result file:

Run the code to launch the React app

The result file:

Find the first occurrence of a specified text and highlight it

Find and Highlight All Instances of Specified Text in Word in JavaScript

Spire.Doc for JavaScript also provides the Document.FindAllString() method to find all instances of a specified text in a Word document. Then you can iterate through these instances and highlight each one with a background color. The following are the main steps:

  • Create a new document using the wasmModule.Document.Create() method.
  • Load a Word document using the Document.LoadFromFile() method.
  • Find all instances of a specific text in the document using the Document.FindAllString() method.
  • Iterate through each found instance and get it as a single text range using the TextSelection.GetAsOneRange() method, then highlight each text range with a bright color using the TextRange.CharacterFormat.HighlightColor property.
  • Save the result document using Document.SaveToFile() method.
  • 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 find and higlight a specified text in Word
  const FindAndHighlightAll = async () => {
    if (wasmModule) {

      // Load the sample file into the virtual file system (VFS)
      let inputFileName = 'Spire.docx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);

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

      // Load the Word document
      doc.LoadFromFile(inputFileName);

      // Find all occurrences of the specified text in the document
      let textSelections = doc.FindAllString('Spire.Doc for JavaScript', false, true);

      // Iterate through all found text selections
      for (let i = 0; i < textSelections.length; i++) {
        let selection = textSelections[i];

        // Set highlight color 
        selection.GetAsOneRange().CharacterFormat.HighlightColor = wasmModule.Color.get_Yellow();
      }

      // Save the result document
      const outputFileName = 'FindAndHighlight.docx';
      doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });

      // Release resources
      doc.Dispose();

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

      // Create a Blob object from the Word file
      const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
      
      // 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>Find and Highlight Specified Text in Word Using JavaScript in React</h1>
      <button onClick={FindAndHighlightAll} disabled={!wasmModule}>
      Execute
      </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.

Incorporating a watermark to Word documents is a simple yet impactful way to protect your content and assert ownership. Whether you're marking a draft as confidential or branding a business document, watermarks can convey essential information without distracting from your text.

In this article, you will learn how to add and customize watermarks in Word documents in a React application using Spire.Doc for JavaScript.

Install Spire.Doc for JavaScript

To get started with adding watermarks to Word 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 a Text Watermark to Word in React

Spire.Doc for JavaScript provides the TextWatermark class, enabling users to create customizable text watermarks with their preferred text and font effects. Once the TextWatermark object is created, it can be applied to the entire document using the Document.Watermark property.

The steps to add a text watermark to Word in React are as follows:

  • Load the necessary font file and input Word document into the virtual file system (VFS).
  • Create a Document object using the wasmModule.Document.Create() method.
  • Load the Word file using the Document.LoadFromFile() method.
  • Create a TextWatermark object using the wasmModule.TextWatermark.Create() method.
  • Customize the watermark's text, font size, font name, and color using the properties under the TextWatermark object.
  • Apply the text watermark to the document using the Document.Watermark property.
  • Save the document and trigger a 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 Spire.Doc 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 add a text watermark
  const AddWatermark = async () => {
    if (wasmModule) {

      // Load the required font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS("ARIALUNI.TTF","/Library/Fonts/",`${process.env.PUBLIC_URL}/`);

      // Load the input Word file into the VFS
      const inputFileName = 'input.docx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);

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

      // Load the Word document
      doc.LoadFromFile(inputFileName);

      // Create a TextWatermark instance
      let txtWatermark = wasmModule.TextWatermark.Create();
      
      // Set the text for the watermark
      txtWatermark.Text = "Do Not Copy";
      
      // Set the font size and name for the text
      txtWatermark.FontSize = 58;
      txtWatermark.FontName = "Arial"
      
      // Set the color of the text
      txtWatermark.Color = wasmModule.Color.get_Blue();
      
      // Set the layout of the watermark to diagonal
      txtWatermark.Layout = wasmModule.WatermarkLayout.Diagonal;

      // Apply the text watermark to the document
      doc.Watermark = txtWatermark;

      // Define the output file name
      const outputFileName = "TextWatermark.docx";

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

      // Read the generated file from VFS
      const fileArray = wasmModule.FS.readFile(outputFileName);
      
      // Create a Blob object from the file
      const blob = new Blob([fileArray], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});      

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

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

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

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

export default App;

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

Run React app to add watermarks to Word

Here is a screenshot of the generated Word file that includes a text watermark:

Add a text watermark to Word in React

Add an Image Watermark to Word in React

Spire.Doc for JavaScript provides the PictrueWatermark to help configure the image resource, scaling, washout effect for image watermarks in Word. Once a PictureWatermak object is created, you can apply it to an entire document using the Document.Watermark property.

Steps to add an image watermark to a Word document in React:

  • Load the image file and input Word document into the virtual file system (VFS).
  • Create a Document object using the wasmModule.Document.Create() method.
  • Load the Word file using the Document.LoadFromFile() method.
  • Create a PictureWatermark object using the wasmModule.PictureWatermark.Create() method.
  • Set the image resource, scaling, and washout effect for the watermark using the methods and properties under the PictureWatermark object.
  • Apply the image watermark to the document using the Document.Watermark property.
  • Save the document and trigger a 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 Spire.Doc 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 add an image watermark
  const AddWatermark = async () => {
    if (wasmModule) {

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

      // Load the input Word file into the VFS
      const inputFileName = 'input.docx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);

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

      // Load the Word document
      doc.LoadFromFile(inputFileName);
  
      // Create a new PictureWatermark instance
      const pictureWatermark = wasmModule.PictureWatermark.Create();

      // Set the picture
      pictureWatermark.SetPicture(imageFileName);

      // Set the scaling factor of the image
      pictureWatermark.Scaling = 150;

      // Disable washout effect
      pictureWatermark.IsWashout = false;

      // Apply the image watermark to the document
      doc.Watermark = pictureWatermark;
    
      // Define the output file name
      const outputFileName = 'ImageWatermark.docx';

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

      // Read the generated file from VFS
      const fileArray = wasmModule.FS.readFile(outputFileName);
      
      // Create a Blob object from the file
      const blob = new Blob([fileArray], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});      

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

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

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

  return (
    

Add an Image Watermark to Word in React

); } export default App;

Add an image watermark to Word 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.

In MS word, images can quickly and easily convey complex information that may be difficult to explain in words alone. Whether you're creating a report, a presentation, a newsletter, or a simple document, adding images can make your content more engaging, informative, and visually appealing. In this article, you will learn how to add images to a Word document in React using Spire.Doc for JavaScript.

Install the JavaScript Library

To get started with inserting images in Word 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.

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

Insert an Image in a Word Document in JavaScript

The Paragraph.AppendPicture() method offered by Spire.Doc for JavaScript allows to insert an image into a Word document. The following are the main steps to insert an image in Word and set its size, text wrapping style using JavaScript.

  • Create a new document using the wasmModule.Document.Create() method.
  • Load a Word document using the Document.LoadFromFile() method.
  • Get a specified section in the document using the Document.Sections.get() method.
  • Get a specified paragraph in the section using the Section.Paragraphs.get_Item() method.
  • Add an image to the specified paragraph using the Paragraph.AppendPicture() method.
  • Set width, height and text wrapping style for the image.
  • Save the result document using Document.SaveToFile() method.
  • 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 insert an image in Word
  const InsertWordImage = async () => {
    if (wasmModule) {
      // Load the input file into the virtual file system (VFS)
      const inputFileName = "Spire.docx";
      await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);
      
      // Load the image file into the virtual file system (VFS)
      const imageFile = "JS.png";
      await wasmModule.FetchFileToVFS(imageFile, "", `${process.env.PUBLIC_URL}/`);

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

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

      // Get the first section
      const section = doc.Sections.get(0);
      
      // Get the first paragraph
      const paragraph = section.Paragraphs.get_Item(0);

      // Add the image to the first paragraph
      let picture = paragraph.AppendPicture({ imgFile: imageFile });

      // Set image width and height
      picture.Width = 100;
      picture.Height = 100;

      // Set text wrapping style for the image
      picture.TextWrappingStyle = wasmModule.TextWrappingStyle.Square;
      
      // Save the result document
      const outputFileName = "InsertImage.docx";
      doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx });

      // Release resources
      doc.Dispose();

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

      // Create a Blob object from the Word file
      const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
      
      // 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>Insert an Image in a Word Document Using JavaScript in React</h1>
      <button onClick={InsertWordImage} disabled={!wasmModule}>
      Execute
      </button>
    </div>
 );
}
     
export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Execute" button to download the result file:

Run the code to launch the React app

The input file and the result file:

Add an image to the first paragraph in a Word document

Insert an Image at a Specified Location in Word in JavaScript

You can also place the image at any specified location in the Word document through the DocPicture.HorizontalPosition and DocPicture.VerticalPosition properties. The following are the main steps:

  • Create a new document using the wasmModule.Document.Create() method.
  • Add a section to the document using the Document.AddSection() method.
  • Add a paragraph to the section using the Section.AddParagraph() method.
  • Add text to the paragraph and set paragraph style.
  • Add an image to the paragraph using the Paragraph.AppendPicture() method.
  • Set the horizontal position and vertical position for the image through the DocPicture.HorizontalPosition and DocPicture.VerticalPosition properties.
  • Set width, height and text wrapping style for the image.
  • Save the result document using Document.SaveToFile() method.
  • 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 insert an image at a specified location in Word
  const InsertImage = async () => {
    if (wasmModule) {

      // Load the image file into the virtual file system (VFS)
      const imageFile = "JS.png";
      await wasmModule.FetchFileToVFS(imageFile, "", `${process.env.PUBLIC_URL}/`);

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

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

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

      // Add text to the paragraph and set paragraph style
      paragraph.AppendText("The sample demonstrates how to insert an image at a specified location in a Word document.");
      paragraph.ApplyStyle({ builtinStyle: wasmModule.BuiltinStyle.Heading2 });

      //Add an image to the paragraph
      let picture = paragraph.AppendPicture({ imgFile: imageFile });

      // Set image position
      picture.HorizontalPosition = 150.0;
      picture.VerticalPosition = 70.0;

      // Set image width and height
      picture.Width = 100;
      picture.Height = 100;

      // Set text wrapping style for the image
      picture.TextWrappingStyle = wasmModule.TextWrappingStyle.Through;
      
      // Save the result document
      const outputFileName = "WordImage.docx";
      doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx });

      // Release resources
      doc.Dispose();

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

      // Create a Blob object from the Word file
      const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
      
      // 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>Insert an Image at a Specified Location in Word Using JavaScript in React</h1>
      <button onClick={InsertImage} disabled={!wasmModule}>
      Execute
      </button>
    </div>
 );
}
     
export default App;

Insert an image at a specified location in Word

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.

Adding or removing text boxes in Word is a valuable skill that enhances document layout and visual appeal. Text boxes provide a flexible way to highlight important information, create side notes, or organize content more effectively. They allow for creative formatting options, enabling you to draw attention to specific areas of your document.

In this article, you will learn how to add or move text boxes in a Word document in React using Spire.Doc for JavaScript.

Install Spire.Doc for JavaScript

To get started wtih manipulating text boxes in Word in a React applicaiton, 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 and consistent text rendering.

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

Add a Text Box to a Word Document in React

Spire.Doc for JavaScript offers the Paragraph.AppendTextBox() method to seamlessly insert a text box into a specified paragraph. Once inserted, you can customize the text box by adding content and applying formatting using properties like TextBox.Body and TextBox.Format.

The following are the steps to add a text box to a Word document in React:

  • Load required font and input file into the virtual file system (VFS).
  • Create a Document object using the wasmModule.Document.Create() method.
  • Load the Word file using the Document.LoadFromFile() method.
  • Access the first section and paragraph.
  • Insert a text box to the paragraph using the Paragraph.AppendTextBox() method.
  • Add a paragraph to the text box and append text to it through the TextBox.Body property.
  • Customize the appearance of the text box through the TextBox.Format property.
  • Save the document and trigger a 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 Spire.Doc 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 box
  const AddTextBox = async () => {
    if (wasmModule) {

      // Load the font files into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

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

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

      // Load the Word document
      doc.LoadFromFile(inputFileName);

      // Get a specific section
      let section = doc.Sections.get_Item(0)

      // Get a specific paragraph
      let paragraph = section.Paragraphs.get_Item(0)

      // Insert a textbox and set its wrapping style
      let textBox = paragraph.AppendTextBox(150, 100);
      textBox.Format.TextWrappingStyle = wasmModule.TextWrappingStyle.Square;

      // Set the position of the textbox
      textBox.Format.HorizontalPosition = 0;
      textBox.Format.VerticalPosition = 50;

      // Set the line style and fill color
      textBox.Format.LineColor = wasmModule.Color.get_DarkBlue();
      textBox.Format.LineStyle = wasmModule.TextBoxLineStyle.Simple;
      textBox.Format.FillColor = wasmModule.Color.get_LightGray();
  
      // Add a paragraph to the textbox
      let para = textBox.Body.AddParagraph();
      let textRange = para.AppendText("This is a sample text box created by Spire.Doc for JavaScript.");

      // Format the text 
      textRange.CharacterFormat.FontName = "Arial";
      textRange.CharacterFormat.FontSize = 15;
      textRange.CharacterFormat.TextColor = wasmModule.Color.get_Blue();

      // Set the horizontal alignment of the paragraph
      para.Format.HorizontalAlignment = wasmModule.HorizontalAlignment.Center;
 
      // Define the output file name
      const outputFileName = "Textbox.docx";
 
      // Save the document to the specified path
      doc.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2013});

      // Read the generated file from VFS
      const fileArray = wasmModule.FS.readFile(outputFileName);
      
      // Create a Blob object from the file
      const blob = new Blob([fileArray], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});      

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

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

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Add a text box to Word in React</h1>
      <button onClick={AddTextBox} 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 runs at localhost:3000

Here is a screenshot of the generated Word file that includes a text box:

Add a text box to a Word document in React

Remove a Text Box from a Word Document in React

Spire.Doc for JavaScript includes the Document.TextBoxes.RemoveAt() method, which allows you to delete a specific text box by its index. If you need to remove all text boxes from a Word document, you can use the Document.TextBoxes.Clear() method for a quick and efficient solution.

The following are the steps to remove a text box from a Word document in React:

  • Load the input file into the virtual file system (VFS).
  • Create a Document object using the wasmModule.Document.Create() method.
  • Load the Word file using the Document.LoadFromFile() method.
  • Remove a specific text box using the Document.TextBoxes.RemoveAt() method.
  • Save the document and trigger a 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 Spire.Doc 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 remove text box
  const RemoveTextBox = async () => {
    if (wasmModule) {

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

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

      // Load the Word document
      doc.LoadFromFile(inputFileName);

      // Remove the text box at index 0
      doc.TextBoxes.RemoveAt(0);
       
// Remove all text boxes
// doc.TextBoxes.Clear();
        
      // Define the output file name
      const outputFileName = "RemoveTextBox.docx";

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

      // Read the generated file from VFS
      const fileArray = wasmModule.FS.readFile(outputFileName);
      
      // Create a Blob object from the file
      const blob = new Blob([fileArray], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});      

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

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

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Remove a text box from Word in React</h1>
      <button onClick={RemoveTextBox} disabled={!wasmModule}>
        Generate
      </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.

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.

Seamless conversion between Word documents and Markdown files is increasingly essential in web development for boosting productivity and interoperability. Word documents dominate in complex formatting, while Markdown offers a simple, universal approach to content creation. Enabling conversion between the two within a React application allows users to work in their preferred format while ensuring compatibility across different platforms, streamlining workflows without relying on external tools. In this article, we will explore how to use Spire.Doc for JavaScript to convert Word to Markdown and Markdown to Word with JavaScript in React applications.

Install Spire.Doc for JavaScript

To get started with conversion between Word and Markdown 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

Convert Word to Markdown with JavaScript

The Spire.Doc for JavaScript provides a WebAssembly module that enables loading Word documents from the VFS and converting them to Markdown. Developers can achieve this conversion by fetching the documents to the VFS, loading them using the Document.LoadFromFile() method, and saving them as Markdown with the Document.SaveToFile() method. The process involves the following steps:

  • Load the Spire.Doc.Base.js file to initialize the WebAssembly module.
  • Fetch the Word document into the virtual file system using the wasmModule.FetchFileToVFS() method.
  • Create a Document instance in the WebAssembly module using the wasmModule.Document.Create() method.
  • Load the Word document into the Document instance with the Document.LoadFromFile() method.
  • Convert the document to Markdown format and save it to the VFS using the Document.SaveToFile() method.
  • Read and download the file, or use it as needed.
  • 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 convert Word to Markdown
  const ConvertHTMLStringToPDF = async () => {
    if (wasmModule) {
      // Specify the output file name
      const inputFileName = 'Sample.docx';
      const outputFileName = 'WordToMarkdown.md';

      // Fetch the font 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(inputFileName);

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

      // Release resources
      doc.Dispose();

      // Read the markdown file
      const mdContent = await wasmModule.FS.readFile(outputFileName)

      // Generate a Blob from the markdown file and trigger a download
      const blob = new Blob([mdContent], {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>Convert Word to Markdown Using JavaScript in React</h1>
        <button onClick={ConvertHTMLStringToPDF} disabled={!wasmModule}>
          Convert and Download
        </button>
      </div>
  );
}

export default App;

Result of Converting Word to Markdown with JavaScript

Convert Markdown to Word with JavaScript

The Document.LoadFromFile() method can also be used to load a Markdown file by specifying the file format parameter as wasmModule.FileFormat.Markdown. Then, the Markdown file can be exported as a Word document using the Document.SaveToFile() method.

For Markdown strings, developers can write them as Markdown files into the virtual file system using the wasmModule.FS.writeFile() method, and then convert them to Word documents.

The detailed steps for converting Markdown content to Word documents are as follows:

  • Load the Spire.Doc.Base.js file to initialize the WebAssembly module.
  • Load required font files into the virtual file system using the wasmModule.FetchFileToVFS() method.
  • Import Markdown content:
    • For files: Use the wasmModule.FetchFileToVFS() method to load the Markdown file into the VFS.
    • For strings: Write Markdown content to the VFS via the wasmModule.FS.writeFile() method.
  • Instantiate a Document object via the wasmModule.Document.Create() method within the WebAssembly module.
  • Load the Markdown file into the Document instance using the Document.LoadFromFile({ filename: string, fileFormat: wasmModule.FileFormat.Markdown }) method.
  • Convert the Markdown file to a Word document and save it to the VFS using the Document.SaveToFile( { filename: string, fileFormat:wasmModule.FileFormat.Docx2019 }) method.
  • Retrieve and download the generated Word file from the VFS, or process it further as required.
  • 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 convert Markdown to Word
  const ConvertHTMLStringToPDF = async () => {
    if (wasmModule) {
      // Specify the output file name
      const outputFileName = 'MarkdownStringToWord.docx';

      // Fetch the required font files into the VFS
      await wasmModule.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

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

      // Fetch the Markdown file to the VFS and load it into the Document instance
      // await wasmModule.FetchFileToVFS('MarkdownExample.md', '', `${process.env.PUBLIC_URL}/`);
      // doc.LoadFromFile({ fileName: 'MarkdownExample.md', fileFormat: wasmModule.FileFormat.Markdown });

      // Define the Markdown string
      const markdownString = '# Project Aurora: Next-Gen Climate Modeling System *\n' +
          '## Overview\n' +
          'A next-generation climate modeling platform leveraging AI to predict regional climate patterns with 90%+ accuracy. Built for researchers and policymakers.\n' +
          '### Key Features\n' +
          '- * Real-time atmospheric pattern recognition\n' +
          '- * Carbon sequestration impact modeling\n' +
          '- * Custom scenario simulation builder\n' +
          '- * Historical climate data cross-analysis\n' +
          '\n' +
          '## Sample Usage\n' +
          '| Command | Description | Example Output |\n' +
          '|---------|-------------|----------------|\n' +
          '| `region=asia` | Runs climate simulation for Asia | JSON with temperature/precipitation predictions |\n' +
          '| `model=co2` | Generates CO2 impact visualization | Interactive 3D heatmap |\n' +
          '| `year=2050` | Compares scenarios for 2050 | Tabular data with Δ values |\n' +
          '| `format=netcdf` | Exports data in NetCDF format | .nc file with metadata |'

      // Write the Markdown string to a file in the VFS
      await wasmModule.FS.writeFile('Markdown.md', markdownString, {encoding: 'utf8'})

      // Load the Markdown file from the VFS
      doc.LoadFromFile({ fileName: 'Markdown.md', fileFormat: wasmModule.FileFormat.Markdown });

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

      // Release resources
      doc.Dispose();

      // Read the Word file
      const outputWordFile = await wasmModule.FS.readFile(outputFileName)

      // Generate a Blob from the Word file and trigger a download
      const blob = new Blob([outputWordFile], { 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>Convert Markdown to Word Using JavaScript in React</h1>
        <button onClick={ConvertHTMLStringToPDF} disabled={!wasmModule}>
          Convert and Download
        </button>
      </div>
  );
}

export default App;

Converting Markdown to Word 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.

In modern web development, generating PDFs directly from HTML is essential for applications requiring dynamic reports, invoices, or user-specific documents. Using JavaScript to convert HTML to PDF in React applications ensures the preservation of structure, styling, and interactivity, transforming content into a portable, print-ready format. This method eliminates the need for separate PDF templates, leverages React's component-based architecture for dynamic rendering, and reduces server-side dependencies. By embedding PDF conversion into the front end, developers can provide a consistent user experience, enable instant document downloads, and maintain full control over design and layout. This article explores how to use Spire.Doc for JavaScript to convert HTML files and strings to PDF in React applications.

Install Spire.Doc for JavaScript

To get started with converting HTML to PDF 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

Convert an HTML File to PDF with JavaScript

Using the Spire.Doc WASM module, developers can load HTML files into a Document object with the Document.LoadFromFile() method and then convert them to PDF documents using the Document.SaveToFile() method. This approach provides a concise and efficient solution for HTML-to-PDF conversion in web development.

The detailed steps are as follows:

  • Load the Spire.Doc.Base.js file to initialize the WebAssembly module.
  • Load the HTML file and the font files used in the HTML file into the virtual file system using the wasmModule.FetchFileToVFS() method.
  • Create an instance of the Document class using the wasmModule.Document.Create() method.
  • Load the HTML file into the Document instance using the Document.LoadFromFile() method.
  • Convert the HTML file to PDF format and save it using the Document.SaveToFile() method.
  • Read the converted file as a file array 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 convert HTML files to PDF document
  const ConvertHTMLFileToPDF = async () => {
    if (wasmModule) {
      // Specify the input and output file names
      const inputFileName = 'Sample.html';
      const outputFileName = 'HTMLFileToPDF.pdf';

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

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

      // Create an instance of the Document class
      const doc = wasmModule.Document.Create();
      // Load the Word document
      doc.LoadFromFile({ fileName: inputFileName, fileFormat: wasmModule.FileFormat.Html, validationType: wasmModule.XHTMLValidationType.None });

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

      // Release resources
      doc.Dispose();

      // Read the saved file from the VFS
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

      // Generate a Blob from the file array and trigger a download
      const blob = new Blob([modifiedFileArray], {type: 'application/pdf'});
      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 (
      

Convert HTML Files to PDF Using JavaScript in React

); } export default App;

Converting HTML Files to PDF with JavaScript Result

Convert an HTML String to PDF with JavaScript

Spire.Doc for JavaScript offers the Paragraph.AppendHTML() method, which allows developers to insert HTML-formatted content directly into a document paragraph. Once the HTML content is added, the document can be saved as a PDF, enabling a seamless conversion from an HTML string to a PDF file.

The detailed steps are as follows:

  • Load the Spire.Doc.Base.js file to initialize the WebAssembly module.
  • Define the HTML string.
  • Load the font files used in the HTML string using the wasmModule.FetchFileToVFS() method.
  • Create a new Document instance using the wasmModule.Document.Create() method.
  • Add a section to the document using the Document.AddSection() method.
  • Add a paragraph to the section using the Section.AddParagraph() method.
  • Insert the HTML content into the paragraph using the Paragraph.AppendHTML() method.
  • Save the document as a PDF file using the Document.SaveToFile() method.
  • Read the converted file as a file array 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 convert HTML string to PDF
  const ConvertHTMLStringToPDF = async () => {
    if (wasmModule) {
      // Specify the output file name
      const outputFileName = 'HTMLStringToPDF.pdf';

      // Define the HTML string
      const htmlString = `
          <html lang="en">
              <head>
                  <meta charset="UTF-8">
                  <title>Sales Snippet</title>
              </head>
              <body style="font-family: Arial, sans-serif; margin: 20px;">
                  <div style="border: 1px solid #ddd; padding: 15px; max-width: 600px; margin: auto; background-color: #f9f9f9;">
                      <h1 style="color: #e74c3c; text-align: center;">Limited Time Offer!</h1>
                      <p style="font-size: 1.1em; color: #333; line-height: 1.5;">
                          Get ready to save big on all your favorites. This week only, enjoy 15% off site wide. From trendy clothing to home decor, find everything you love at unbeatable prices.
                      </p>
                      <div style="text-align: center;">
                          <button 
                              style="background-color: #5cb85c; border: none; color: white; padding: 10px 20px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; border-radius: 8px;"
                          >
                              Shop Deals
                          </button>
                      </div>
                  </div>
              </body>
          </html>
      `;

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

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

      // Add a section to the document
      const section = doc.AddSection();

      // Add a paragraph to the section
      const paragraph = section.AddParagraph();

      // Insert the HTML content to the paragraph
      paragraph.AppendHTML(htmlString)

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

      // Release resources
      doc.Dispose();

      // Read the saved file from the VFS
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

      // Generate a Blob from the file array and trigger a download
      const blob = new Blob([modifiedFileArray], {type: 'application/pdf'});
      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>Convert HTML Strings to PDF Using JavaScript in React</h1>
        <button onClick={ConvertHTMLStringToPDF} disabled={!wasmModule}>
          Convert and Download
        </button>
      </div>
  );
}

export default App;

Effect of HTML String to PDF Conversion 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.

Converting between Word and TXT formats is a skill that can greatly enhance your productivity and efficiency in handling documents. For example, converting a Word document to a plain text file can make it easier to analyze and manipulate data using other text processing tools or programming languages. Conversely, converting a text file to Word format allows you to add formatting, graphics, and other elements to enhance the presentation of the content. In this article, you will learn how to convert text files to Word format or convert Word files to text format in React using Spire.Doc for JavaScript.

Install Spire.Doc for JavaScript

To get started with the conversion between the TXT and Word formats 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.

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

Convert Text (TXT) to Word in JavaScript

Spire.Doc for JavaScript allows you to load a TXT file and then save it to Word Doc or Docx format using the Document.SaveToFile() method. The following are the main steps.

  • Create a new document using the wasmModule.Document.Create() method.
  • Load a text file using the Document.LoadFromFile() method.
  • Save the text file as a Word document using the Document.SaveToFile() method.
  • 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 convert a text file to a Word document
  const TXTtoWord = async () => {
    if (wasmModule) {

      // Specify the input and output file paths
      const inputFileName = 'input.txt';
      const outputFileName = 'TxtToWord.docx';

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

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

      // Load the text file
      doc.LoadFromFile(inputFileName);

      // Save the text file as a Word document 
      doc.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2016});

      // Read the generated Word document from VFS
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

      // Create a Blog object from the Word document
      const modifiedFile = new Blob([modifiedFileArray], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});

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

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert Text to Word Using JavaScript in React</h1>
      <button onClick={TXTtoWord} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to download the Word document converted from a TXT file:

Run the React app at localhost:3000

Below is the input text file and the generated Word document:

Convert a TXT file to a Word document

Convert Word to Text (TXT) in JavaScript

The Document.SaveToFile() method can also be used to export a Word Doc or Docx document to a plain text file. The following are the main steps.

  • Create a new document using the wasmModule.Document.Create() method.
  • Load a Word document using the Document.LoadFromFile() method.
  • Save the Word document in TXT format using the Document.SaveToFile({fileName: string, fileFormat: wasmModule.FileFormat.Txt}) method.
  • 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 convert a Word document to a text file 
  const WordToTXT = async () => {
    if (wasmModule) {

      // Specify the input and output file paths
      const inputFileName = 'Data.docx';
      const outputFileName = 'WordToText.txt';

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

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

      // Load the Word document
      doc.LoadFromFile(inputFileName);

      // Save the Word document in TXT format
      doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Txt});

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

      // Create a Blog object from the text file
      const modifiedFile = new Blob([modifiedFileArray], {type: 'text/plain'});

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

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

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

export default App;

Convert a Word document to a text file

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.

Converting HTML to images allows you to transform HTML content into static images that can be easily shared on social media, embedded in emails, or used as thumbnails in search engine results. This conversion process ensures that your content is displayed consistently across different devices and browsers, improving the overall user experience. In this article, you will learn how to convert HTML to images in React using Spire.Doc for JavaScript.

Install Spire.Doc for JavaScript

To get started with converting Word documents to PDF 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 and consistent text rendering.

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

Convert an HTML File to an Image in JavaScript

Spire.Doc for JavaScript allows you to load an HTML file and convert a specific page to an image stream using the Document.SaveImageToStreams() method. The image streams can then be further saved to a desired image format such as jpg, png, bmp, gif. The following are the main steps.

  • Load the font file to ensure correct text rendering.
  • Create a new document using the wasmModule.Document.Create() method.
  • Load the HTML file using the Document.LoadFromFile() method.
  • Convert a specific page to an image stream using the Document.SaveImageToStreams() method.
  • Save the image stream to a specified image format.
  • 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 convert an HTML file to an image
  const HtmlToImage = async () => {
    if (wasmModule) {

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

      // Specify the input and output file paths
      const inputFileName = 'sample1.html';
      const outputFileName = 'HtmlToImage.png';

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

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

      // Load the HTML file
      doc.LoadFromFile({fileName: inputFileName,fileFormat: wasmModule.FileFormat.Html,validationType: wasmModule.XHTMLValidationType.None});

      // Save the first page as an image stream
      let image = doc.SaveImageToStreams({pageIndex : 0, imagetype : wasmModule.ImageType.Bitmap});

      // Save the image stream as a PNG file
      image.Save(outputFileName);

      // Read the generated image from VFS
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

      // Create a Blog object from the image file
      const modifiedFile = new Blob([modifiedFileArray], {type: 'image/png'});

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

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert an HTML File to an Image Using JavaScript in React</h1>
      <button onClick={HtmlToImage} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to download the image converted from an HTML file:

Run the React app at localhost:3000

Below is the converted image file:

A PNG image converted from an Html file

Convert an HTML String to an Image in JavaScript

To convert HTML strings to images, you'll need to first add HTML strings to the paragraphs of a Word page through the Paragraph.AppendHTML() method, and then convert the page to an image. The following are the main steps.

  • Load the font file to ensure correct text rendering.
  • Specify the HTML string.
  • Create a new document using the wasmModule.Document.Create() method.
  • Add a new section using the Document.AddSection() method.
  • Add a paragraph to the section using the Section.AddParagraph() method.
  • Append the HTML string to the paragraph using the Paragraph.AppendHTML() method.
  • Convert a specific page to an image stream using the Document.SaveImageToStreams() method.
  • Save the image stream to a specified image format.
  • 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 convert an HTML string to an image
  const HtmlStringToImage = async () => {
    if (wasmModule) {

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

      // Specify the output file path
      const outputFileName = 'HtmlStringToImage.png';

      // Specify the HTML string
      let HTML = "<html><head><title>HTML to Word Example</title><style>, body {font-family: 'Calibri';}, h1 {color: #FF5733; font-size: 24px; margin-bottom: 20px;}, p {color: #333333; font-size: 16px; margin-bottom: 10px;}";
      HTML+="ul {list-style-type: disc; margin-left: 20px; margin-bottom: 15px;}, li {font-size: 14px; margin-bottom: 5px;}, table {border-collapse: collapse; width: 100%; margin-bottom: 20px;}";
      HTML+= "th, td {border: 1px solid #CCCCCC; padding: 8px; text-align: left;}, th {background-color: #F2F2F2; font-weight: bold;}, td {color: #0000FF;}</style></head>";
      HTML+="<body><h1>This is a Heading</h1><p>This is a paragraph demonstrating the conversion of HTML to Word document.</p><p>Here's an example of an unordered list:</p><ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>";
      HTML+="<p>Here's a table:</p><table><tr><th>Product</th><th>Quantity</th><th>Price</th></tr><tr><td>Jacket</td><td>30</td><td>$150</td></tr><tr><td>Sweater</td><td>25</td><td>$99</td></tr></table></body></html>";

      // Create a new document
      const doc = wasmModule.Document.Create();
      
      // Add a section to the document
      let section = doc.AddSection();

      // Add a paragraph to the section
      let paragraph = section.AddParagraph();
    
      // Append the HTML string to the paragraph
      paragraph.AppendHTML(HTML.toString('utf8',0,HTML.length));

      // Save the first page as an image stream
      let image = doc.SaveImageToStreams({pageIndex : 0, imagetype : wasmModule.ImageType.Bitmap});

      // Save the image stream as a PNG file
      image.Save(outputFileName);

      // Read the generated image from VFS
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

      // Create a Blog object from the image file
      const modifiedFile = new Blob([modifiedFileArray], {type: 'image/png'});

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

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert an HTML String to an Image Using JavaScript in React</h1>
      <button onClick={HtmlStringToImage} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

A PNG image converted from an Html string

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 1 of 2
page 1