React (18)
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.
Spire.Doc for JavaScript is an independent Word API that allows developers to integrate Microsoft Word document creation capabilities into their JavaScript applications, without installing Microsoft Word on either development or target systems.
It is a trustworthy MS Word API for JavaScript that can apply multiple Word document processing tasks. Spire.Doc for JavaScript supports Word 97-2003 /2007/2010/2013/2016/2019, and it has the capability of converting them to other common formats, like XML, RTF, TXT, EMF, HTML, ODT, Markdown, and vice versa. Moreover, it supports converting Word Doc/Docx to PDF, images (PNG, JPEG), PostScript, OFD, XPS, EPUB, PCL (Printer Command Language), and RTF to PDF/HTML, HTML to PDF/Image, Markdown to PDF in high quality.


