Java如何设置word文档(.doc或.docx)的背景颜色(Page Color)?

How to set background color (Page Color) for word document (.doc or .docx) in Java?

通过一些像 http://poi.apache.org 这样的库,我们可以创建具有任何文本颜色的 word 文档,但是对于 background 或突出显示文中,我没有找到任何解决方案。

手动方式的word页面颜色!:

https://support.office.com/en-us/article/Change-the-background-or-color-of-a-document-6ce0b23e-b833-4421-b8c3-b3d637e62524

这是我创建word文档的主要代码poi.apache

        // Blank Document
        @SuppressWarnings("resource")
        XWPFDocument document = new XWPFDocument();
        // Write the Document in file system
        FileOutputStream out = new FileOutputStream(new File(file_address));
        // create Paragraph
        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.RIGHT);

        XWPFRun run = paragraph.createRun();
        run.setFontFamily(font_name);
        run.setFontSize(font_size);
        // This only set text color not background!
        run.setColor(hex_color);

        for (String s : text_array) {
            run.setText(s);
            run.addCarriageReturn();
        }

        document.write(out);
        out.close();

更新:XWPF是创建word文档文件的最新方式,但是只能通过HWPF设置背景,它适用于旧格式版本(.doc)

对于*.doc(即POI的HWPF组件):

  1. 文本突出显示: 查看 setHighlighted()

  2. 背景颜色:

    我想你的意思是段落的背景(AFAIK,Word 还允许为整个页面着色,这是另一回事)

    setShading() 允许您为段落提供前景色和背景色(通过 setCvFore()SHDAbstractTypesetCvBack())。 IIRC,这是您想要设置的 foreground 以便为您的段落着色。 背景仅与由两种(交替)颜色组成的阴影相关。

    底层数据结构名为 Shd80 ([MS-DOC], 2.9.248)。还有 SHDOperand ([MS-DOC], 2.9.249) 反映了 Word97 之前的 Word 的功能。 [MS-DOC] 是二进制 Word 文件格式规范,可在 MSDN 上免费获得。

编辑:

下面是一些代码来说明上面的内容:

    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();
    }
  • ICO是颜色结构
  • IPAT 是预定义的阴影样式列表

我们只需要添加这3行就可以通过XWPF设置Word文档的背景颜色。我们必须在声明 XWPFRun 之后设置这些行及其文本颜色:

CTShd cTShd = run.getCTR().addNewRPr().addNewShd();
cTShd.setVal(STShd.CLEAR);
cTShd.setFill(hex_background_color);