Java Set background color for specified paragraph or text of a Word document

In addition to supporting adding background color to a whole Word document, Spire.Doc for Java can set background color for specified paragraph or text of a Word document. This article will demonstrate how to do it in Java programmatically.

Using the code

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

public class SetParagraphShading {
    public static void main(String[] args) {
        //Load a Word document sample
        Document document = new Document();
        document.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.docx");

        //Get a specified paragraph from the sample
        Paragraph paragaph = document.getSections().get(0).getParagraphs().get(1);
        //Set background color for the paragraph.
        paragaph.getFormat().setBackColor(Color.yellow);

        //Get specified text from the sample
        paragaph = document.getSections().get(0).getParagraphs().get(6);
        TextSelection selection = paragaph.find("Spire.Doc for Java", true, false);
        //Set background color for the text 
        TextRange range = selection.getAsOneRange();
        range.getCharacterFormat().setTextBackgroundColor(Color.pink);

        //Saving the resulting document 
        document.saveToFile("output/setParagraphShading.docx", FileFormat.Docx_2013);
    }
}

Output

Java Set background color for specified paragraph or text of a Word document