在Word文档中设置背景图片

Setting background image on Word document

我正在阅读我在代码中处理的 Word 模板文件。

我想设置上述文档的背景图片。这是我的做法

ImagePart ip = mainPart.AddImagePart(ImagePartType.Jpeg, "ImageBackground");
Stream streamImage = ip.GetStream();

BinaryWriter bw = new BinaryWriter(streamImage);
bw.Write(imageArray);
bw.Close();

DocumentBackground docBg = new DocumentBackground() { Color = "FFFFFF" };
V.Background bg = new V.Background()
{
    Id = "_x0000_s1025",
    BlackWhiteMode = V.Office.BlackAndWhiteModeValues.White,
    TargetScreenSize = V.Office.ScreenSizeValues.Sz1024x768
};

V.Fill fill = new V.Fill()
{
    RelationshipId = "ImageBackground",
    Title = "background",
    Recolor = true,
    Type = V.FillTypeValues.Frame
};

bg.Append(fill);
docBg.Append(bg);

mainPart.Document.InsertAt(docBg, 0);

生成的 XML 与您手动设置背景时 Word 创建的内容完全匹配。

然而,当我打开生成的文件时,后台无法运行。

此外,一件奇怪的事情是,当我使用 Word 将文档导出为 HTML(一旦编辑器切换到 HTML 内容),Word 中的渲染更新和背景正在运行,但当再次打开文件时,不再处于 HTML 模式,它再次消失。

您需要将 <w:displayBackgroundShape/> 添加到 "settings.xml" 部分。
因此,请尝试使用以下内容:

var settings = mainPart.DocumentSettingsPart.Settings;
settings.DisplayBackgroundShape = new DisplayBackgroundShape();