Convert HTML to Images with JavaScript in React

Convert HTML to Images with JavaScript in React

2025-01-17 01:00:22 Written by  Administrator
Rate this item
(0 votes)

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.

Additional Info

  • tutorial_title:
Last modified on Friday, 05 June 2026 09:30