Seamless 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.