[英]Set background color for XWPFParagraph
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.但是当你在谈论Word
段落时,我怀疑它显示了一个有边框和阴影的段落。
Following code creates a Word
document having a paragraph having having a border and a shading.以下代码创建了一个Word
文档,其中的段落具有边框和底纹。 The border settings can be achieved using methods of XWPFParagraph
.边框设置可以使用XWPFParagraph
的方法来实现。 The shading settings are not provided there until now.直到现在才提供着色设置。 So methods and classes of underlying ooxml-schemas
are needed.所以需要底层ooxml-schemas
的方法和类。
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.