vstoadd-inoffice-addinsword-2013word-addins

Removing a Watermark from the Active document in VSTO Word 2013


I am trying to remove a watermark that I have created previously in my code from the document. Here is the code which creates and applies the watermark:

 foreach (Word.Section section in document.Sections)
        {
            nShape = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Shapes.AddTextEffect(MsoPresetTextEffect.msoTextEffect1, tag, "Calibri", 10, MsoTriState.msoTrue, MsoTriState.msoFalse, 0, 0);
            nShape.Name = "securityTagWaterMark";
            nShape.Line.Visible = MsoTriState.msoFalse;
            nShape.Fill.Solid();
            nShape.Fill.ForeColor.RGB = (Int32)Word.WdColor.wdColorGray20;
            nShape.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin;
            nShape.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionMargin;
            // bottom right location
            nShape.Left = (float)Word.WdShapePosition.wdShapeRight;
            nShape.Top = (float)Word.WdShapePosition.wdShapeBottom;
            nShape.LockAspectRatio = MsoTriState.msoTrue;
        }

How can I check the document to find any shape objects or replace the text of the watermark that is already on the page. Here is what I have tried but It doesnt work:

 Word.Document currentDoc = Globals.ThisAddIn.Application.ActiveDocument;

        Word.Shapes shapeCollection = Globals.ThisAddIn.Application.ActiveDocument.Shapes;

        foreach (Word.Shape shape in shapeCollection)
        {
            if (shape.Name == "securityTagWaterMark")
            {
                shape.TextEffect.Text = newText;
            } 
        }

Solution

  • You're adding it to the header but looking for shapes in the main content. Word does not return all shapes in the Document.Shapes object. This is true for objects in the header but also for nested shapes that do exist in the document content.

    Word.Document currentDoc = Globals.ThisAddIn.Application.ActiveDocument;
    Word.Shapes shapeCollection = Globals.ThisAddIn.Application.ActiveDocument.Shapes;
    foreach (Word.Shape shape in currentDoc.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Shapes)
    {
        if (shape.Name == "securityTagWaterMark")
        {
            shape.TextEffect.Text = newText;
        } 
    }