Dynamically remove Shapes in First page header and in the last page header in C# code

Hi Team,

Following sample template have shapes in first page header and double shape (signature image) at the last page of the template. At the last page any one of the shape has to be removed based on the conditions. Could you please share a code sample to remove shape dynamically in C# code. If we need to insert bookmarks also that can be done from our end. Kindly suggest a code sample to achieve this, that would be really helpful.

Note: We own the control of this template

Sample template: Sample Tempalte with Content and Signature.docx (60.2 KB)

Thanks,
Karthikeyan

@Karthik_Test_account
To remove shapes you can use the following code.

document.FirstSection.HeadersFooters[HeaderFooterType.HeaderFirst].Shapes[0].Remove();
document.LastSection.Body.Shapes[1].Remove();

Please describe in more detail what conditions you mean.

@Vadim.Saltykov

Thank you for the reply

At the last page any one of the shape has to be removed based on the conditions. - this means based on a Boolean value I have to remove first image if it’s true else have to remove the second image.

Also in the code that you send Shapes couldn’t be found and it errors in my code, any reason for this ?

document.FirstSection.HeadersFooters[HeaderFooterType.HeaderFirst].Shapes[0].Remove();
document.LastSection.Body.Shapes[1].Remove();

@Karthik_Test_account

Where is this condition located and what does it represent?

My example was given in relation to your document attached in the first post. Here is a complete sample code.

Document doc = new Document("Sample Tempalte with Content and Signature.docx");
doc.FirstSection.HeadersFooters[HeaderFooterType.HeaderFirst].Shapes[0].Remove();
doc.LastSection.Body.Shapes[1].Remove();
doc.Save("output.docx");

Are you using Aspose.Words for .Net?

@Vadim.Saltykov

Yes we are using Aspose Words for .Net. Above logic helps.

One more thing is there a way to fetch a shape with a bookmark name, cause we might have a scenario in future where there might be multiple shapes in the header so if we fetch it bookmark name then that would be really helpful. Kindly share a code sample for this one.

@Karthik_Test_account Please clarify what you mean by “fetch a shape with a bookmark name”.
You can find a Shape with a given name

foreach (Shape shape in doc.GetChildNodes(NodeType.Shape, true))
{
    if (shape.Name == "shape_target_name")
        shape.Remove();
}

Or delete the content of a predefined bookmark.

Document doc = new Document("Sample Tempalte with Content and Signature_Bmk.docx");
Node node = doc.Range.Bookmarks["MarkToDelete"].BookmarkStart.NextPreOrder(doc);
while (node != doc.Range.Bookmarks["MarkToDelete"].BookmarkEnd)
{
    Node nodeToRemove = node;
    node = node.NextPreOrder(doc);
    nodeToRemove.Remove();
}
doc.Save("out.docx");

Sample Tempalte with Content and Signature_Bmk.docx (61.0 KB)