How to get table preferred point width using .NET

hi team,

I have a table setting preferred width 100% , but the content overlap the right margin, so i want to know how to get the table actually preferred width of point, or how to convert the percent to actually point.

The test document: test.zip (11.8 KB)

@TommyZhou

We suggest you please use Table.AutoFit method as shown below to get the desired output.

Document doc = new Document(MyDir + "test.docx");
foreach (Table table in doc.FirstSection.Body.Tables)
{
 table.AutoFit(AutoFitBehavior.AutoFitToWindow);
}
doc.Save(MyDir + "20.6.docx");

@tahir.manzoor

Thanks, for some reason, i don’t want to re-render table or page layout, only expected to get the table’s preferred point width, Whether this can be achieved? or detect the table is overlap the right margin.

@TommyZhou

In your case, we suggest you following solution.

  1. Bookmark the first or last row. Please read article about working with bookmarks.
  2. Please use Layout API to get the position of BookmartStart and BookmarkEnd nodes as shown in following code snippet.
  3. Please substract the left margin of page from the pages width. You can use PageSetup.PageWidth property to get the page’s width and PageSetup.LeftMargin property to get the page’s left margin.
  4. Substract the left position of BookmartStart and BookmarkEnd to get the approximate width of table.
  5. You can compare table’s width with page width to get the desired result.

Hope this helps you.

Document doc = new Document(MyDir + "test.docx");
                
LayoutCollector collector = new LayoutCollector(doc);
LayoutEnumerator enumerator = new LayoutEnumerator(doc);

Bookmark bm = doc.Range.Bookmarks["MyBookmark"];

enumerator.Current = collector.GetEntity(bm.BookmarkStart);
Console.WriteLine(" --> Left : " + enumerator.Rectangle.Left);