Free Support Forum - aspose.com

Replace a string with a Table

Hi, we have Aspose version 14.8.0 installed, I am wondering if you might be able to tell me how to replace a string with a table

eg.
Let’s say I have a table:

Table tbl = builder.StartTable();

etc until the table is done. -> builder.EndTable()

And then I want to use this table to replace a string – something like this:
doc.Range.Replace(new Regex("\[Table_To_Replace\]"), tbl );

How would I do that?

Thank you very much in advance!

@AlinaS,

Thanks for your inquiry. Please refer to the following article.
Find and Replace

In your case, we suggest you following solution.

  1. Please implement IReplacingCallback interface.
  2. In IReplacingCallback.Replacing method, move the cursor to the matched node. You can get matched node using ReplacingArgs.MatchNode proeprty.
  3. Insert the table.
  4. Remove the matched node.

Hi thank you very much!
That helped.
I have one more question though – when I was testing my code I placed the string to be replaced in the center of an empty line but when it got replaced with the table, the table was positioned as left-aligned on the page. Is there a way to maintain the positioning?

@AlinaS,

Thanks for your inquiry. Please note that Aspose.Words mimics the behavior of MS Word. In your case, we suggest you following solution.

  1. Get the position of text using Aspose.Words.Layout API. To get the position of text, you need to bookmark the text. Following code snippet shows how to get the position of bookmark.

  2. Set the left indent of table using Table.LeftIndent property with the position of bookmark.

     LayoutCollector collector = new LayoutCollector(doc);
     LayoutEnumerator enumerator = new LayoutEnumerator(doc);
    
     double bm_position = 0;
     Bookmark bookmark = doc.Range.Bookmarks["bm_name"];
    
     enumerator.Current = collector.GetEntity(bookmark.BookmarkStart);
     bm_position = enumerator.Rectangle.Left;
     Console.WriteLine(bm_position);
    

If you face any issue, please ZIP and attach your input and expected output Word documents here for our reference. We will then provide you more information about your query.

Thank you very much – that helped!