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:
npm i spire.doc
Make sure to copy all the dependencies 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 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 wasmModule.Document.Create() 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
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 Word to JPG const convertWord = 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}/`); // Specify the input file path const inputFileName = 'input.docx'; // Create a new document const doc= wasmModule.Document.Create(); // Fetch the input file and add it to the VFS await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`); // 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, imagetype: 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); // Read the generated image file from VFS const modifiedFileArray = wasmModule.FS.readFile(outputFileName); // Create a Blob object from the image file const modifiedFile = new Blob([modifiedFileArray], { type: 'image/jpeg' }); // 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 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.
Below is a screenshot of one of the generated JPG files:
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 wasmModule.Document.Create() 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
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 Word to JPG const convertWord = 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}/`); // Specify the input file path const inputFileName = 'input.docx'; // Create a new document const doc= wasmModule.Document.Create(); // Fetch the input file and add it to the VFS await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`); // 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, imagetype: 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); // Read the generated image file from VFS const modifiedFileArray = wasmModule.FS.readFile(outputFileName); // Create a Blob 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 Word to PNG in React</h1> <button onClick={convertWord} disabled={!wasmModule}> Convert </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.