I’m using aspose to replace a tag (e.g. [[FileContacts]]) with an HTML table. I know I can do the DocumentBuilder etc but have no idea how to:
a) find that tag (and all identical others) in the document
b) tell DocumentBuilder to inserthtml() right there.
The MoveCursor() doesn’t help much as there is no bookmark for the tag and I don’t know which node it belongs to.
Ideally, I would want the Replace() callback to support, in its e.Replacement property, a DocumentBuilder. Is that possible? Is there any other way of doing a find and replace that is more than just a text string?
Thanks for your inquiry. You can achieve your requirements by implementing IReplacingCallback. Please use following code example to find the text and replace it with footnote. Hope this helps you.
public class FindandInsertHtml : IReplacingCallback
private String html;
public FindandInsertHtml(string htmlcontents)
html = htmlcontents;
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
// This is a Run node that contains either the beginning or the complete match.
Node currentNode = e.MatchNode;
// The first (and may be the only) run can contain text before the match,
// in this case it is necessary to split the run.
if (e.MatchOffset > 0)
currentNode = SplitRun((Run)currentNode, e.MatchOffset);
// This array is used to store all nodes of the match for further removing.
ArrayList runs = new ArrayList();
// Find all runs that contain parts of the match string.
int remainingLength = e.Match.Value.Length;
(remainingLength > 0) &&
(currentNode != null) &&
(currentNode.GetText().Length <= remainingLength))
remainingLength = remainingLength - currentNode.GetText().Length;
// Select the next Run node.
// Have to loop because there could be other nodes such as BookmarkStart etc.
currentNode = currentNode.NextSibling;
while ((currentNode != null) && (currentNode.NodeType != NodeType.Run));
// Split the last run that contains the match if there is any text left.
if ((currentNode != null) && (remainingLength > 0))
// Create Document Buidler
DocumentBuilder builder = new DocumentBuilder(e.MatchNode.Document as Document);
builder.MoveTo((Run)runs[runs.Count - 1]);
// Now remove all runs in the sequence.
foreach (Run run in runs)
// Signal to the replace engine to do nothing because we have already done all what we wanted.
private static Run SplitRun(Run run, int position)
Run afterRun = (Run)run.Clone(true);
afterRun.Text = run.Text.Substring(position);
run.Text = run.Text.Substring(0, position);
Document mainDoc = new Document(MyDir + "in.docx");
string html = "<b>Some Bold Text From HTML</b>";
mainDoc.Range.Replace(new Regex("Replace me with html"), new FindandInsertHtml(html), false);
mainDoc.Save(MyDir + "Out.docx");