Knowledgebase (2311)
Children categories
Converting between Word and TXT formats is a skill that can greatly enhance your productivity and efficiency in handling documents. For example, converting a Word document to a plain text file can make it easier to analyze and manipulate data using other text processing tools or programming languages. Conversely, converting a text file to Word format allows you to add formatting, graphics, and other elements to enhance the presentation of the content. In this article, you will learn how to convert text files to Word format or convert Word files to text format in React using Spire.Doc for JavaScript.
Install Spire.Doc for JavaScript
To get started with the conversion between the TXT and Word formats in a React application, you can either download Spire.Doc for JavaScript from our website or install it via npm with the following command:
npm i spire.doc
After that, copy the "Spire.Doc.Base.js" and "Spire.Doc.Base.wasm" files to the public folder of your project.
For more details, refer to the documentation: How to Integrate Spire.Doc for JavaScript in a React Project
Convert Text (TXT) to Word in JavaScript
Spire.Doc for JavaScript allows you to load a TXT file and then save it to Word Doc or Docx format using the Document.SaveToFile() method. The following are the main steps.
- Create a new document using the wasmModule.Document.Create() method.
- Load a text file using the Document.LoadFromFile() method.
- Save the text file as a Word document using the Document.SaveToFile() method.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and spiredoc from the global window object
const { Module, spiredoc } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spiredoc);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to convert a text file to a Word document
const TXTtoWord = async () => {
if (wasmModule) {
// Specify the input and output file paths
const inputFileName = 'input.txt';
const outputFileName = 'TxtToWord.docx';
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName,'', `${process.env.PUBLIC_URL}/`);
// Create a new document
const doc = wasmModule.Document.Create();
// Load the text file
doc.LoadFromFile(inputFileName);
// Save the text file as a Word document
doc.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2016});
// Read the generated Word document from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog object from the Word document
const modifiedFile = new Blob([modifiedFileArray], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
doc.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert Text to Word Using JavaScript in React</h1>
<button onClick={TXTtoWord} disabled={!wasmModule}>
Convert
</button>
</div>
);
}
export default App;
Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to download the Word document converted from a TXT file:

Below is the input text file and the generated Word document:

Convert Word to Text (TXT) in JavaScript
The Document.SaveToFile() method can also be used to export a Word Doc or Docx document to a plain text file. The following are the main steps.
- Create a new document using the wasmModule.Document.Create() method.
- Load a Word document using the Document.LoadFromFile() method.
- Save the Word document in TXT format using the Document.SaveToFile({fileName: string, fileFormat: wasmModule.FileFormat.Txt}) method.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and spiredoc from the global window object
const { Module, spiredoc } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spiredoc);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to convert a Word document to a text file
const WordToTXT = async () => {
if (wasmModule) {
// Specify the input and output file paths
const inputFileName = 'Data.docx';
const outputFileName = 'WordToText.txt';
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName,'', `${process.env.PUBLIC_URL}/`);
// Create a new document
const doc = wasmModule.Document.Create();
// Load the Word document
doc.LoadFromFile(inputFileName);
// Save the Word document in TXT format
doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Txt});
// Read the generated text file from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog object from the text file
const modifiedFile = new Blob([modifiedFileArray], {type: 'text/plain'});
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
doc.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert a Word Document to Plain Text Using JavaScript in React</h1>
<button onClick={WordToTXT} disabled={!wasmModule}>
Convert
</button>
</div>
);
}
export default App;

Get a Free License
To fully experience the capabilities of Spire.Doc for JavaScript without any evaluation limitations, you can request a free 30-day trial license.
In Word documents, hyperlinks can be added to images and shapes to link to external websites, files, or specific sections within the document. However, over time, the destination URLs or file paths may change due to updates in external resources or reorganization of the document. When this happens, it’s important to update the hyperlinks to ensure they continue to point to the correct locations. For example, if a website's URL changes, an image is moved to a new folder or a linked shape needs to connect to a different page, updating the hyperlinks is crucial to keep the document functional and user-friendly.
In this article, we will introduce how to programmatically update hyperlinks for images and shapes in Word documents in C# using 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
Update Hyperlinks for Images in Word in C#
Spire.Doc for .NET offers the DocPicture.HasHyperlink property which allows you to identify if an image contains a hyperlink. Once identified, you can use the DocPicture.HRef property to seamlessly update or modify the hyperlink as needed. The detailed steps are as follows.
- Create an instance of the Document class.
- Load a Word document using the Document.LoadFromFile() method.
- Iterate through all sections in the document, all paragraphs in each section, and all objects in each paragraph.
- Check if the object is a DocPicture.
- Check if the DocPicture object has a hyperlink using the DocPicture.HasHyperlink property.
- Modify the hyperlink of the DocPicture object using the DocPicture.HRef property.
- Save the modified document using the Document.SaveToFile() method.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace UpdateHyperlinkForImage
{
internal class Program
{
static void Main(string[] args)
{
// Create a Document instance
Document doc = new Document();
// Load a Word document
doc.LoadFromFile("Sample1.docx");
// Iterate through all sections in the document
foreach (Section section in doc.Sections)
{
// Iterate through all paragraphs in the section
foreach (Paragraph paragraph in section.Paragraphs)
{
// Iterate through all objects in the paragraph
foreach (DocumentObject documentObject in paragraph.ChildObjects)
{
// Check if the object is a DocPicture (image)
if (documentObject is DocPicture)
{
DocPicture pic = documentObject as DocPicture;
// Check if the DocPicture object has a hyperlink
if (pic.HasHyperlink)
{
// Update the hyperlink (if you want to remove the hyperlink, set the value to null)
pic.HRef = "https://www.e-iceblue.com/";
}
}
}
}
}
// Save the modified document
doc.SaveToFile("UpdateImageHyperlink.docx", FileFormat.Docx2016);
doc.Close();
}
}
}

Update Hyperlinks for Shapes in Word in C#
Similarly, you can check if a shape has a hyperlink using the ShapeObject.HasHyperlink property, and update or modify the hyperlink with the ShapeObject.HRef property. The detailed steps are as follows.
- Create an instance of the Document class.
- Load a Word document using the Document.LoadFromFile() method.
- Iterate through all sections in the document, all paragraphs in each section, and all objects in each paragraph.
- Check if the object is a ShapeObject.
- Check if the ShapeObject object has a hyperlink using the ShapeObject.HasHyperlink property.
- Modify the hyperlink of the ShapeObject object using the ShapeObject.HRef property.
- Save the modified document using the Document.SaveToFile() method.
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace UpdateHyperlinkForShape
{
internal class Program
{
static void Main(string[] args)
{
// Create a Document instance
Document doc = new Document();
// Load a Word document
doc.LoadFromFile("Sample2.docx");
// Iterate through all sections in the document
foreach (Section section in doc.Sections)
{
// Iterate through all paragraphs in the section
foreach (Paragraph paragraph in section.Paragraphs)
{
// Iterate through all objects in the paragraph
foreach (DocumentObject documentObject in paragraph.ChildObjects)
{
// Check if the object is a ShapeObject
if (documentObject is ShapeObject)
{
ShapeObject shape = documentObject as ShapeObject;
// Check if the shape has a hyperlink
if (shape.HasHyperlink)
{
// Update the hyperlink (if you want to remove the hyperlink, set the value to null)
shape.HRef = "https://www.e-iceblue.com/";
}
}
}
}
}
// Save the modified document
doc.SaveToFile("UpdateShapeHyperlink.docx", FileFormat.Docx2016);
doc.Close();
}
}
}

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.
Converting HTML to images allows you to transform HTML content into static images that can be easily shared on social media, embedded in emails, or used as thumbnails in search engine results. This conversion process ensures that your content is displayed consistently across different devices and browsers, improving the overall user experience. In this article, you will learn how to convert HTML to images in React using Spire.Doc for JavaScript.
Install Spire.Doc for JavaScript
To get started with converting Word documents to PDF in a React application, you can either download Spire.Doc for JavaScript from our website or install it via npm with the following command:
npm i spire.doc
After that, copy the "Spire.Doc.Base.js" and "Spire.Doc.Base.wasm" files to the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.
For more details, refer to the documentation: How to Integrate Spire.Doc for JavaScript in a React Project
Convert an HTML File to an Image in JavaScript
Spire.Doc for JavaScript allows you to load an HTML file and convert a specific page to an image stream using the Document.SaveImageToStreams() method. The image streams can then be further saved to a desired image format such as jpg, png, bmp, gif. The following are the main steps.
- Load the font file to ensure correct text rendering.
- Create a new document using the wasmModule.Document.Create() method.
- Load the HTML file using the Document.LoadFromFile() method.
- Convert a specific page to an image stream using the Document.SaveImageToStreams() method.
- Save the image stream to a specified image format.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and spiredoc from the global window object
const { Module, spiredoc } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spiredoc);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to convert an HTML file to an image
const HtmlToImage = async () => {
if (wasmModule) {
// Load the font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('CALIBRI.ttf','/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Specify the input and output file paths
const inputFileName = 'sample1.html';
const outputFileName = 'HtmlToImage.png';
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName,'', `${process.env.PUBLIC_URL}/`);
// Create a new document
const doc = wasmModule.Document.Create();
// Load the HTML file
doc.LoadFromFile({fileName: inputFileName,fileFormat: wasmModule.FileFormat.Html,validationType: wasmModule.XHTMLValidationType.None});
// Save the first page as an image stream
let image = doc.SaveImageToStreams({pageIndex : 0, imagetype : wasmModule.ImageType.Bitmap});
// Save the image stream as a PNG file
image.Save(outputFileName);
// Read the generated image from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog object from the image file
const modifiedFile = new Blob([modifiedFileArray], {type: 'image/png'});
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
const a = document.createElement("a");
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
doc.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert an HTML File to an Image Using JavaScript in React</h1>
<button onClick={HtmlToImage} disabled={!wasmModule}>
Convert
</button>
</div>
);
}
export default App;
Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to download the image converted from an HTML file:

Below is the converted image file:

Convert an HTML String to an Image in JavaScript
To convert HTML strings to images, you'll need to first add HTML strings to the paragraphs of a Word page through the Paragraph.AppendHTML() method, and then convert the page to an image. The following are the main steps.
- Load the font file to ensure correct text rendering.
- Specify the HTML string.
- Create a new document using the wasmModule.Document.Create() method.
- Add a new section using the Document.AddSection() method.
- Add a paragraph to the section using the Section.AddParagraph() method.
- Append the HTML string to the paragraph using the Paragraph.AppendHTML() method.
- Convert a specific page to an image stream using the Document.SaveImageToStreams() method.
- Save the image stream to a specified image format.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and spiredoc from the global window object
const { Module, spiredoc } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spiredoc);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to convert an HTML string to an image
const HtmlStringToImage = async () => {
if (wasmModule) {
// Load the font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('CALIBRI.ttf','/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Specify the output file path
const outputFileName = 'HtmlStringToImage.png';
// Specify the HTML string
let HTML = "<html><head><title>HTML to Word Example</title><style>, body {font-family: 'Calibri';}, h1 {color: #FF5733; font-size: 24px; margin-bottom: 20px;}, p {color: #333333; font-size: 16px; margin-bottom: 10px;}";
HTML+="ul {list-style-type: disc; margin-left: 20px; margin-bottom: 15px;}, li {font-size: 14px; margin-bottom: 5px;}, table {border-collapse: collapse; width: 100%; margin-bottom: 20px;}";
HTML+= "th, td {border: 1px solid #CCCCCC; padding: 8px; text-align: left;}, th {background-color: #F2F2F2; font-weight: bold;}, td {color: #0000FF;}</style></head>";
HTML+="<body><h1>This is a Heading</h1><p>This is a paragraph demonstrating the conversion of HTML to Word document.</p><p>Here's an example of an unordered list:</p><ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>";
HTML+="<p>Here's a table:</p><table><tr><th>Product</th><th>Quantity</th><th>Price</th></tr><tr><td>Jacket</td><td>30</td><td>$150</td></tr><tr><td>Sweater</td><td>25</td><td>$99</td></tr></table></body></html>";
// Create a new document
const doc = wasmModule.Document.Create();
// Add a section to the document
let section = doc.AddSection();
// Add a paragraph to the section
let paragraph = section.AddParagraph();
// Append the HTML string to the paragraph
paragraph.AppendHTML(HTML.toString('utf8',0,HTML.length));
// Save the first page as an image stream
let image = doc.SaveImageToStreams({pageIndex : 0, imagetype : wasmModule.ImageType.Bitmap});
// Save the image stream as a PNG file
image.Save(outputFileName);
// Read the generated image from VFS
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog object from the image file
const modifiedFile = new Blob([modifiedFileArray], {type: 'image/png'});
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
const a = document.createElement("a");
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
doc.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert an HTML String to an Image Using JavaScript in React</h1>
<button onClick={HtmlStringToImage} disabled={!wasmModule}>
Convert
</button>
</div>
);
}
export default App;

Get a Free License
To fully experience the capabilities of Spire.Doc for JavaScript without any evaluation limitations, you can request a free 30-day trial license.