Nathan J
Nathan J

Reputation: 95

Setting background image on Word document

I'm reading a Word template file that I process in my code.

I want to set the background image of said document. Here's how I'm doing it

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);

The generated XML matches perfectly to what's created by Word when you set the background manually.

Yet, when I open the generated file, the background is not working.

Also, one weird thing is that when I use Word to export the document as an HTML (As soon as the editor switches to HTML content), the render updates in Word and the background is working but when opening the file again, no longer in HTML mode, it disappear again.

Upvotes: 0

Views: 843

Answers (1)

Mario Z
Mario Z

Reputation: 4381

You need to add <w:displayBackgroundShape/> to the "settings.xml" part.
So, try using the following:

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

Upvotes: 1

Related Questions