Convert Word to JPG and PNG with JavaScript in React

Convert Word to JPG and PNG with JavaScript in React

2024-12-31 01:28:50 Written by  Administrator
Rate this item
(0 votes)

Convert Word to JPG and PNG with JavaScript in React

Converting Word documents to JPG or PNG formats is a practical solution for sharing visual content. This transformation preserves the layout and design, making it ideal for presentations, websites, or social media. Whether for professional or personal use, converting Word files to images simplifies accessibility and enhances visual appeal, allowing for easy integration into various digital platforms.

In this article, you will learn how to convert Word to JPG and PNG in React using Spire.Doc for JavaScript.

Install Spire.Doc for JavaScript

To get started with converting Word documents to image files 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 Word to JPG with JavaScript

Spire.Doc for JavaScript includes the Document.SaveImageToStreams() method, which enables users to convert a specific page of a Word document into an image stream. This stream can then be saved in various formats such as JPG, PNG, or BMP using the Save() method of the image stream object.

The following are the detailed steps to convert a Word document to JPG files with JavaScript in React:

  • Load required font files into the virtual file system (VFS).
  • Instantiate a new document using the new wasmModule.Document() method
  • Load the Word document using the Document.LoadFromFile() method.
  • Loop through the pages in the document:
    • Convert a specific page into image stream using the Document.SaveImageToStreams() method.
    • Save the image stream to a JPG file using the Save() method of the image stream object.
    • Read the generated image file from the VFS.
    • Create a Blob object from the image data.
    • Trigger the download of the JPG 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 convert Word to JPG
  const convertWord = 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/`);

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

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

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

      // Get the total number of pages in the document
      const totalPages = doc.GetPageCount();

      // Loop through each page and convert it to an image
      for (let pageIndex = 0; pageIndex < totalPages; pageIndex++) {

        // Convert the specific page to an image stream
        let img = doc.SaveImageToStreams({ pageIndex, type: wasmModule.ImageType.Bitmap });

        // Specify output file name based on page index
        const outputFileName = `IMG-${pageIndex}.jpg`;

        // Save the image stream to a JPG file
        img.Save(outputFileName);

        const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
        const modifiedFile = new Blob([modifiedFileArray], { type: 'image/jpeg' });

        // Create download link
        const url = URL.createObjectURL(modifiedFile);
        const a = document.createElement('a');
        a.href = url;
        a.download = outputFileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }
      // dispose 
      doc.Dispose();

    }

  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert Word to JPG in React</h1>
      <button onClick={convertWord} disabled={!wasmModule}>
        Convert
      </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.

React app runs at localhost:3000

Below is a screenshot of one of the generated JPG files:

Convert Word to JPG

Convert Word to PNG with JavaScript

The example above illustrates how to convert Word documents to JPG images. To convert to PNG, you only need to change the image format to PNG in the code.

The following are the detailed steps to convert a Word document to PNG files with JavaScript in React:

  • Load required font files into the virtual file system (VFS).
  • Instantiate a new document using the new wasmModule.Document() method
  • Load the Word document using the Document.LoadFromFile() method.
  • Loop through the pages in the document:
    • Convert a specific page into image stream using the Document.SaveImageToStreams() method.
    • Save the image stream to a PNG file using the Save() method of the image stream object.
    • Read the generated image file from the VFS.
    • Create a Blob object from the image data.
    • Trigger the download of the PNG 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 convert Word to JPG
  const convertWord = 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/`);

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

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

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

      // Get the total number of pages in the document
      const totalPages = doc.GetPageCount();

      // Loop through each page and convert it to an image
      for (let pageIndex = 0; pageIndex < totalPages; pageIndex++) {

        // Convert the specific page to an image stream
        let img = doc.SaveImageToStreams({ pageIndex, type: wasmModule.ImageType.Bitmap });

        // Specify output file name based on page index
        const outputFileName = `IMG-${pageIndex}.png`;

        // Save the image stream to a JPG file
        img.Save(outputFileName);

        const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
        const modifiedFile = new Blob([modifiedFileArray], { type: 'image/png' });

        // Create download link
        const url = URL.createObjectURL(modifiedFile);
        const a = document.createElement('a');
        a.href = url;
        a.download = outputFileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }
      // dispose 
      doc.Dispose();

    }

  };

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

export default App;

Convert Word to PNG

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 08:55