Applying fonts in a Word document significantly enhances its visual appeal and readability. The choice of font can influence how the content is perceived, allowing you to convey tone and mood effectively. By selecting appropriate fonts, you can emphasize key points, guide the reader's attention, and create a cohesive and polished presentation.
In this article, you will learn how to apply fonts in a Word document in React using Spire.Doc for JavaScript.
- Apply a Font Style to a Paragraph in Word
- Apply Multiple Font Styles to a Paragraph in Word
- Apply a Private Font in a Word Document
Install Spire.Doc for JavaScript
To get started with applying fonts in Word 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
Apply a Font Style to a Paragraph in Word
Applying a font style to a paragraph in Microsoft Word is a fundamental skill that enhances the readability and overall appearance of your document.
Spire.Doc for JavaScript provides the ParagraphStyle class, enabling developers to define multiple text attributes, including font name, size, style, and color, all within a single object. After the style object is created, you can easily format a paragraph by using the Paragraph.ApplyStyle() method.
The following are the steps to apply a font style to a paragraph with JavaScript in React:
- Create a Document object using the wasmModule.Document.Create() method.
- Load the Word file using the Document.LoadFromFile() method.
- Add a paragraph to the document using the Document.LastSection.AddParagraph() method.
- Create a ParagraphStyle object, specifying the font name, font size, font style, and text color.
- Add the style to the document using the Document.Styles.Add() method.
- Apply the style to the paragraph using the Paragraph.ApplyStyle() method.
- Save the document to a different Word 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 set font
const SetFont = 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);
// Add a section
let section = doc.LastSection;
// Add a paragraph
let paragraph = section.AddParagraph();
// Append text to the paragraph
paragraph.AppendText('JavaScript is essential for modern web development, offering a rich ecosystem and '+
'a wide range of applications. Its ability to create responsive, interactive experiences '+
'makes it a favored choice among developers.');
// Create a paragraph style,specifying font name, font size, and text color
let paragraphStyle = wasmModule.ParagraphStyle.Create(doc);
paragraphStyle.Name = 'newStyle';
paragraphStyle.CharacterFormat.FontName = 'Times New Roman'
paragraphStyle.CharacterFormat.FontSize = 13;
paragraphStyle.CharacterFormat.TextColor = wasmModule.Color.get_Blue();
// Add the style to the document
doc.Styles.Add(paragraphStyle);
// Apply the style to the paragraph
paragraph.ApplyStyle(paragraphStyle.Name);
// Define the output file name
const outputFileName = 'output.docx';
// Save the document to the specified path
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013});
// Read the generated Word file
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob 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>Apply Fonts in a Word Document in React</h1>
<button onClick={SetFont} disabled={!wasmModule}>
Apply
</button>
</div>
);
}
export default App;
Run the code to launch the React app at localhost:3000. Click "Apply", 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 Word document:

Apply Multiple Font Styles to a Paragraph in Word
Applying multiple font styles to different parts of a paragraph allows you to highlight key points or sections, making your content more engaging for readers.
The Paragraph.AppendText() method returns a TextRange object, which offers simple APIs for formatting text within that range. When you call AppendText() multiple times, the paragraph's text is divided into distinct text ranges, allowing for individual styling with different fonts.
The following are the steps to apply multiple font styles to a paragraph using JavaScript in React:
- Load the font files you plan to use and the input Word file into the virtual file system (VFS).
- Create a Document object using the wasmModule.Document.Create() method.
- Load the Word file using the Document.LoadFromFile() method.
- Add a paragraph to the document using the Document.LastSection.AddParagraph() method.
- Append text to the paragraph using the Paragraph.AppendText() method, which returns a TextRange object.
- Append more text that needs to be styled differently to the paragraph and return different TextRange objects.
- Create a ParagraphStyle object with the basic font information and apply it to the paragraph.
- Change the font name, style, size and text color of the specified text range using the properties under the specific TextRange object.
- Save the document to a different Word 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 set font
const SetFont = 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);
// Add a section
let section = doc.LastSection;
// Add a paragraph
let paragraph = section.AddParagraph();
// Append text to the paragraph
let range_one = paragraph.AppendText('JavaScript is essential for ');
let range_two = paragraph.AppendText('modern web development');
let range_three = paragraph.AppendText(', offering a rich ecosystem and a wide range of applications. Its ability to create ');
let range_four = paragraph.AppendText('responsive, interactive experiences')
let range_five = paragraph.AppendText(' makes it a favored choice among developers.')
// Create a paragraph style
let paragraphStyle = wasmModule.ParagraphStyle.Create(doc);
paragraphStyle.Name = 'newStyle';
paragraphStyle.CharacterFormat.FontName = 'Times New Roman'
paragraphStyle.CharacterFormat.FontSize = 13;
paragraphStyle.CharacterFormat.TextColor = wasmModule.Color.get_Black();
// Add the style to the document
doc.Styles.Add(paragraphStyle);
// Apply the style to the paragraph
paragraph.ApplyStyle(paragraphStyle.Name);
// Change the font style of the second text range
range_two.CharacterFormat.TextColor = wasmModule.Color.get_Blue();
range_two.CharacterFormat.Bold = true;
range_two.CharacterFormat.UnderlineStyle = wasmModule.UnderlineStyle.Single;
// Change the font style of the fourth text range
range_four.CharacterFormat.TextColor = wasmModule.Color.get_Blue();
range_four.CharacterFormat.Italic = true;
// Define the output file name
const outputFileName = 'output.docx';
// Save the document to the specified path
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013});
// Read the generated Word file
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob 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>Set Fonts in a Word Document in React</h1>
<button onClick={SetFont} disabled={!wasmModule}>
Apply Multiple Fonts
</button>
</div>
);
}
export default App;

Apply a Private Font in a Word Document
Using a private font in a Word document can give your project a unique flair and reflect your personal or brand identity.
To apply a private font, use the TextRange.CharacterFormat.FontName property. To maintain a uniform look on various devices, it's advisable to embed the font within the document. You can do this by first loading the font file into the virtual file system using wasmModule.FetchFileToVFS().
Then, employ the Document.AddPrivateFont() method to include the font in the document. Additionally, activate font embedding by setting Document.EmbedFontsInFile to true, which ensures the private font is retained in the final document.
The following are the steps to apply a private font in Word using JavaScript:
- Load the font files you plan to use and the input Word file into the virtual file system (VFS).
- Create a Document object using the wasmModule.Document.Create() method.
- Load the Word file using the Document.LoadFromFile() method.
- Add a paragraph to the document using the Document.LastSection.AddParagraph() method.
- Append text to the paragraph using the Paragraph.AppendText() method, which returns a TextRange object.
- Apply the font to the paragraph using the TextRange.CharacterFormat.FontName property.
- Add the font to document using the Document.AddPrivateFont() method.
- Embed the font in the document by setting Document.EmbedFontsInFile to true.
- Save the document to a different Word 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 set font
const SetFont = async () => {
if (wasmModule) {
// Load the private font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('FreebrushScriptPLng.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);
// Add a section
let section = doc.LastSection;
// Add a paragraph
let paragraph = section.AddParagraph();
// Append text to the paragraph
let textRange = paragraph.AppendText('JavaScript is essential for modern web development, offering a rich ecosystem and '+
'a wide range of applications. Its ability to create responsive, interactive experiences '+
'makes it a favored choice among developers.');
// Apply the private font to the text range
textRange.CharacterFormat.FontName = 'Freebrush Script'
textRange.CharacterFormat.FontSize = 13;
textRange.CharacterFormat.TextColor = wasmModule.Color.get_Blue();
// Embed the private font in the document
doc.AddPrivateFont(wasmModule.PrivateFontPath.Create("Freebrush Script", "FreebrushScriptPLng.ttf"))
// Allow embedding font in document
doc.EmbedFontsInFile = true;
// Define the output file name
const outputFileName = 'output.docx';
// Save the document to the specified path
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013});
// Read the generated Word file
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob 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>Apply Fonts in a Word Document in React</h1>
<button onClick={SetFont} disabled={!wasmModule}>
Apply
</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.
