Open XML - How to add a watermark to a docx document

remove the line

doc.MainDocumentPart.DeleteParts(doc.MainDocumentPart.HeaderParts);

AND replace the check for sectionproperties with something similar to

if (doc.MainDocumentPart.Document.Body.Elements<SectionProperties>().Count == 0)

EDIT:

the complete if then.. would look like this:

var sectionProps = null;

if (doc.MainDocumentPart.Document.Body.Elements<SectionProperties>().Count == 0)
{
sectionProps = new SectionProperties();
doc.MainDocumentPart.Document.Body.Append(sectionProps);
}
else
{
sectionProps = doc.MainDocumentPart.Document.Body.Elements<SectionProperties>().Last();
}

This is now resolved by changing the way the file is opened up. When we change the Main function to:

static void Main(string[] args)
{
    //var doc = WordprocessingDocument.Open(@"C:\Users\loggedinuser\Desktop\TestDoc.docx", true);
    //AddWatermark(doc);
    //doc.MainDocumentPart.Document.Save();
    byte[] sourceBytes = File.ReadAllBytes(@"C:\Users\loggedinuser\Desktop\TestDoc.docx");
    MemoryStream inMemoryStream = new MemoryStream();
    inMemoryStream.Write(sourceBytes, 0, (int)sourceBytes.Length);

    var doc = WordprocessingDocument.Open(inMemoryStream, true);
    AddWatermark(doc);
    doc.MainDocumentPart.Document.Save();

    doc.Close();
    doc.Dispose();
    doc = null;

    using (FileStream fileStream = new FileStream(@"C:\Users\loggedinuser\Desktop\TestDoc.docx", System.IO.FileMode.Create))
    {
        inMemoryStream.WriteTo(fileStream);
    }

    inMemoryStream.Close();
    inMemoryStream.Dispose();
    inMemoryStream = null;
}

The document now correctly opens in word. Thanks to Brad B. a coworker at Sonoma Partners for finding this!

Tags:

C#

.Net

Openxml