Adding and removing a watermark

Hi there,

I’m adding a watermark to a document using the sample code provided by Aspose, with a little change: the watermark I add has a name:

Shape watermark = new Shape(wordDocument, ShapeType.TextPlainText);

// Set up the text of the watermark.
watermark.Name = "myWatermark"; // MY CHANGE
watermark.TextPath.Text = watermarkText;
watermark.TextPath.FontFamily = "Arial";
watermark.Width = 500;
watermark.Height = 100;

// Text will be directed from the bottom-left to the top-right corner.
watermark.Rotation = -45;
watermark.Fill.Color = System.Drawing.Color.LightGray;
watermark.StrokeColor = System.Drawing.Color.LightGray;

// Place the watermark in the page center.
watermark.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
watermark.RelativeVerticalPosition = RelativeVerticalPosition.Page;
watermark.WrapType = WrapType.None;
watermark.VerticalAlignment = VerticalAlignment.Center;
watermark.HorizontalAlignment = HorizontalAlignment.Center;

// Create a new paragraph and append the watermark to this paragraph.
Paragraph watermarkPara = new Paragraph(wordDocument);
watermarkPara.AppendChild(watermark);

// Insert the watermark into all headers of each document section.
foreach(Section sect in wordDocument.Sections)
{
    // There could be up to three different headers in each section, since we want
    // the watermark to appear on all pages, insert into all headers.
   InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderPrimary);
   InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderFirst);
   InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderEven);
}

I save the document and the watermark is there. Great. Later when I open the document and try to remove the watermark, I get no error, but the watermark remains there. I am trying to remove the watermark with the following code:

NodeCollection shapes = wordDocument.GetChildNodes(NodeType.Shape, true, false);
foreach(Shape sh in shapes)
{
    if ((sh.Name == "myWatermark"))
    {
        sh.Remove();
    }
}

When I add a breakpoint to the above code, I see that there is indeed a shape with the name of “myWatermark” and that the sh.Remove() code actually runs, but then I save the document, and when I open it using word, the watermark is still there…

Am I doing something wrong ?

Thanks,

Joao Maia

Hi

Thanks for your request. Please try using the following code to remove watermarks:

Document wordDocument = new Document("in.doc");
Node[] shapes = wordDocument.GetChildNodes(NodeType.Shape, true, false).ToArray();
foreach(Shape sh in shapes)
{
    if ((sh.Name == "myWatermark"))
    {
        sh.Remove();
    }
}
wordDocument.Save("out.doc");

Best regards,

It worked perfectly, thanks !

jm