Knowledgebase (2300)
Word documents often contain extensive text, and applying emphasis marks is an effective way to highlight key information. Whether you need to accentuate important terms or enhance text clarity with styled formatting, emphasis marks can make your content more readable and professional. Instead of manually adjusting formatting, this guide demonstrates how to use Spire.Doc for Python to efficiently apply emphasis to text in Word with Python, saving time while ensuring a polished document.
- Apply Emphasis Marks to First Matched Text
- Apply Emphasis Marks to All Matched Text
- Apply Emphasis Marks to Text with Regular Expression
Install Spire.Doc for Python
This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.Doc
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows.
Apply Emphasis Marks to First Matched Text in Word Documents
When crafting a Word document, highlighting keywords or phrases can improve readability and draw attention to important information. With Spire.Doc's CharacterFormat.EmphasisMark property, you can easily apply emphasis marks to any text, ensuring clarity and consistency.
Steps to apply emphasis marks to the first matched text in a Word document:
- Create an object of the Document class.
- Load a source Word document from files using Document.LoadFromFile() method.
- Find the text that you want to emphasize with Document.FindString() method.
- Apply emphasis marks to the text through CharacterFormat.EmphasisMark property.
- Save the updated Word document using Document.SaveToFile() method.
Below is the code example showing how to emphasize the first matching text of "AI-Generated Art" in a Word document:
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
doc.LoadFromFile("/AI-Generated Art.docx")
# Customize the text that you want to apply an emphasis mark to
matchingtext = doc.FindString("AI-Generated Art", True, True)
# Apply the emphasis mark to the matched text
matchingtext.GetAsOneRange().CharacterFormat.EmphasisMark = Emphasis.CommaAbove
# Save the document as a new one
doc.SaveToFile("/ApplyEmphasisMark_FirstMatch.docx", FileFormat.Docx2013)
doc.Close()

Apply Emphasis Marks to All Matched Text in Word Files
In the previous section, we demonstrated how to add an emphasis mark to the first matched text. Now, let's take it a step further—how can we emphasize all occurrences of a specific text? The solution is simple: use the Document.FindAllString() method to locate all matches and then apply emphasis marks using the CharacterFormat.EmphasisMark property. Below, you'll find detailed steps and code examples to guide you through the process.
Steps to apply emphasis marks to all matched text:
- Create an instance of Document class.
- Read a Word file through Document.LoadFromFile() method.
- Find all the matching text using Document.FindAllString() method.
- Loop through all occurrences and apply the emphasis effect to the text through CharacterFormat.EmphasisMark property.
- Save the modified Word document through Document.SaveToFile() method.
The following code demonstrates how to apply emphasis to all occurrences of "AI-Generated Art" while ignoring case sensitivity:
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
doc.LoadFromFile("/AI-Generated Art.docx")
# Customize the text that you want to apply an emphasis mark to
textselections = doc.FindAllString("AI-Generated Art", False, True)
# Loop through the text selections and apply the emphasis mark to the text
for textselection in textselections:
textselection.GetAsOneRange().CharacterFormat.EmphasisMark = Emphasis.CircleAbove
# Save the document as a new one
doc.SaveToFile("/ApplyEmphasisMark_AllMatch.docx", FileFormat.Docx2013)
doc.Close()

Apply Emphasis Marks to Text in Word Documents with Regular Expression
Sometimes, the text you want to highlight may vary but follow a similar structure, such as email addresses, phone numbers, dates, or patterns like two to three words followed by special symbols (#, *, etc.). The best way to identify such text is by using regular expressions. Once located, you can apply emphasis marks using the same method. Let's go through the steps!
Steps to apply emphasis marks to text using regular expressions:
- Create a Document instance.
- Load a Word document from the local storage using Document.LoadFromFile() method.
- Find text that you want to emphasize with Document.FindAllPattern() method.
- Iterate through all occurrences and apply the emphasis effect to the text through CharacterFormat.EmphasisMark property.
- Save the resulting Word file through Document.SaveToFile() method.
The code example below shows how to emphasize "AI" and the word after it in a Word document:
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
doc.LoadFromFile("/AI-Generated Art.docx")
# Match "AI" and the next word using regular expression
pattern = Regex(r"AI\s+\w+")
# Find all matching text
textSelections = doc.FindAllPattern(pattern)
# Loop through all the matched text and apply an emphasis mark
for selection in textSelections:
selection.GetAsOneRange().CharacterFormat.EmphasisMark = Emphasis.DotBelow
# Save the document as a new one
doc.SaveToFile("/ApplyEmphasisMark_Regex.docx", FileFormat.Docx2013)
doc.Close()

Get a Free License
To fully experience the capabilities of Spire.Doc for Python without any evaluation limitations, you can request a free 30-day trial license.
Adding borders to specific text and paragraphs in Word documents is an effective way to highlight key information and improve the document's structure. Whether it's important terms or entire sections, borders help them stand out. In this guide, we'll show you how to use Spire.Doc for Python to add borders to text and paragraphs in Word with Python, boosting both the readability and professionalism of your document while saving you time from manual formatting.
Install Spire.Doc for Python
This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.Doc
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows.
Add a Border to Text in Word Documents with Python
In Word documents, important information like technical terms, company names, or legal clauses can be highlighted with borders to draw readers' attention. Using Python, you can locate the required text with the Document.FindAllString() method and apply borders using the CharacterFormat.Border.BorderType property. Here's a step-by-step guide to help you do this efficiently.
Steps to add borders to all matched text in a Word document:
- Create an object of Document class.
- Read a source Word document from files using Document.LoadFromFile() method.
- Find all occurrences of the specified text through Document.FindAllString() method.
- Loop through all matched text and get the text as a text range.
- Add a border to the text with CharacterFormat.Border.BorderType property.
- Customize the color of the border through CharacterFormat.Border.Color property.
- Save the modified document with Document.SaveToFile() method.
The code example below shows how to add a border to all occurrences of "AI-Generated Art":
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
doc.LoadFromFile("/AI-Generated Art.docx")
# Set the target text
target_text = "AI-Generated Art"
# Create a TextSelection object and find all matches
text_selections = doc.FindAllString(target_text, False, True)
# Loop through the text selections
for selection in text_selections:
text_range = selection.GetAsOneRange()
# Add a border to the text
text_range.CharacterFormat.Border.BorderType = BorderStyle.Single
# Set the border color
text_range.CharacterFormat.Border.Color = Color.get_Blue()
# Save the resulting document
doc.SaveToFile("/AddBorder_Text.docx", FileFormat.Docx2013)
doc.Close()

Add a Border to Paragraphs in Word Files Using Python
Important clauses or legal statements in contracts, summaries in reports, and quotations in papers often require adding borders to paragraphs for emphasis or distinction. Unlike text borders, adding a border to a paragraph involves finding the target paragraph by its index and then using the Format.Borders.BorderType property. Let's check out the detailed instructions.
Steps to add a border to paragraphs in Word documents:
- Create a Document instance.
- Read a Word document through Document.LoadFromFile() method.
- Get the specified paragraph with Document.Sections[].Paragraphs[] property.
- Add a border to the paragraph using Format.Borders.BorderType property.
- Set the type and color of the border.
- Save the resulting Word file through Document.SaveToFile() method.
Here is an example showing how to add a border to the fourth paragraph in a Word document:
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
doc.LoadFromFile("/AI-Generated Art.docx")
# Get the fourth paragraph
paragraph = doc.Sections[0].Paragraphs[3]
# Add a border to the paragraph
borders = paragraph.Format.Borders
borders.BorderType(BorderStyle.DotDotDash)
borders.Color(Color.get_Blue())
# Save the updated document
doc.SaveToFile("/AddBorder_Paragraph.docx", FileFormat.Docx2013)
doc.Close()

Get a Free License
To fully experience the capabilities of Spire.Doc for Python without any evaluation limitations, you can request a free 30-day trial license.
PDFs are versatile documents that often contain images to enhance their visual appeal and convey information. The ability to manipulate these images - adding new ones, replacing existing ones, or removing unwanted ones - is a valuable skill. In this article, you will learn how to add, replace, or delete images in a PDF document in React using Spire.PDF for JavaScript .
- Add an Image to a PDF Document in JavaScript
- Replace an Image in a PDF Document in JavaScript
- Remove an Image from a PDF Document in JavaScript
Install Spire.PDF for JavaScript
To get started with manipulating images in PDF 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.pdf
After that, copy the "Spire.Pdf.Base.js" and "Spire.Pdf.Base.wasm" files to the public folder of your project.
For more details, refer to the documentation: How to Integrate Spire.PDF for JavaScript in a React Project
Add an Image to a PDF Document in JavaScript
Spire.PDF for JavaScript provides the PdfPage.Canvas.DrawImage() method to add an image at a specified location on a PDF page. The main steps are as follows.
- Load the input image into the Virtual File System (VFS).
- Create a PdfDocument object with the wasmModule.PdfDocument.Create() method.
- Add a page to the PDF document using the PdfDocument.Pages.Add() method.
- Load the image using the wasmModule.PdfImage.FromFile() method.
- Specify the size of the image.
- Draw the image at a specified location on the page using the PdfPageBase.Canvas.DrawImage() method.
- Save the PDF document using PdfDocument.SaveToFile() method.
- Trigger the download of the resulting document.
- 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 spirepdf from the global window object
const { Module, spirepdf } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepdf);
};
} 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.Pdf.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 add images in PDF
const AddPdfImage = async () => {
if (wasmModule) {
// Specify the input and output file paths
const inputFileName = "JS.png";
const outputFileName = "DrawImage.pdf";
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName , '', `${process.env.PUBLIC_URL}/`);
// Create a pdf instance
let pdf = wasmModule.PdfDocument.Create();
// Add a page
let page = pdf.Pages.Add();
// Load the image
let image = wasmModule.PdfImage.FromFile(inputFileName);
// Calculate the scaled width and height of the image
let width = image.Width * 0.6;
let height = image.Height * 0.6;
// Calculate the x-coordinate to center the image horizontally on the page
let x = (page.Canvas.ClientSize.Width - width) / 2;
// Draw the image at a specified location on the page
page.Canvas.DrawImage({image:image, x:x, y: 60, width: width, height: height});
// Save the result file
pdf.SaveToFile({fileName: outputFileName});
// Clean up resources
pdf.Close();
// Read the generated PDF file
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob 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);
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Add Images in PDF with JavaScript in React</h1>
<button onClick={AddPdfImage} disabled={!wasmModule}>
Process
</button>
</div>
);
}
export default App;
Run the code to launch the React app at localhost:3000. Once it's running, click the "Process" button to insert image in PDF:

Below is the result file:

Replace an Image in a PDF Document in JavaScript
To replace an image in PDF, you can load a new image and then replace the existing image with the new one through the PdfImageHelper.ReplaceImage() method. The main steps are as follows.
- Load the input file and image into the Virtual File System (VFS).
- Create a PdfDocument object with the wasmModule.PdfDocument.Create() method.
- Load a PDF document using the PdfDocument.LoadFromFile() method.
- Get a specific page through the PdfDocument.Pages.get_Item() method.
- Load an image using PdfImage.FromFile() method.
- Create a PdfImageHelper object with the wasmModule.PdfImageHelper.Create() method.
- Get the image information on the page using the PdfImageHelper.GetImagesInfo() method.
- Load the input image using the wasmModule.PdfImage.FromFile() method.
- Replace an existing image in the page with the new image using the PdfImageHelper.ReplaceImage() method.
- Save the PDF document using PdfDocument.SaveToFile() method.
- Trigger the download of the resulting document.
- 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 spirepdf from the global window object
const { Module, spirepdf } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepdf);
};
} 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.Pdf.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 replace an image in PDF
const ReplacePdfImage = async () => {
if (wasmModule) {
// Specify the input and output file paths
const inputFileName = "DrawImage.pdf";
const inputImageName = "coding1.jpg";
const outputFileName = "ReplaceImage.pdf";
// Fetch the input file and image and add them to the VFS
await wasmModule.FetchFileToVFS(inputFileName , '', `${process.env.PUBLIC_URL}/`);
await wasmModule.FetchFileToVFS(inputImageName , '', `${process.env.PUBLIC_URL}/`);
// Create a pdf instance
let pdf = wasmModule.PdfDocument.Create();
// Load the PDF file
pdf.LoadFromFile({fileName: inputFileName});
// Get the first page
let page = pdf.Pages.get_Item(0);
// Create a PdfImageHelper instance
let helper = wasmModule.PdfImageHelper.Create();
// Get the image information from the page
let images = helper.GetImagesInfo(page);
// Load a new image
let newImage = wasmModule.PdfImage.FromFile(inputImageName);
// Replace the first image on the page with the loaded image
helper.ReplaceImage(images[0], newImage);
// Save the result file
pdf.SaveToFile({fileName: outputFileName});
// Clean up resources
pdf.Close();
// Read the generated PDF file
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob 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);
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Replace an Image in PDF with JavaScript in React</h1>
<button onClick={ReplacePdfImage} disabled={!wasmModule}>
Process
</button>
</div>
);
}
export default App;

Remove an Image from a PDF Document in JavaScript
The PdfImageHelper class also provides the DeleteImage() method to remove a specific image from a PDF page. The main steps are as follows.
- Load the input file into the Virtual File System (VFS).
- Create a PdfDocument object with the wasmModule.PdfDocument.Create() method.
- Load a PDF document using the PdfDocument.LoadFromFile() method.
- Get a specific page using the PdfDocument.Pages.get_Item() method.
- Create a PdfImageHelper object with the wasmModule.PdfImageHelper.Create() method.
- Get the image information on the page using the PdfImageHelper.GetImagesInfo() method.
- Delete a specified image on the page using the PdfImageHelper.DeleteImage() method.
- Save the PDF document using PdfDocument.SaveToFile() method.
- Trigger the download of the resulting document.
- 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 spirepdf from the global window object
const { Module, spirepdf } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepdf);
};
} 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.Pdf.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 remove images in PDF
const DeletePdfImage = async () => {
if (wasmModule) {
// Specify the input and output file paths
const inputFileName = "DrawImage.pdf";
const outputFileName = "DeleteImage.pdf";
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName , '', `${process.env.PUBLIC_URL}/`);
// Create a pdf instance
let pdf = wasmModule.PdfDocument.Create();
// Load the PDF file
pdf.LoadFromFile({fileName: inputFileName});
// Get the first page
let page = pdf.Pages.get_Item(0);
// Create a PdfImageHelper instance
let helper = wasmModule.PdfImageHelper.Create();
// Get the image information from the page
let images = helper.GetImagesInfo(page);
// Delete the first image on the page
helper.DeleteImage({imageInfo: images[0]});
// Save the result file
pdf.SaveToFile({fileName: outputFileName});
// Clean up resources
pdf.Close();
// Read the generated PDF file
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob 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);
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Remove an Image from PDF with JavaScript in React</h1>
<button onClick={DeletePdfImage} disabled={!wasmModule}>
Process
</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.