Change Text Case to All Capitals in Word in Java

·

2 min read

When creating a Word document, you may sometimes need to capitalize all characters in a paragraph to emphasize the content or to draw the reader’s attention to it. In this article, you will learn how to change the case of existing text to all caps in Java using the Free Spire.Doc for Java library.

Install the Library (Two Methods)

Method 1: Download the free library and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.
Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

<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.free</artifactId>
      <version>5.2.0</version>
   </dependency>
</dependencies>

Sample Code

The following example shows how to change the case of a specified paragraph to All Caps or Small Caps using TextRange.getCharacterFormat().setAllCaps() method or TextRange.getCharacterFormat().isSmallCaps() method.

(Note*: AllCaps means to capitalize all the letters and set them to the same size, and SmallCaps means to capitalize all the letters but set the original majuscules bigger than the minuscules.)*

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;

public class changeCase {
    public static void main(String[] args) {
        // Create a new document and load from file
        Document doc = new Document();
        doc.loadFromFile("input.docx");

        TextRange textRange;
        //Get the first paragraph and set its CharacterFormat to AllCaps
        Paragraph para1 = doc.getSections().get(0).getParagraphs().get(0);
        for (Object docObj : para1.getChildObjects()) {
            DocumentObject obj=(DocumentObject)docObj;
            if ((obj instanceof TextRange)) {
                textRange = ((TextRange)(obj));
                textRange.getCharacterFormat().setAllCaps(true);
            }
        }

        //Get the third paragraph and set its CharacterFormat to IsSmallCaps
        Paragraph para2 = doc.getSections().get(0).getParagraphs().get(1);
        for (Object docObj : para2.getChildObjects()) {
            DocumentObject obj=(DocumentObject)docObj;
            if ((obj instanceof TextRange)) {
                textRange = ((TextRange)(obj));
                textRange.getCharacterFormat().isSmallCaps(true);
            }
        }

        //Save and launch the document
        doc.saveToFile("changeCase.docx", FileFormat.Docx_2013);
    }
}