Retrieving and replacing fonts in Word documents is a key aspect of document design. This process enables users to refresh their text with modern typography, improving both appearance and readability. Mastering font adjustments can enhance the overall impact of your documents, making them more engaging and accessible.
In this article, you will learn how to retrieve and replace fonts in a Word document using Spire.Doc for Java.
Install Spire.Doc for Java
First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>13.4.1</version> </dependency> </dependencies>
Retrieve Fonts Used in a Word Document
To retrieve font information from a Word document, you'll need to navigate through the document's sections, paragraphs, and their child objects. For each child object, check if it is an instance of TextRange. If a TextRange is detected, you can extract the font details, including the font name and size, using the methods under the TextRange class.
Here are the steps to retrieve font information from a Word document using Java:
- Create a Document object.
- Load the 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.getCharacterFormat().getFontName() and TextRange.getCharacterFormat().getFontSize() methods.
- Java
import com.spire.doc.*; import com.spire.doc.documents.*; import com.spire.doc.fields.TextRange; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; // Customize a FontInfo class to help store font information class FontInfo { private String name; private Float size; public FontInfo() { this.name = ""; this.size = null; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Float getSize() { return size; } public void setSize(Float size) { this.size = size; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof FontInfo)) return false; FontInfo other = (FontInfo) obj; return name.equals(other.getName()) && size.equals(other.getSize()); } } public class RetrieveFonts { // Function to write string to a txt file public static void writeAllText(String filename, List<String> text) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) { for (String s : text) { writer.write(s); } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { List<FontInfo> fontInfos = new ArrayList<>(); StringBuilder fontInformations = new StringBuilder(); // Create a Document instance Document document = new Document(); // Load a Word document document.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx"); // Iterate through the sections for (int i = 0; i < document.getSections().getCount(); i++) { Section section = document.getSections().get(i); // Iterate through the paragraphs for (int j = 0; j < section.getBody().getParagraphs().getCount(); j++) { Paragraph paragraph = section.getBody().getParagraphs().get(j); // Iterate through the child objects for (int k = 0; k < paragraph.getChildObjects().getCount(); k++) { DocumentObject obj = paragraph.getChildObjects().get(k); if (obj instanceof TextRange) { TextRange txtRange = (TextRange) obj; // Get the font name and size String fontName = txtRange.getCharacterFormat().getFontName(); Float fontSize = txtRange.getCharacterFormat().getFontSize(); String textColor = txtRange.getCharacterFormat().getTextColor().toString(); // Store the font information FontInfo fontInfo = new FontInfo(); fontInfo.setName(fontName); fontInfo.setSize(fontSize); if (!fontInfos.contains(fontInfo)) { fontInfos.add(fontInfo); String str = String.format("Font Name: %s, Size: %.2f, Color: %s%n", fontInfo.getName(), fontInfo.getSize(), textColor); fontInformations.append(str); } } } } } // Write font information to a txt file writeAllText("output/GetFonts.txt", Arrays.asList(fontInformations.toString().split("\n"))); // Dispose resources document.dispose(); } }
Replace a Specific Font with Another in Word
Once you obtain the font name of a specific text range, you can easily replace it with a different font, by using the TextRange.getCharacterFormat().setFontName() method. Additionally, you can adjust the font size and text color using the appropriate methods in the TextRange class.
Here are the steps to replace a specific font in a Word document using Java:
- Create a Document object.
- Load the 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, get the font name using the TextRange.getCharacterFormat().getFontName() method.
- Check if the font name is the specified font.
- If it is, set a new font name for the text range using the TextRange.getCharacterFormat().setFontName() method.
- Save the document to a different Word file using the Document.saveToFile() method.
- Java
import com.spire.doc.*; import com.spire.doc.documents.*; import com.spire.doc.fields.TextRange; public class ReplaceFont { public 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 for (int i = 0; i < document.getSections().getCount(); i++) { // Get a specific section Section section = document.getSections().get(i); // Iterate through the paragraphs for (int j = 0; j < section.getBody().getParagraphs().getCount(); j++) { // Get a specific paragraph Paragraph paragraph = section.getBody().getParagraphs().get(j); // Iterate through the child objects for (int k = 0; k < paragraph.getChildObjects().getCount(); k++) { // Get a specific child object DocumentObject obj = paragraph.getChildObjects().get(k); // Determine if a child object is a TextRange if (obj instanceof TextRange) { // Get a specific text range TextRange txtRange = (TextRange) obj; // Get the font name String fontName = txtRange.getCharacterFormat().getFontName(); // Determine if the font name is Microsoft JhengHei if ("Microsoft JhengHei".equals(fontName)) { // Replace the font with another font txtRange.getCharacterFormat().setFontName("Segoe Print"); } } } } } // Save the document to a different file document.saveToFile("output/ReplaceFonts.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.