We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Replace text in Word Doc

Hi Aspose Team,

My problem is probably a minor one.

I want to replace a graphic and a text string in the header of a document.

The following code works fine, the image is replaced and the text is found and replaced. However I only want to replace the text once in the header only. The replace method as I have it replaces all occurances of the text in the whole document.

' Open document.

Dim doc As New Aspose.Words.Document("c:\downloads\Research.docx")

Dim regex As New System.Text.RegularExpressions.Regex("Research")

Dim shape As Aspose.Words.Drawing.Shape = DirectCast(doc.GetChild(Aspose.Words.NodeType.Shape, 0, True), Aspose.Words.Drawing.Shape)

If shape.HasImage Then

shape.ImageData.SetImage("C:\downloads\pic8.jpg")

End If

doc.Range.Replace(regex, "stringx")

' Save output document.

doc.Save("c:\downloads\out.doc")

Hi

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request. In this case you should loop through all headers and replace image. Please see the following code:

' Open document.

Dim doc As New Document("na22fwf1.doc")

Dim headersFooters As Node() = doc.GetChildNodes(NodeType.HeaderFooter, True).ToArray()

For Each node As HeaderFooter In headersFooters

' Get all shapes in the node if it is header.

If node.IsHeader Then

' Loop throught all shapes in header

Dim shapes As NodeCollection = node.GetChildNodes(NodeType.Shape, True)

For Each shape As Shape In shapes

If shape.HasImage Then

shape.ImageData.SetImage("C:\Temp\Test.jpg")

End If

Next

End If

Next

doc.Save("out.doc")

Best regards,

Resolved!

Thank you