Knowledgebase (2613)
Children categories
Fonts play a crucial role in defining the visual appeal and readability of Word documents, influencing everything from professional reports to creative projects. Whether you're looking to refresh the design of your document by replacing outdated fonts or troubleshooting missing fonts that disrupt formatting, understanding how to retrieve and replace fonts in Microsoft Word is an essential skill.
In this article, you will learn how to get and replace fonts in a Word document using C# and Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Get Fonts Used in a Word Document in C#
To extract font information from a Word document, you must traverse its sections and paragraphs, examining each child object within the paragraphs. If a child object is identified as a TextRange, you can retrieve the font details—such as the font name, size, and color—using the properties of the TextRange class.
The following are the steps to get fonts used in a Word document in C#:
- Create a Document object.
- Load a Word document using the Document.LoadFromFile() method.
- Iterate through each section, paragraph, and child object.
- For each child object, check if it is an instance of TextRange class.
- If it is, retrieve the font name and size using the TextRange.CharacterFormat.FontName and TextRange.CharacterFormat.FontSize properties.
- Write the font information in a text file.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace RetrieveFonts
{
// Customize a FontInfo class to help store font information
class FontInfo
{
public string Name { get; set; }
public float? Size { get; set; }
public FontInfo()
{
Name = "";
Size = null;
}
public override bool Equals(object obj)
{
if (this == obj) return true;
if (!(obj is FontInfo other)) return false;
return Name.Equals(other.Name) && Size.Equals(other.Size);
}
public override int GetHashCode()
{
return HashCode.Combine(Name, Size);
}
}
class Program
{
// Function to write string to a txt file
static void WriteAllText(string filename, List<string> text)
{
try
{
using (StreamWriter writer = new StreamWriter(filename))
{
foreach (var line in text)
{
writer.WriteLine(line);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static void Main(string[] args)
{
List<FontInfo> fontInfos = new List<FontInfo>();
List<string> fontInformations = new List<string>();
// Create a Document instance
Document document = new Document();
// Load a Word document
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");
// Iterate through the sections
foreach (Section section in document.Sections)
{
// Iterate through the paragraphs
foreach (Paragraph paragraph in section.Body.Paragraphs)
{
// Iterate through the child objects
foreach (DocumentObject obj in paragraph.ChildObjects)
{
if (obj is TextRange txtRange)
{
// Get the font name, size and text color
string fontName = txtRange.CharacterFormat.FontName;
float fontSize = txtRange.CharacterFormat.FontSize;
string textColor = txtRange.CharacterFormat.TextColor.ToString();
// Store the font information
FontInfo fontInfo = new FontInfo { Name = fontName, Size = fontSize };
if (!fontInfos.Contains(fontInfo))
{
fontInfos.Add(fontInfo);
string str = $"Font Name: {fontInfo.Name}, Size: {fontInfo.Size:F2}, Color: {textColor}";
fontInformations.Add(str);
}
}
}
}
}
// Write font information to a txt file
WriteAllText("GetFonts.txt", fontInformations);
// Dispose resources
document.Dispose();
}
}
}

Replace a Specific Font in a Word Document in C#
After retrieving the font name from a specific TextRange, you can easily replace it with a new font using the TextRange.CharacterFormat.FontName property. Additionally, you can modify the font size and text color by accessing the corresponding properties in the TextRange class. This allows for comprehensive customization of the text formatting within the document.
The following are the steps to replace a specific font in a Word document in C#:
- Create a Document object.
- Load a Word document using the Document.LoadFromFile() method.
- Iterate through each section and its paragraphs.
- For each paragraph, check each child object to see if it is an instance of the TextRange class.
- If it is a TextRange, retrieve the font name using the TextRange.CharacterFormat.FontName property.
- Compare the font name to the specified font.
- If they match, set a new font name using the TextRange.CharacterFormat.FontName property.
- Save the modified document to a new Word file using the Document.SaveToFile() method.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace ReplaceFont
{
class Program
{
static void Main(string[] args)
{
// Create a Document instance
Document document = new Document();
// Load a Word document
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");
// Iterate through the sections
foreach (Section section in document.Sections)
{
// Iterate through the paragraphs
foreach (Paragraph paragraph in section.Body.Paragraphs)
{
// Iterate through the child objects
foreach (DocumentObject obj in paragraph.ChildObjects)
{
// Determine if a child object is a TextRange
if (obj is TextRange txtRange)
{
// Get the font name
string fontName = txtRange.CharacterFormat.FontName;
// Determine if the font name is Calibri
if (fontName.Equals("Calibri", StringComparison.OrdinalIgnoreCase))
{
// Replace the font with another font
txtRange.CharacterFormat.FontName = "Segoe Print";
}
}
}
}
}
// Save the document to a different file
document.SaveToFile("ReplaceFont.docx", FileFormat.Docx);
// Dispose resources
document.Dispose();
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Extract Text from PDF Documents with JavaScript in React
2025-03-07 06:52:13 Written by AdministratorExtracting text from PDF documents directly within a React application using JavaScript provides a streamlined, self-contained solution for handling dynamic content. Given that PDFs remain a ubiquitous format for reports, forms, and data sharing, parsing their contents on the client side enables developers to build efficient applications without relying on external services. By integrating Spire.PDF for JavaScript into React, development teams gain full control over data processing, reduce latency by eliminating server-side dependencies, and deliver real-time user experiences—all while ensuring that sensitive information remains secure within the browser.
In this article, we explore how to use Spire.PDF for JavaScript to extract text from PDF documents in React applications, simplifying the integration of robust PDF content extraction features.
- General Steps for Extracting PDF Text Using JavaScript
- Extract PDF Text with Layout Preservation
- Extract PDF Text without Layout Preservation
- Extract PDF Text from Specific Page Areas
- Extract Highlighted Text from PDF
Install Spire.PDF for JavaScript
To get started with extracting text from PDF documents with JavaScript in a React application, you can either download Spire.PDF for JavaScript from our website or install it via npm with the following command:
npm i spire.office
The downloaded product package integrates Spire.Doc for JavaScript, Spire.XLS for JavaScript, Spire.PDF for JavaScript, and Spire.Presentation for JavaScript. To use Spire.PDF for JavaScript functionality, you need to copy the corresponding files (spire.pdf.js, Spire.Pdf.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and the _framework folder) to the public folder of your project. Additionally, to ensure proper text rendering, font files can be added to a custom path of your choice. In the following example, the font addition path is: public\static\font.
For more details, refer to the documentation: How to Integrate Spire.PDF for JavaScript in a React Project
General Steps for Extracting PDF Text Using JavaScript
Spire.PDF for JavaScript provides a WebAssembly module that enables PDF document processing using simple JavaScript code in React applications. Developers can utilize the PdfTextExtractor class to handle text extraction tasks efficiently. The general steps for extracting text from PDF documents using Spire.PDF for JavaScript in React are as follows:
- Load the Spire.Pdf.Base.js file to initialize the WebAssembly module.
- Fetch the PDF files into the Virtual File System (VFS) using the window.spire.FetchFileToVFS() method.
- Create an instance of the PdfDocument class using the wasmModule.PdfDocument() method.
- Load the PDF document from the VFS into the PdfDocument instance using the PdfDocument.LoadFromFile() method.
- Create an instance of the PdfTextExtractOptions class using the wasmModule.PdfTextExtractOptions() method and configure the text extraction options.
- Retrieve a PDF page using the PdfDocument.Pages.get_Item() method or iterate through the document's pages.
- Create an instance of the PdfTextExtractor class with the page object using the wasmModule.PdfTextExtractor() method.
- Extract text from the page using the PdfTextExtractor.ExtractText() method.
- Download the extracted text or process it as needed.
The PdfTextExtractOptions class allows customization of extraction settings, supporting features such as simple extraction, extracting specific page areas, and retrieving hidden text. The following table outlines the properties of the PdfTextExtractOptions class and their functions:
| Property | Description |
| IsSimpleExtraction | Specifies whether to perform simple text extraction. |
| IsExtractAllText | Specifies whether to extract all text. |
| ExtractArea | Defines the extraction area. |
| IsShowHiddenText | Specifies whether to extract hidden text. |
Extract PDF Text with Layout Preservation
Using the PdfTextExtractor.ExtractText() method with default options enables text extraction while preserving the original text layout of the PDF pages. Below is a code example and the corresponding extraction result:
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
const [wasmModule, setWasmModule] = useState(null);
useEffect(() => {
(async () => {
try {
const publicUrl = process.env.PUBLIC_URL || '';
const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.pdf.js`);
const rawModule = spireModule.default || spireModule;
window.wasmModule = typeof rawModule === 'function'
? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
: rawModule;
setWasmModule(window.wasmModule);
} catch (error) {
console.error('Failed to load spire.pdf.js:', error);
}
})();
}, []);
const ExtractPDFText = async () => {
const wasmModule = window.wasmModule.spirepdf;
if (wasmModule) {
// Load the input PDF file into the VFS
const inputFileName = 'Sample.pdf';
const outputFileName = 'PDFTextWithLayout.txt';
await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}static/data/`);
let pdf = new wasmModule.PdfDocument();
pdf.LoadFromFile(inputFileName);
// Create a string object to store the extracted text
let text = '';
// Create an instance of the PdfTextExtractOptions class
const extractOptions =new wasmModule.PdfTextExtractOptions();
// Iterate through each page of the PDF document
for (let i = 0; i < pdf.Pages.Count; i++) {
// Get the current page
const page = pdf.Pages.get_Item(i);
// Create an instance of the PdfTextExtractor class
const textExtractor =new wasmModule.PdfTextExtractor(page);
// Extract the text from the current page and add it to the text string
text += textExtractor.ExtractText(extractOptions);
}
// Create a Blob object from the text string and download it
const blob = new Blob([text], { 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>Extract Text from PDF Using JavaScript in React</h1>
<button onClick={ExtractPDFText}>
Extract and Download
</button>
</div>
);
}
export default App;

Extract PDF Text without Layout Preservation
Setting the PdfTextExtractOptions.IsSimpleExtraction property to true enables a simple text extraction strategy, allowing text extraction from PDF pages without preserving the layout. In this approach, blank spaces are not retained. Instead, the program tracks the Y position of each text string and inserts line breaks whenever the Y position changes.
Below is a code example demonstrating text extraction without layout preservation using Spire.PDF for JavaScript, along with the extraction result:
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
const [wasmModule, setWasmModule] = useState(null);
useEffect(() => {
(async () => {
try {
const publicUrl = process.env.PUBLIC_URL || '';
const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.pdf.js`);
const rawModule = spireModule.default || spireModule;
window.wasmModule = typeof rawModule === 'function'
? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
: rawModule;
setWasmModule(window.wasmModule);
} catch (error) {
console.error('Failed to load spire.pdf.js:', error);
}
})();
}, []);
const ExtractPDFText = async () => {
const wasmModule = window.wasmModule.spirepdf;
if (wasmModule) {
// Load the input PDF file into the VFS
const inputFileName = 'Sample.pdf';
const outputFileName = 'PDFTextWithoutLayout.txt';
await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}static/data/`);
let pdf = new wasmModule.PdfDocument();
pdf.LoadFromFile(inputFileName);
// Create a string object to store the extracted text
let text = '';
// Create an instance of the PdfTextExtractOptions class
const extractOptions =new wasmModule.PdfTextExtractOptions();
// Enable simple text extraction to extract text without preserving layout
extractOptions.IsSimpleExtraction = true;
// Iterate through each page of the PDF document
for (let i = 0; i < pdf.Pages.Count; i++) {
// Get the current page
const page = pdf.Pages.get_Item(i);
// Create an instance of the PdfTextExtractor class
const textExtractor =new wasmModule.PdfTextExtractor(page);
// Extract the text from the current page and add it to the text string
text += textExtractor.ExtractText(extractOptions);
}
// Create a Blob object from the text string and download it
const blob = new Blob([text], { 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>Extract Text from PDF Without Layout Preservation Using JavaScript in React</h1>
<button onClick={ExtractPDFText} disabled={!wasmModule}>
Extract and Download
</button>
</div>
);
}
export default App;

Extract PDF Text from Specific Page Areas
The PdfTextExtractOptions.ExtractArea property allows users to define a specific area using a RectangleF object to extract only the text within that area from a PDF page. This method helps exclude unwanted fixed content from the extraction process. The following code example and extraction result illustrate this functionality:
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
const [wasmModule, setWasmModule] = useState(null);
useEffect(() => {
(async () => {
try {
const publicUrl = process.env.PUBLIC_URL || '';
const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.pdf.js`);
const rawModule = spireModule.default || spireModule;
window.wasmModule = typeof rawModule === 'function'
? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
: rawModule;
setWasmModule(window.wasmModule);
} catch (error) {
console.error('Failed to load spire.pdf.js:', error);
}
})();
}, []);
const ExtractPDFText = async () => {
const wasmModule = window.wasmModule.spirepdf;
if (wasmModule) {
// Load the input PDF file into the VFS
const inputFileName = 'Sample.pdf';
const outputFileName = 'PDFTextPageArea.txt';
await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}static/data/`);
let pdf = new wasmModule.PdfDocument();
pdf.LoadFromFile(inputFileName);
// Create a string object to store the extracted text
let text = '';
// Get a page from the PDF document
const page = pdf.Pages.get_Item(0);
// Create an instance of the PdfTextExtractOptions class
const extractOptions =new wasmModule.PdfTextExtractOptions();
// Set the page area to extract text from using a RectangleF object
extractOptions.ExtractArea =new wasmModule.RectangleF({ x: 0, y: 500, width: page.Size.Width, height: 200});
// Create an instance of the PdfTextExtractor class
const textExtractor =new wasmModule.PdfTextExtractor(page);
// Extract the text from specified area of the page
text = textExtractor.ExtractText(extractOptions);
// Create a Blob object from the text string and download it
const blob = new Blob([text], { 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>Extract Text from a PDF Page Area Using JavaScript in React</h1>
<button onClick={ExtractPDFText} disabled={!wasmModule}>
Extract and Download
</button>
</div>
);
}
export default App;

Extract Highlighted Text from PDF
Text highlighting in PDF documents is achieved using annotation features. With Spire.PDF for JavaScript, we can retrieve all annotations on a PDF page via the PdfPageBase.Annotations property. By checking whether each annotation is an instance of the PdfTextMarkupAnnotationWidget class, we can identify highlight annotations. Once identified, we can use the PdfTextExtractOptions.Bounds property to obtain the bounding rectangles of these annotations and set them as extraction areas, thereby extracting only the highlighted text.
The following code example demonstrates this process along with the extracted result:
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
const [wasmModule, setWasmModule] = useState(null);
useEffect(() => {
(async () => {
try {
const publicUrl = process.env.PUBLIC_URL || '';
const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.pdf.js`);
const rawModule = spireModule.default || spireModule;
window.wasmModule = typeof rawModule === 'function'
? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
: rawModule;
setWasmModule(window.wasmModule);
} catch (error) {
console.error('Failed to load spire.pdf.js:', error);
}
})();
}, []);
const ExtractPDFText = async () => {
const wasmModule = window.wasmModule.spirepdf;
if (wasmModule) {
// Load the input PDF file into the VFS
const inputFileName = 'Sample.pdf';
const outputFileName = 'PDFTextHighlighted.txt';
await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}static/data/`);
let pdf = new wasmModule.PdfDocument();
pdf.LoadFromFile(inputFileName);
// Create a string object to store the extracted text
let text = '';
// Iterate through each page of the PDF document
for (let i = 0; i < pdf.Pages.Count; i++) {
let page = pdf.Pages.get_Item(i);
// Iterate through each annotation on the page
for (let i = 0; i < page.Annotations.Count; i++) {
// Get the current annotation
const annotation = page.Annotations.get_Item(i)
// Check if the annotation is an instance of PdfTextMarkupAnnotation
if (annotation instanceof wasmModule.PdfTextMarkupAnnotationWidget) {
// Get the bounds of the annotation
const bounds = annotation.Bounds;
// Create an instance of PdfTextExtractOptions
const extractOptions =new wasmModule.PdfTextExtractOptions();
// Set the bounds of the highlight annotation as the extraction area
extractOptions.ExtractArea = bounds;
//
const textExtractor =new wasmModule.PdfTextExtractor(page)
// Extract the highlighted text and append it to the text string
text += textExtractor.ExtractText(extractOptions);
}
}
}
// Create a Blob object from the text string and download it
const blob = new Blob([text], { 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>Extract Highlighted Text from PDF Using JavaScript in React</h1>
<button onClick={ExtractPDFText} disabled={!wasmModule}>
Extract and Download
</button>
</div>
);
}
export default App;

Get a Free License
To fully experience the capabilities of Spire.PDF for JavaScript without any evaluation limitations, you can request a free 30-day trial license.
Add a Watermark to Word Documents with JavaScript in React
2025-03-07 01:03:22 Written by AdministratorIncorporating a watermark to Word documents is a simple yet impactful way to protect your content and assert ownership. Whether you're marking a draft as confidential or branding a business document, watermarks can convey essential information without distracting from your text.
In this article, you will learn how to add and customize watermarks in Word documents in a React application using Spire.Doc for JavaScript.
Install Spire.Doc for JavaScript
To get started with adding watermarks to 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.office
The downloaded product package integrates Spire.Doc for JavaScript, Spire.XLS for JavaScript, Spire.PDF for JavaScript, and Spire.Presentation for JavaScript. To use the features of Spire.Doc for JavaScript, you need to copy the corresponding files (spire.doc.js, Spire.Doc.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and the _framework folder) to the public folder of your project. To ensure proper text rendering, you can add relevant font files with a custom path. In the following example, the font is added to the path: public\static\font.
For more details, refer to the documentation: How to Integrate Spire.Doc for JavaScript in a React Project
Add a Text Watermark to Word in React
Spire.Doc for JavaScript provides the TextWatermark class, enabling users to create customizable text watermarks with their preferred text and font effects. Once the TextWatermark object is created, it can be applied to the entire document using the Document.Watermark property.
The steps to add a text watermark to Word in React are as follows:
- Load the necessary font file and input Word document into the virtual file system (VFS).
- Create a Document object using the new wasmModule.Document() method.
- Load the Word file using the Document.LoadFromFile() method.
- Create a TextWatermark object using the new wasmModule.TextWatermark() method.
- Customize the watermark's text, font size, font name, and color using the properties under the TextWatermark object.
- Apply the text watermark to the document using the Document.Watermark property.
- Save the document and trigger a download.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
const [wasmModule, setWasmModule] = useState(null);
// Load Spire.Doc
useEffect(() => {
(async () => {
try {
const publicUrl = process.env.PUBLIC_URL || '';
const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.doc.js`);
const rawModule = spireModule.default || spireModule;
window.wasmModule = typeof rawModule === 'function'
? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
: rawModule;
setWasmModule(window.wasmModule);
} catch (error) {
console.error('Failed to load spire.doc.js WASM module:', error);
}
})();
}, []);
// Function add a text watermark
const AddWatermark = async () => {
const wasmModule = window.wasmModule.spiredoc;
if (wasmModule) {
// Load the font files into the virtual file system (VFS)
await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
// Specify the input file name and the output file name
const outputFileName = "TextWatermark.docx";
const inputFileName = 'input.docx';
// Fetch the input file and add it to the VFS
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);
// Create an instance of the Document class
const doc = new wasmModule.Document();
// Load the Word document
doc.LoadFromFile(inputFileName);
// Create a TextWatermark instance
let txtWatermark =new wasmModule.TextWatermark();
// Set the text for the watermark
txtWatermark.Text = "Do Not Copy";
// Set the font size and name for the text
txtWatermark.FontSize = 58;
txtWatermark.FontName = "Arial"
// Set the color of the text
txtWatermark.Color = wasmModule.Color.get_Blue();
// Set the layout of the watermark to diagonal
txtWatermark.Layout = wasmModule.WatermarkLayout.Diagonal;
// Apply the text watermark to the document
doc.Watermark = txtWatermark;
// Save the document to the specified path
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
// Read the generated file from VFS
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
// Create a Blob object from the file
const blob = new Blob([fileArray], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
// Create a URL for the Blob
const url = URL.createObjectURL(blob);
// 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>Add a Text Watermark to Word in React</h1>
<button onClick={AddWatermark} disabled={!wasmModule}>
Generate
</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.

Here is a screenshot of the generated Word file that includes a text watermark:

Add an Image Watermark to Word in React
Spire.Doc for JavaScript provides the PictrueWatermark to help configure the image resource, scaling, washout effect for image watermarks in Word. Once a PictureWatermak object is created, you can apply it to an entire document using the Document.Watermark property.
Steps to add an image watermark to a Word document in React:
- Load the image file and input Word document into the virtual file system (VFS).
- Create a Document object using the new wasmModule.Document() method.
- Load the Word file using the Document.LoadFromFile() method.
- Create a PictureWatermark object using the new wasmModule.PictureWatermark() method.
- Set the image resource, scaling, and washout effect for the watermark using the methods and properties under the PictureWatermark object.
- Apply the image watermark to the document using the Document.Watermark property.
- Save the document and trigger a download.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
const [wasmModule, setWasmModule] = useState(null);
// Load Spire.Doc
useEffect(() => {
(async () => {
try {
const publicUrl = process.env.PUBLIC_URL || '';
const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.doc.js`);
const rawModule = spireModule.default || spireModule;
window.wasmModule = typeof rawModule === 'function'
? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
: rawModule;
setWasmModule(window.wasmModule);
} catch (error) {
console.error('Failed to load spire.doc.js WASM module:', error);
}
})();
}, []);
// Function add an image watermark
const AddWatermark = async () => {
const wasmModule = window.wasmModule.spiredoc;
if (wasmModule) {
// Load the font files into the virtual file system (VFS)
await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
// Specify the input file name and the output file name
const outputFileName = 'ImageWatermark.docx';
const inputFileName = 'input.docx';
const imageFileName = 'logo.png';
// Fetch the input file and add it to the VFS
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);
await window.spire.FetchFileToVFS(imageFileName, '', `${process.env.PUBLIC_URL}/static/data/`);
// Create an instance of the Document class
const doc = new wasmModule.Document();
// Load the Word document
doc.LoadFromFile(inputFileName);
// Create a new PictureWatermark instance
const pictureWatermark = new wasmModule.PictureWatermark();
// Set the picture
pictureWatermark.SetPicture(imageFileName);
// Set the scaling factor of the image
pictureWatermark.Scaling = 150;
// Disable washout effect
pictureWatermark.IsWashout = false;
// Apply the image watermark to the document
doc.Watermark = pictureWatermark;
// Save the document to the specified path
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
// Read the generated file from VFS
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
// Create a Blob object from the file
const blob = new Blob([fileArray], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
// Create a URL for the Blob
const url = URL.createObjectURL(blob);
// 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>Add an Image Watermark to Word in React</h1>
<button onClick={AddWatermark} 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.