By some libraries like http://poi.apache.org , we could create word document with any text color, but for background or highlight of the te
We Only need to add these 3 lines to set the background color for Word documents by XWPF. We have to set these lines after declaring XWPFRun and it's text color:
CTShd cTShd = run.getCTR().addNewRPr().addNewShd();
cTShd.setVal(STShd.CLEAR);
cTShd.setFill(hex_background_color);
Update: XWPF is the newest way to create word document files, but setting background only possible by HWPF which is for old format version (.doc)
For *.doc (i.e. POI's HWPF component):
Highlighting of text: Look into setHighlighted()
Background color:
I suppose you mean the background of a paragraph (AFAIK, Word also allows to color the entire page which is a different matter)
There is setShading() which allows you to provide a foreground and background color (through setCvFore()
and setCvBack()
of SHDAbstractType
) for a Paragraph. IIRC, it is the foreground that you would want to set in order to color your Paragraph. The background is only relevant for shadings which are composed of two (alternating) colors.
The underlying data structure is named Shd80
([MS-DOC], 2.9.248). There is also SHDOperand
([MS-DOC], 2.9.249) that reflects the functionality of Word prior to Word97. [MS-DOC] is the Binary Word File format specification which is freely available on MSDN.
Edit:
Here is some code to illustrate the above:
try {
HWPFDocument document = [...]; // comes from somewhere
Range range = document.getRange();
// Background shading of a paragraph
ParagraphProperties pprops = new ParagraphProperties();
ShadingDescriptor shd = new ShadingDescriptor();
shd.setCvFore(Colorref.valueOfIco(0x07)); // yellow; ICO
shd.setIpat(0x0001); // solid background; IPAT
pprops.setShading(shd);
Paragraph p1 = range.insertBefore(pprops, StyleSheet.NIL_STYLE);
p1.insertBefore("shaded paragraph");
// Highlighting of individual characters
Paragraph p2 = range.insertBefore(new ParagraphProperties(), StyleSheet.NIL_STYLE);
CharacterRun cr = p2.insertBefore("highlighted text\r");
cr.setHighlighted((byte) 0x06); // red; ICO
document.write([...]); // document goes to somewhere
} catch (IOException e) {
e.printStackTrace();
}