I want to change the background color for paragraph but I cannot find the way on how to do it. I could find only how to highlight words. I want my text to look like in
Your screenshot is not really clear. It could show multiple different things. But as you are talking about Word
paragraph, I suspect it shows a paragraph having a border and a shading.
Following code creates a Word
document having a paragraph having having a border and a shading. The border settings can be achieved using methods of XWPFParagraph
. The shading settings are not provided there until now. So methods and classes of underlying ooxml-schemas
are needed.
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
public class CreateWordParagraphBackground {
private static void setParagraphShading(XWPFParagraph paragraph, String rgb) {
if (paragraph.getCTP().getPPr() == null) paragraph.getCTP().addNewPPr();
if (paragraph.getCTP().getPPr().getShd() != null) paragraph.getCTP().getPPr().unsetShd();
paragraph.getCTP().getPPr().addNewShd();
paragraph.getCTP().getPPr().getShd().setVal(org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd.CLEAR);
paragraph.getCTP().getPPr().getShd().setColor("auto");
paragraph.getCTP().getPPr().getShd().setFill(rgb);
}
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("Folollowing paragraph with border and shading:");
paragraph = document.createParagraph();
paragraph.setBorderLeft(Borders.SINGLE);
paragraph.setBorderTop(Borders.SINGLE);
paragraph.setBorderRight(Borders.SINGLE);
paragraph.setBorderBottom(Borders.SINGLE);
setParagraphShading(paragraph, "BFBFBF");
run = paragraph.createRun();
run.setText("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, ");
run = paragraph.createRun();
run.addBreak(BreakType.TEXT_WRAPPING);
run.setText("sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.");
run.addBreak(BreakType.TEXT_WRAPPING);
paragraph = document.createParagraph();
FileOutputStream out = new FileOutputStream("CreateWordParagraphBackground.docx");
document.write(out);
out.close();
document.close();
}
}