Conversion (9)
Convert Word to Markdown and Markdown to Word with JavaScript in React
2025-02-12 08:00:00 Written by KoohjiSeamless 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;

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;

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;

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;

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:

Below is the input text file and the generated 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;

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:

Below is the converted image 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;

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.
RTF files are versatile, containing text, images, and formatting information. Converting these files into PDF and HTML ensures that they are accessible and display consistently across various devices and browsers. Whether you're building a document viewer or integrating document management features into your application, mastering RTF conversion is a valuable skill.
In this article, you will learn how to convert RTF to PDF and RTF to HTML in React using Spire.Doc for JavaScript.
Install Spire.Doc for JavaScript
To get started with converting RTF to PDF and HTML 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 RTF to PDF with JavaScript
With Spire.Doc for JavaScript, converting RTF files to PDF is straightforward. Utilize the Document.LoadFromFile() method to load the RTF file, preserving its formatting. Then, save it as a PDF using the Document.SaveToFile() method. This process ensures high-quality output, making file format conversion easy and efficient.
Here are the steps to convert RTF to PDF in React using Spire.Doc for JavaScript:
- Load the font files used in the RTF document into the virtual file system (VFS).
- Create a new Document object using the wasmModule.Document.Create() method.
- Load the input RTF file using the Document.LoadFromFile() method.
- Save the document as a PDF file using the Document.SaveToFile() method.
- Generate a Blob from the PDF file, create a download link, 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 convert RTF to PDF
const convertRtfToPdf = 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.rtf';
// 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 RTF file
doc.LoadFromFile(inputFileName);
// Define the output file name
const outputFileName = "RtfToPdf.pdf";
// Save the document to the specified path
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.PDF});
// Read the generated PDF file from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the PDF file
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf'});
// 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 RTF to PDF in React</h1>
<button onClick={convertRtfToPdf} 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 the generated PDF document:

Convert RTF to HTML with JavaScript
When converting RTF to HTML, it's crucial to decide whether to embed image files and CSS stylesheets as internal resources, as these elements significantly impact the HTML file's display.
With Spire.Doc for JavaScript, you can easily configure these settings using the Document.HtmlExportOptions.CssStyleSheetType and Document.HtmlExportOptions.ImageEmbedded properties.
Here are the steps to convert RTF to HTML with embedded images and CSS stylesheets using Spire.Doc for JavaScript:
- Load the font files used in the RTF document into the virtual file system (VFS).
- Create a new Document object using the wasmModule.Document.Create() method.
- Load the input RTF file using the Document.LoadFromFile() method.
- Embed CSS stylesheet in the HTML file by setting the Document.HtmlExportOptions.CssStyleSheetType as Internal.
- Embed image files in the HTML file by setting the Document.HtmlExportOptions.ImageEmbedded to true.
- Save the document as an HTML file using the Document.SaveToFile() method.
- Generate a Blob from the PDF file, create a download link, 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 convert RTF to HTML
const convertRtfToHtml = 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.rtf';
// 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 RTF file
doc.LoadFromFile(inputFileName);
// Embed CSS file in the HTML file
doc.HtmlExportOptions.CssStyleSheetType = wasmModule.CssStyleSheetType.Internal;
// Embed images in the HTML file
doc.HtmlExportOptions.ImageEmbedded = true;
// Define the output file name
const outputFileName = "RtfToHtml.html";
// Save the document to the specified path
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Html});
// Read the generated HTML file from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the HTML file
const modifiedFile = new Blob([modifiedFileArray], { type: 'text/html'});
// 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 RTF to HTML in React</h1>
<button onClick={convertRtfToHtml} 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.
In web page development, transforming Word documents into HTML allows content creators to leverage the familiar Word document editing for crafting web-ready content. This approach not only structures the content appropriately for web delivery but also streamlines content management processes. Furthermore, by harnessing the capabilities of React, developers can execute this transformation directly within the browser on the client side, thereby simplifying the development workflow and potentially reducing load times and server costs.
This article demonstrates how to use Spire.Doc for JavaScript to convert Word documents to HTML files within React applications.
- Convert Word Documents to HTML Using JavaScript
- Convert Word to HTML with Embedded CSS and Images
- Convert Word to HTML with Customized Options
Install Spire.Doc for JavaScript
To get started with converting Word documents to HTML 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 Documents to HTML Using JavaScript
With Spire.Doc for JavaScript, you can load Word documents into the WASM environment using the Document.LoadFromFile() method and convert them to HTML files with the Document.SaveToFile() method. This approach converts Word documents into HTML format with CSS files and images separated from the main HTML file, allowing developers to easily customize the HTML page.
Follow these steps to convert a Word document to HTML format using Spire.Doc for JavaScript in React:
- Load the Spire.Doc.Base.js file to initialize the WebAssembly module.
- Load the Word file into the virtual file system using the wasmModule.FetchFileToVFS() method.
- Create a Document instance in the WASM module using the wasmModule.Document.Create() method.
- Load the Word document into the Document instance using the Document.LoadFromFile() method.
- Convert the Word document to HTML format using the Document.SaveToFile({ fileName: string, fileFormat: wasmModule.FileFormat.Html }) method.
- Pack and download the result files or take further actions as needed.
- JavaScript
import React, { useState, useEffect } from 'react';
import JSZip from 'jszip';
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 the Word document to HTML format
const WordToHTMLAndZip = async () => {
if (wasmModule) {
// Specify the input file name and the output folder name
const inputFileName = 'Sample.docx';
const outputFolderName = 'WordToHTMLOutput';
// 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 });
// Save the Word document to HTML format in the output folder
doc.SaveToFile({ fileName: `${outputFolderName}/document.html`, fileFormat: wasmModule.FileFormat.Html });
// Release resources
doc.Dispose();
// Create a new JSZip object
const zip = new JSZip();
// Recursive function to add a directory and its contents to the ZIP
const addFilesToZip = (folderPath, zipFolder) => {
const items = wasmModule.FS.readdir(folderPath);
items.filter(item => item !== "." && item !== "..").forEach((item) => {
const itemPath = `${folderPath}/${item}`;
try {
// Attempt to read file data
const fileData = wasmModule.FS.readFile(itemPath);
zipFolder.file(item, fileData);
} catch (error) {
if (error.code === 'EISDIR') {
// If it's a directory, create a new folder in the ZIP and recurse into it
const zipSubFolder = zipFolder.folder(item);
addFilesToZip(itemPath, zipSubFolder);
} else {
// Handle other errors
console.error(`Error processing ${itemPath}:`, error);
}
}
});
};
// Add all files in the output folder to the ZIP
addFilesToZip(outputFolderName, zip);
// Generate and download the ZIP file
zip.generateAsync({ type: 'blob' }).then((content) => {
const url = URL.createObjectURL(content);
const a = document.createElement('a');
a.href = url;
a.download = `${outputFolderName}.zip`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
});
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert Word File to HTML and Download as ZIP Using JavaScript in React</h1>
<button onClick={WordToHTMLAndZip} disabled={!wasmModule}>
Convert and Download
</button>
</div>
);
}
export default App;

Convert Word to HTML with Embedded CSS and Images
In addition to converting Word documents to HTML with separated files, CSS and images can be embedded into a single HTML file by configuring the Document.HtmlExportOptions.CssStyleSheetType property and the Document.HtmlExportOptions.ImageEmbedded property. The steps to achieve this are as follows:
- Load the Spire.Doc.Base.js file to initialize the WebAssembly module.
- Load the Word file into the virtual file system using the wasmModule.FetchFileToVFS() method.
- Create a Document instance in the WASM module using the wasmModule.Document.Create() method.
- Load the Word document into the Document instance using the Document.LoadFromFile() method.
- Set the Document.HtmlExportOptions.CssStyleSheetType property to wasmModule.CssStyleSheetType.Internal to embed CSS styles in the resulting HTML file.
- Set the Document.HtmlExportOptions.ImageEmbedded property to true to embed images in the resulting HTML file.
- Convert the Word document to an HTML file with CSS styles and images embedded using the Document.SaveToFile({ fileName: string, fileFormat: wasmModule.FileFormat.Html }) method.
- Download the resulting HTML file or take further actions as needed.
- 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 {
const { Module, spiredoc } = window;
Module.onRuntimeInitialized = () => {
setWasmModule(spiredoc);
};
} catch (err) {
console.error('Failed to load WASM module:', err);
}
};
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`;
script.onload = loadWasm;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, []);
// Function to convert the Word document to HTML format
const WordToHTMLAndZip = async () => {
if (wasmModule) {
// Specify the input file name and the base output name
const inputFileName = 'Sample.docx';
const outputFileName = 'ConvertedDocument.html';
// 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 });
// Embed CSS file in the HTML file
doc.HtmlExportOptions.CssStyleSheetType = wasmModule.CssStyleSheetType.Internal;
// Embed images in the HTML file
doc.HtmlExportOptions.ImageEmbedded = true;
// Save the Word document to HTML format
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Html });
// Release resources
doc.Dispose();
// Read the HTML file from the VFS
const htmlFileArray = wasmModule.FS.readFile(outputFileName);
// Generate a Blob from the HTML file array and trigger download
const blob = new Blob([new Uint8Array(htmlFileArray)], { type: 'text/html' });
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 HTML Using JavaScript in React</h1>
<button onClick={WordToHTMLAndZip} disabled={!wasmModule}>
Convert and Download
</button>
</div>
);
}
export default App;

Convert Word to HTML with Customized Options
Spire.Doc for JavaScript also supports customizing many other HTML export options, such as CSS file name, header and footer, form field, etc., through the Document.HtmlExportOptions property. The table below lists the properties available under Document.HtmlExportOptions, which can be used to tailor the Word-to-HTML conversion:
| Property | Description |
| CssStyleSheetType | Specifies the type of the HTML CSS style sheet (External or Internal). |
| CssStyleSheetFileName | Specifies the name of the HTML CSS style sheet file. |
| ImageEmbedded | Specifies whether to embed images in the HTML code using the Data URI scheme. |
| ImagesPath | Specifies the folder for images in the exported HTML. |
| UseSaveFileRelativePath | Specifies whether the image file path is relative to the HTML file path. |
| HasHeadersFooters | Specifies whether headers and footers should be included in the exported HTML. |
| IsTextInputFormFieldAsText | Specifies whether text-input form fields should be exported as text in HTML. |
| IsExportDocumentStyles | Specifies whether to export document styles to the HTML <head>. |
Follow these steps to customize options when converting Word documents to HTML format:
- Load the Spire.Doc.Base.js file to initialize the WebAssembly module.
- Load the Word file into the virtual file system using the wasmModule.FetchFileToVFS() method.
- Create a Document instance in the WASM module using the wasmModule.Document.Create() method.
- Load the Word document into the Document instance using the Document.LoadFromFile() method.
- Customize the conversion options through properties under Document.HtmlExportOptions.
- Convert the Word document to HTML format using the Document.SaveToFile({ fileName: string, fileFormat: wasmModule.FileFormat.Html }) method.
- Pack and download the result files or take further actions as needed.
- JavaScript
import React, { useState, useEffect } from 'react';
import JSZip from 'jszip';
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 the Word document to HTML format
const WordToHTMLAndZip = async () => {
if (wasmModule) {
// Specify the input file name and the base output file name
const inputFileName = 'Sample.docx';
const baseOutputFileName = 'WordToHTML';
const outputFolderName = 'WordToHTMLOutput';
// 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 });
// Un-embed the CSS file and set its name
doc.HtmlExportOptions.CssStyleSheetType = wasmModule.CssStyleSheetType.External;
doc.HtmlExportOptions.CssStyleSheetFileName = `${baseOutputFileName}CSS.css`;
// Un-embed the image files and set their path
doc.HtmlExportOptions.ImageEmbedded = false;
doc.HtmlExportOptions.ImagesPath = `/Images`;
doc.HtmlExportOptions.UseSaveFileRelativePath = true;
// Set to ignore headers and footers
doc.HtmlExportOptions.HasHeadersFooters = false;
// Set form fields flattened as text
doc.HtmlExportOptions.IsTextInputFormFieldAsText = true;
// Set exporting document styles in the head section
doc.HtmlExportOptions.IsExportDocumentStyles = true;
// Save the Word document to HTML format
doc.SaveToFile({
fileName: `${outputFolderName}/${baseOutputFileName}.html`,
fileFormat: wasmModule.FileFormat.Html
});
// Release resources
doc.Dispose();
// Create a new JSZip object
const zip = new JSZip();
// Recursive function to add a directory and its contents to the ZIP
const addFilesToZip = (folderPath, zipFolder) => {
const items = wasmModule.FS.readdir(folderPath);
items.filter(item => item !== "." && item !== "..").forEach((item) => {
const itemPath = `${folderPath}/${item}`;
try {
// Attempt to read file data. If it's a directory, this will throw an error.
const fileData = wasmModule.FS.readFile(itemPath);
zipFolder.file(item, fileData);
} catch (error) {
if (error.code === 'EISDIR') {
// If it's a directory, create a new folder in the ZIP and recurse into it
const zipSubFolder = zipFolder.folder(item);
addFilesToZip(itemPath, zipSubFolder);
} else {
// Handle other errors
console.error(`Error processing ${itemPath}:`, error);
}
}
});
};
// Add the contents of the output folder to the ZIP
addFilesToZip(`${outputFolderName}`, zip);
// Generate and download the ZIP file
zip.generateAsync({ type: 'blob' }).then((content) => {
const url = URL.createObjectURL(content);
const a = document.createElement("a");
a.href = url;
a.download = `${baseOutputFileName}.zip`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
});
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert Word File to HTML and Download as ZIP Using JavaScript in React</h1>
<button onClick={WordToHTMLAndZip} disabled={!wasmModule}>
Convert 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.
HTML, the backbone of web development, is widely used to build and present content on the web. While HTML is great for creating dynamic and interactive web pages, it is not well suited for creating professional-looking documents. When faced with such requirements, converting HTML to Word format is an ideal solution.
By implementing the Html to Word conversion, you can preserve the structure and content of the HTML while applying appropriate formatting and styles in Word to ensure the document look more professional. In this article, you will learn how to convert HTML to Word 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
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 an HTML File to Word with JavaScript in React
With Spire.Doc for JavaScript, you can simply load an HTML file and then save it as a Word Doc or Docx format through the Document.SaveToFile() function. The following are the main steps to convert an HTML file to Word in JavaScript.
- Load the font file to ensure correct text rendering.
- Create a new document using the wasmModule.Document.Create() function.
- Load the HTML file using the Document.LoadFromFile() function.
- Save the HTML file to a Word file using the Document.SaveToFile() function.
- 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 HTML file to Word
const HtmlToWord = 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 = 'HtmlToWord.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 HTML file
doc.LoadFromFile({fileName: inputFileName,fileFormat: wasmModule.FileFormat.Html,validationType: wasmModule.XHTMLValidationType.None});
// Save the HTML file to a Word file
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx});
// Read the generated Word file from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog 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>Convert HTML File to Word Using JavaScript in React</h1>
<button onClick={HtmlToWord} 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 file generated from an HTML file:

Below is the input HTML file and the converted Word file:

Convert an HTML String to Word with JavaScript in React
You can also convert an HTML string to Word by calling the Paragraph.AppendHTML() function to add the HTML string to a paragraph in Word and then save the Word document. The following are the main steps to convert an HTML string to a Word file in JavaScript.
- Load the font file to ensure correct text rendering.
- Specify the HTML string
- Create a new document using the wasmModule.Document.Create() function.
- Add a new section using the Document.AddSection() function.
- Add a paragraph to the section using the Section.AddParagraph() function.
- Append the HTML string to the paragraph using the Paragraph.AppendHTML() function.
- Save the Word document using the Document.SaveToFile() function.
- 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 HTML string to Word
const HtmlStringToWord = 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 = 'HtmlStringToWord.docx';
// 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 Word file
doc.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2016});
// Read the generated Word file from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog 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>Convert HTML String to Word Using JavaScript in React</h1>
<button onClick={HtmlStringToWord} 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.
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.
Converting Word documents to PDF is crucial for maintaining formatting and ensuring consistent viewing across various devices. This conversion process protects the content and layout, making PDFs a preferred choice for sharing official documents such as contracts and reports. PDFs not only preserve the original design but also enhance security, as they are less susceptible to unauthorized edits.
This article demonstrates how to convert Word documents to PDF in React using Spire.Doc for JavaScript. It covers the installation process and provides practical examples to help you configure different conversion options efficiently.
- Install Spire.Doc for JavaScript
- General Steps to Convert Word to PDF in React
- Convert Word to PDF with Installed Fonts Embedded
- Convert Word to PDF with Non-Installed Fonts Embedded
- Convert Word to Password-Protected PDF
- Convert Word to PDF with Hyperlinks Disabled
- Convert Word to PDF with Bookmarks Preserved
- Convert Word to PDF with Custom Image Quality
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
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
General Steps to Convert Word to PDF in React
Converting Word documents to PDF in React using Spire.Doc for JavaScript involves several key steps. Here's a step-by-step guide to help you get started:
- Load Fonts: Load necessary font files into the virtual file system (VFS) for accurate rendering.
- Prepare Document: Fetch the input Word file, create a new document, and load the file into it.
- Set PDF Conversion Parameters: Configure any necessary conversion options, such as embedding fonts or preserving bookmarks.
- Convert to PDF: Convert the document to PDF with the specified options.
- Download PDF: Read the generated PDF from the VFS, create a Blob object, and trigger the download for the user.
Convert Word to PDF with Installed Fonts Embedded
When converting documents, you may want to ensure that all fonts used in the Word document are embedded into the PDF. This is especially important for maintaining the document's layout.
Spire.Doc for JavaScript offer the ToPdfParameterList class to customize the conversion options. The key parameter set here is IsEmbeddedAllFonts, which guarantees that all fonts are included in the final PDF.
The following code snippet demonstrates how to embed installed fonts when converting Word to PDF using JavaScript.
- 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 PDF
const convertWordToPdf = 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 and output file paths
const inputFileName = 'input.docx';
const outputFileName = 'ToPDF.pdf';
// 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);
// Create a parameter list for the PDF conversion
let parameters = wasmModule.ToPdfParameterList.Create();
// Set the parameter to embed all fonts in the PDF
parameters.IsEmbeddedAllFonts = true;
// Save the document as a PDF file
doc.SaveToFile({fileName: outputFileName, paramList: parameters});
// Read the generated PDF file from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog object from the PDF file
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
// 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 PDF Using JavaScript in React</h1>
<button onClick={convertWordToPdf} disabled={!wasmModule}>
Generate
</button>
</div>
);
}
export default App;
Run the code, and the React app will launch at localhost:3000. Click "Generate," and a "Save As" window will appear, prompting you to save the output file in your chosen folder.

Below is a screenshot of the generated PDF document:

Convert Word to PDF with Non-Installed Fonts Embedded
For fonts that are not installed on your machine but applied in the Word document, you can also embed these fonts directly into the PDF. This ensures that the document looks consistent across different devices.
To embed non-installed fonts, start by creating a ToPdfParameterList object to customize the conversion process. Next, define a list of custom fonts for the PDF output. Finally, assign the custom font paths to the parameters using the ToPdfParameterList.PrivateFontPaths property.
The following code snippet demonstrates how to embed non-installed fonts when converting Word to PDF using JavaScript.
- 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 PDF
const convertWordToPdf = async () => {
if (wasmModule) {
// Load the font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('FreebrushScriptPLng.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Specify the input and output file paths
const inputFileName = 'input.docx';
const outputFileName = 'ToPDF.pdf';
// 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);
// Create a parameter list for the PDF conversion
let parameters = wasmModule.ToPdfParameterList.Create();
// Define a list of custom fonts to be used in the PDF
let fonts = [wasmModule.PrivateFontPath.Create('Freebrush Script', 'FreebrushScriptPLng.ttf')];
// Assign the custom font paths to the parameters for the PDF conversion
parameters.PrivateFontPaths = fonts;
// Save the document as a PDF file
doc.SaveToFile({fileName: outputFileName, paramList: parameters});
// Read the generated PDF file from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog object from the PDF file
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
// 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 PDF Using JavaScript in React</h1>
<button onClick={convertWordToPdf} disabled={!wasmModule}>
Generate
</button>
</div>
);
}
export default App;

Convert Word to Password-Protected PDF
To enhance security, you can convert a Word document to a password-protected PDF. This feature is essential when sharing sensitive information.
Spire.Doc for JavaScript provides the ToPdfParameterList.PdfSecurity.Encrypt() method, enabling users to protect the generated PDF with an open password, a permission password, and specific document permissions.
The following code illustrates how to convert Word to password-protected PDF using JavaScript.
- 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 PDF
const convertWordToPdf = 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 and output file paths
const inputFileName = 'input.docx';
const outputFileName = 'Encrypted.pdf';
// 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);
// Create a parameter list for the PDF conversion
let parameters = wasmModule.ToPdfParameterList.Create();
// Set the parameter to encrypt the generated PDF file
parameters.PdfSecurity.Encrypt('open-psd', 'permission-psd', wasmModule.PdfPermissionsFlags.Default, wasmModule.PdfEncryptionKeySize.Key128Bit);
// Save the document as a PDF file
doc.SaveToFile({fileName: outputFileName, paramList: parameters});
// Read the generated PDF file from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog object from the PDF file
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
// 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 PDF Using JavaScript in React</h1>
<button onClick={convertWordToPdf} disabled={!wasmModule}>
Generate
</button>
</div>
);
}
export default App;

Convert Word to PDF with Hyperlinks Disabled
Disabling hyperlinks when converting a Word document to PDF enhances readability and maintains a clean, distraction-free format. This adjustment can be particularly useful for print materials, presentations, and documents requiring a focus on content without external links.
By setting the ToPdfParameterList.DisableLink property to true, you can ensure that any clickable links in the original document are rendered as plain text in the PDF output.
The following code snippet demonstrates how to disable hyperlinks when converting Word to PDF using JavaScript.
- 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 PDF
const convertWordToPdf = 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 and output file paths
const inputFileName = 'input.docx';
const outputFileName = 'DisableHyperlinks.pdf';
// 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);
// Create a parameter list for the PDF conversion
let parameters = wasmModule.ToPdfParameterList.Create();
// Set the parameter to disable hyperlinks
parameters.DisableLink = true;
// Save the document as a PDF file
doc.SaveToFile({fileName: outputFileName, paramList: parameters});
// Read the generated PDF file from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog object from the PDF file
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
// 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 PDF Using JavaScript in React</h1>
<button onClick={convertWordToPdf} disabled={!wasmModule}>
Generate
</button>
</div>
);
}
export default App;
Convert Word to PDF with Bookmarks Preserved
Preserving bookmarks when converting a Word document to PDF enhances navigation in lengthy documents, allowing readers to quickly access specific sections. This feature improves usability and the overall experience of the PDF.
To create bookmarks in the output PDF document from the existing Word bookmarks, set the ToPdfParameterList.CreateWordBookmarks property to true.
The following is an example of preserving bookmarks when converting Word to PDF using JavaScript.
- 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 PDF
const convertWordToPdf = 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 and output file paths
const inputFileName = 'input.docx';
const outputFileName = 'CreateBookmarks.pdf';
// 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);
// Create a parameter list for the PDF conversion
let parameters = wasmModule.ToPdfParameterList.Create();
// Set the parameter to create bookmarks in the PDF from existing bookmarks in Word
parameters.CreateWordBookmarks = true;
// Save the document as a PDF file
doc.SaveToFile({fileName: outputFileName, paramList: parameters});
// Read the generated PDF file from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog object from the PDF file
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
// 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 PDF Using JavaScript in React</h1>
<button onClick={convertWordToPdf} disabled={!wasmModule}>
Generate
</button>
</div>
);
}
export default App;

Convert Word to PDF with Custom Image Quality
If your Word document contains images, you may want to control the quality of these images in the PDF. This can help balance file size and quality.
Spire.Doc for JavaScript includes the Document.JPEGQuality property, which allows developers to set image compression quality on a scale from 1 to 100.
The following is an example of customizing image quality when converting Word to PDF using JavaScript.
- 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 PDF
const convertWordToPdf = 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 and output file paths
const inputFileName = 'input.docx';
const outputFileName = 'CustomImageQuality.pdf';
// 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);
// Set the output image quality to be 40% of the original image
doc.JPEGQuality = 40;
// Save the document as a PDF file
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.PDF});
// Read the generated PDF file from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog object from the PDF file
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
// 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 PDF Using JavaScript in React</h1>
<button onClick={convertWordToPdf} 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.