Spire.Office Knowledgebase Page 27 | E-iceblue

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:

Copy
npm i spire.office

The downloaded product package integrates Spire.Doc for JavaScript, Spire.XLS for JavaScript, Spire.PDF for JavaScript, and Spire.Presentation for JavaScript. To use the features of Spire.Doc for JavaScript, you need to copy the corresponding files (spire.doc.js, Spire.Doc.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and the _framework folder) to the public folder of your project. To ensure proper text rendering, you can add relevant font files with a custom path. In the following example, the font is added to the path: public\static\font.

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 new wasmModule.Document() 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
Copy
import React, { useState, useEffect } from 'react';

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

  // Function to convert an HTML file to an image
  const HtmlToImage = async () => {
    const wasmModule = window.wasmModule.spiredoc;

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

      // Specify the input file name 
      const inputFileName = 'sample.html';

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

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

      // 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, type: wasmModule.ImageType.Bitmap });

      // Save the image stream as a PNG file
      const outputFileName = 'HtmlToImage.png';
      image.Save(outputFileName);

      // Read the generated image from VFS
      const modifiedFileArray = window.dotnetRuntime.Module.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 new wasmModule.Document() 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
Copy
import React, { useState, useEffect } from 'react';

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

  // Function to convert an HTML string to an image
  const HtmlStringToImage = async () => {
    const wasmModule = window.wasmModule.spiredoc;

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

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

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

      // 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, type: wasmModule.ImageType.Bitmap });

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

      // Read the generated image from VFS
      const modifiedFileArray = window.dotnetRuntime.Module.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.

The seamless integration of document processing capabilities into web applications has become increasingly vital for enhancing user experience and streamlining workflows. For developers working within the React ecosystem, the ability to extract text from Word documents using JavaScript allows for the dynamic presentation of content, enabling users to easily import, edit, and interact with text data directly within a web interface. In this article, we will explore how to use Spire.Doc for JavaScript to extract text from Word documents in React applications.

Install Spire.Doc for JavaScript

To get started with extracting text from 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:

Copy
npm i spire.office

The downloaded product package integrates Spire.Doc for JavaScript, Spire.XLS for JavaScript, Spire.PDF for JavaScript, and Spire.Presentation for JavaScript. To use the features of Spire.Doc for JavaScript, you need to copy the corresponding files (spire.doc.js, Spire.Doc.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and the _framework folder) to the public folder of your project. To ensure proper text rendering, you can add relevant font files with a custom path. In the following example, the font is added to the path: public\static\font.

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

Extract All Text from a Word Document Using JavaScript

To extract the complete text content from a Word document, Spire.Doc for JavaScript offers the Document.GetText() method. This method retrieves all the text in a document and returns it as a string, enabling efficient access to the content. The implementation steps are as follows:

  • Load the spire.doc.js file to initialize the WebAssembly module.
  • Load the Word file into the virtual file system using the window.spire.FetchFileToVFS method.
  • Create a Document instance in the WebAssembly module using the new wasmModule.Document() method.
  • Load the Word document into the Document instance with the Document.LoadFromFile() method.
  • Retrieve the document's text as a string using the Document.GetText() method.
  • Process the extracted text, such as downloading it as a text file or performing additional operations.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';

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

  // Function to extract all text from a Word document
  const ExtractAllTextFromWord = async () => {
    const wasmModule = window.wasmModule.spiredoc;

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

      // Specify the input file name and the output file name
      const inputFileName = 'Sample.docx';
      const outputFileName = 'ExtractWordText.txt';

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

      // Create an instance of the Document class
      const doc = new wasmModule.Document();
      
      // Load the Word document
      doc.LoadFromFile({ fileName: inputFileName });

      // Get all text from the document
      const documentText = doc.GetText();

      // Release resources
      doc.Dispose();

      // Generate a Blob from the extracted text and trigger a download
      const blob = new Blob([documentText], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }
  };

  return (
      <div style={{ textAlign: 'center', height: '300px' }}>
        <h1>Extract All Text from Word Documents Using JavaScript in React</h1>
        <button onClick={ExtractAllTextFromWord} disabled={!wasmModule}>
          Convert and Download
        </button>
      </div>
  );
}

export default App;

Extracting All Text from a Word Document with React

Extract Text from Specific Sections or Paragraphs in a Word Document

When only specific sections or paragraphs of a Word document are needed, Spire.Doc for JavaScript offers the Section.Paragraphs.get_Item(index).Text method to extract text from individual paragraphs. The following steps outline the process:

  • Load the spire.doc.js file to initialize the WebAssembly module.
  • Use the window.spire.FetchFileToVFS method to load the Word file into the virtual file system.
  • Create a Document instance using the new wasmModule.Document() method.
  • Load the Word document into the Document instance with the Document.LoadFromFile() method.
  • Access a specific section using the Document.Sections.get_Item() method.
  • Extract text from a specific paragraph with the Section.Paragraphs.get_Item().Text property.
  • To retrieve all text within a section, iterate through the section's paragraphs and concatenate their text into a single string.
  • Process the extracted text, such as saving it to a file or performing further analysis.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';

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

  // Function to extract text from a specific part of a Word document
  const ExtractTextFromWordPart = async () => {
    const wasmModule = window.wasmModule.spiredoc;

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

      // Specify the input file name and the output file name
      const inputFileName = 'Sample.docx';
      const outputFileName = 'ExtractWordText.txt';

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

      // Create an instance of the Document class
      const doc = new wasmModule.Document();
      
      // Load the Word document
      doc.LoadFromFile({ fileName: inputFileName });

      // Get a specific section from the document
      const section = doc.Sections.get_Item(1);

      // Get the text of a specific paragraph in the section
      //const paragraphText = section.Paragraphs.get_Item(1).Text;

      // Extract all text from the section
      let sectionText = "";
      for (let i = 0; i < section.Paragraphs.Count; i++) {
        // Extract the text from the paragraphs
        const text = section.Paragraphs.get_Item(i).Text;
        sectionText += text + "\n";
      }

      // Release resources
      doc.Dispose();

      // Generate a Blob from the extracted text and trigger a download
      const blob = new Blob([sectionText], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }
  };

  return (
      <div style={{ textAlign: 'center', height: '300px' }}>
        <h1>Extract Text from a Specific Part of a Word Document Using JavaScript in React</h1>
        <button onClick={ExtractTextFromWordPart} disabled={!wasmModule}>
          Convert and Download
        </button>
      </div>
  );
}

export default App;

Extract Text of Specific Word Document Section or Paragraph

Extract Text from a Word Document Based on Paragraph Styles

When extracting text formatted with specific paragraph styles, the Paragraph.StyleName property can be utilized to identify and filter paragraphs by their styles. This approach is beneficial for structured documents with distinct headings or other styled elements. The implementation process is as follows:

  • Load the spire.doc.js file to initialize the WebAssembly module.
  • Load the Word file into the virtual file system using the window.spire.FetchFileToVFS() method.
  • Create a Document instance in the WebAssembly module with the new wasmModule.Document() method.
  • Load the Word document into the Document instance using the Document.LoadFromFile() method.
  • Define the target style name or retrieve one from the document.
  • Iterate through the document's sections and their paragraphs:
    • Use the Paragraph.StyleName property to identify each paragraph's style.
    • Compare the paragraph's style name with the target style. If they match, retrieve the paragraph's text using the Paragraph.Text property.
  • Process the retrieved text, such as saving it to a file or using it for further operations.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';

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

  // Function to extract text from a Word document based on paragraph styles
  const ExtractTextByParagraphStyle = async () => {
    const wasmModule = window.wasmModule.spiredoc;

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

      // Specify the input file name and the output file name
      const inputFileName = 'Sample.docx';
      const outputFileName = 'ExtractWordText.txt';

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

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

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

      // Define the style name or get the style name of the target paragraph style
      const styleName = 'Heading2';
      // const styleName = doc.Sections.get_Item(2).Paragraphs.get_Item(2).StyleName;

      // Array to store extracted text
      let paragraphStyleText = [];
      // Iterate through the sections in the document
      for (let sectionIndex = 0; sectionIndex < doc.Sections.Count; sectionIndex++) {
        // Get the current section
        const section = doc.Sections.get_Item(sectionIndex);
        // Iterate through the paragraphs in the section
        for (let paragraphIndex = 0; paragraphIndex < section.Paragraphs.Count; paragraphIndex++) {
          // Get the current paragraph
          const paragraph = section.Paragraphs.get_Item(paragraphIndex);
          // Get the style name of the paragraph
          const paraStyleName = paragraph.StyleName;
          // Check if the style name matches the target style
          if (paraStyleName === styleName) {
            // Extract the text from the paragraph
            const paragraphText = paragraph.Text;
            console.log(paragraphText);
            // Append the extracted text to the array
            paragraphStyleText.push(paragraphText);
          }
        }
      }

      // Release resources
      doc.Dispose();

      // Generate a Blob from the extracted text and trigger a download
      const text = paragraphStyleText.join('\n');
      const blob = new Blob([text], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Extract Text from Word Documents by Paragraph Style Using JavaScript in React</h1>
      <button onClick={ExtractTextByParagraphStyle} disabled={!wasmModule}>
        Convert and Download
      </button>
    </div>
  );
}

export default App;

Extract Text from Word Documents by Paragraph Styles 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.

Applying fonts in a Word document significantly enhances its visual appeal and readability. The choice of font can influence how the content is perceived, allowing you to convey tone and mood effectively. By selecting appropriate fonts, you can emphasize key points, guide the reader's attention, and create a cohesive and polished presentation.

In this article, you will learn how to apply fonts in a Word document in React using Spire.Doc for JavaScript.

Install Spire.Doc for JavaScript

To get started with applying fonts 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:

Copy
npm i spire.office

The downloaded product package integrates Spire.Doc for JavaScript, Spire.XLS for JavaScript, Spire.PDF for JavaScript, and Spire.Presentation for JavaScript. To use the features of Spire.Doc for JavaScript, you need to copy the corresponding files (spire.doc.js, Spire.Doc.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and the _framework folder) to the public folder of your project. To ensure proper text rendering, you can add relevant font files with a custom path. In the following example, the font is added to the path: public\static\font.

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

Apply a Font Style to a Paragraph in Word

Applying a font style to a paragraph in Microsoft Word is a fundamental skill that enhances the readability and overall appearance of your document.

Spire.Doc for JavaScript provides the ParagraphStyle class, enabling developers to define multiple text attributes, including font name, size, style, and color, all within a single object. After the style object is created, you can easily format a paragraph by using the Paragraph.ApplyStyle() method.

The following are the steps to apply a font style to a paragraph with JavaScript in React:

  • Create a Document object using the new wasmModule.Document() method.
  • Load the Word file using the Document.LoadFromFile() method.
  • Add a paragraph to the document using the Document.LastSection.AddParagraph() method.
  • Create a ParagraphStyle object, specifying the font name, font size, font style, and text color.
  • Add the style to the document using the Document.Styles.Add() method.
  • Apply the style to the paragraph using the Paragraph.ApplyStyle() method.
  • Save the document to a different Word file.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';

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

  // Function to set font
  const SetFont = async () => {
    const wasmModule = window.wasmModule.spiredoc;

    if (wasmModule) {
      // Load the font files into the virtual file system (VFS)
      await window.spire.FetchFileToVFS('times.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
      await window.spire.FetchFileToVFS('timesbd.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
      await window.spire.FetchFileToVFS('timesbi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
      await window.spire.FetchFileToVFS('timesi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Specify the input file name and the output file name
      const inputFileName = 'input.docx';
      const outputFileName = 'output.docx';

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

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

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

      // Add a section
      let section = doc.LastSection;

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

      // Append text to the paragraph
      paragraph.AppendText('JavaScript is essential for modern web development, offering a rich ecosystem and ' +
        'a wide range of applications. Its ability to create responsive, interactive experiences ' +
        'makes it a favored choice among developers.');

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

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

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


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

      // Read the generated Word file
      const modifiedFileArray = window.dotnetRuntime.Module.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);

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Apply Fonts in a Word Document in React</h1>
      <button onClick={SetFont} disabled={!wasmModule}>
        Apply
      </button>
    </div>
  );
}

export default App;

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

React app runs at localhost:3000

Below is a screenshot of the generated Word document:

Apply a font to a paragraph in Word using JavaScript

Apply Multiple Font Styles to a Paragraph in Word

Applying multiple font styles to different parts of a paragraph allows you to highlight key points or sections, making your content more engaging for readers.

The Paragraph.AppendText() method returns a TextRange object, which offers simple APIs for formatting text within that range. When you call AppendText() multiple times, the paragraph's text is divided into distinct text ranges, allowing for individual styling with different fonts.

The following are the steps to apply multiple font styles to a paragraph using JavaScript in React:

  • Load the font files you plan to use and the input Word file into the virtual file system (VFS).
  • Create a Document object using the new wasmModule.Document() method.
  • Load the Word file using the Document.LoadFromFile() method.
  • Add a paragraph to the document using the Document.LastSection.AddParagraph() method.
  • Append text to the paragraph using the Paragraph.AppendText() method, which returns a TextRange object.
  • Append more text that needs to be styled differently to the paragraph and return different TextRange objects.
  • Create a ParagraphStyle object with the basic font information and apply it to the paragraph.
  • Change the font name, style, size and text color of the specified text range using the properties under the specific TextRange object.
  • Save the document to a different Word file.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';

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

  // Function to set font
  const SetFont = async () => {
    const wasmModule = window.wasmModule.spiredoc;

    if (wasmModule) {
      // Load the font files into the virtual file system (VFS)
      await window.spire.FetchFileToVFS('times.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
      await window.spire.FetchFileToVFS('timesbd.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
      await window.spire.FetchFileToVFS('timesbi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
      await window.spire.FetchFileToVFS('timesi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Specify the input file name and the output file name
      const inputFileName = 'input.docx';
      const outputFileName = 'output.docx';

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

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

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

      // Add a section
      let section = doc.LastSection;

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

      // Append text to the paragraph
      let range_one = paragraph.AppendText('JavaScript is essential for ');
      let range_two = paragraph.AppendText('modern web development');
      let range_three = paragraph.AppendText(', offering a rich ecosystem and a wide range of applications. Its ability to create ');
      let range_four = paragraph.AppendText('responsive, interactive experiences')
      let range_five = paragraph.AppendText(' makes it a favored choice among developers.')

      // Create a paragraph style
      let paragraphStyle = new wasmModule.ParagraphStyle(doc);
      paragraphStyle.Name = 'newStyle';
      paragraphStyle.CharacterFormat.FontName = 'Times New Roman'
      paragraphStyle.CharacterFormat.FontSize = 13;
      paragraphStyle.CharacterFormat.TextColor = wasmModule.Color.get_Black();

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

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

      // Change the font style of the second text range
      range_two.CharacterFormat.TextColor = wasmModule.Color.get_Blue();
      range_two.CharacterFormat.Bold = true;
      range_two.CharacterFormat.UnderlineStyle = wasmModule.UnderlineStyle.Single;

      // Change the font style of the fourth text range
      range_four.CharacterFormat.TextColor = wasmModule.Color.get_Blue();
      range_four.CharacterFormat.Italic = true;

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

      // Read the generated Word file
      const modifiedFileArray = window.dotnetRuntime.Module.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);

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Set Fonts in a Word Document in React</h1>
      <button onClick={SetFont} disabled={!wasmModule}>
        Apply Multiple Fonts
      </button>
    </div>
  );
}

export default App;

Apply multiple fonts to a paragraph in Word using JavaScript

Apply a Private Font in a Word Document

Using a private font in a Word document can give your project a unique flair and reflect your personal or brand identity.

To apply a private font, use the TextRange.CharacterFormat.FontName property. To maintain a uniform look on various devices, it's advisable to embed the font within the document. You can do this by first loading the font file into the virtual file system using window.spire.FetchFileToVFS.

Then, employ the Document.AddPrivateFont() method to include the font in the document. Additionally, activate font embedding by setting Document.EmbedFontsInFile to true, which ensures the private font is retained in the final document.

The following are the steps to apply a private font in Word using JavaScript:

  • Load the font files you plan to use and the input Word file into the virtual file system (VFS).
  • Create a Document object using the new wasmModule.Document() method.
  • Load the Word file using the Document.LoadFromFile() method.
  • Add a paragraph to the document using the Document.LastSection.AddParagraph() method.
  • Append text to the paragraph using the Paragraph.AppendText() method, which returns a TextRange object.
  • Apply the font to the paragraph using the TextRange.CharacterFormat.FontName property.
  • Add the font to document using the Document.AddPrivateFont() method.
  • Embed the font in the document by setting Document.EmbedFontsInFile to true.
  • Save the document to a different Word file.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';

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

  // Function to set font
  const SetFont = async () => {
    const wasmModule = window.wasmModule.spiredoc;

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

      // Specify the input file name and the output file name
      const inputFileName = 'input.docx';
      const outputFileName = 'output.docx';

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

      // Create an instance of the Document class
      const doc = new wasmModule.Document();
      
      // Load the Word file
      doc.LoadFromFile(inputFileName);

      // Add a section
      let section = doc.LastSection;

      // Add a paragraph
      let paragraph = section.AddParagraph();
    
      // Append text to the paragraph
      let textRange = paragraph.AppendText('JavaScript is essential for modern web development, offering a rich ecosystem and '+ 
                          'a wide range of applications. Its ability to create responsive, interactive experiences '+
                          'makes it a favored choice among developers.');

      // Apply the private font to the text range
      textRange.CharacterFormat.FontName = 'Freebrush Script'
      textRange.CharacterFormat.FontSize = 13;
      textRange.CharacterFormat.TextColor = wasmModule.Color.get_Blue();

      // Embed the private font in the document
      doc.AddPrivateFont(new wasmModule.PrivateFontPath("Freebrush Script",  "FreebrushScriptPLng.ttf"))

      // Allow embedding font in document
      doc.EmbedFontsInFile = true;

      // Save the document to the specified path
      doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013});
 
      // Read the generated Word file
      const modifiedFileArray =window.dotnetRuntime.Module.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); 

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Apply Fonts in a Word Document in React</h1>
      <button onClick={SetFont} disabled={!wasmModule}>
        Apply
      </button>
    </div>
  );
}

export default App;

Apply a private font to a paragraph in Word using JavaScript

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 27