Calculate remaining page size during creating report using word template using C# .NET | Page Height Header Footer Distance

Hi,
I am building a report using word template having 2 sections one for content and other is for images. 1st section contains dynamic content (it shrinks or expands according to text). Issue I am facing is when sometimes content expands this move images to next page. This creates lots of blank space in my first page.

Is there any way I can calculate remaining page size? So that I can resize images according to remaining page size. So images cannot goes to second page.

@akoundal,

Please see this sample Word document (in.zip (9.2 KB)) and try running the following code:

Document doc = new Document("E:\\temp\\in.docx");
PageSetup ps = doc.FirstSection.PageSetup;

LayoutCollector layoutCollector = new LayoutCollector(doc);
LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);

layoutEnumerator.Current = layoutCollector.GetEntity(doc.FirstSection.Body.FirstParagraph);
float top = layoutEnumerator.Rectangle.Top;

layoutEnumerator.Current = layoutCollector.GetEntity(doc.FirstSection.Body.LastParagraph);
float bottom = layoutEnumerator.Rectangle.Bottom;

Console.WriteLine("Total height: {0} points", (ps.PageHeight));
Console.WriteLine("Header height: {0} points.", ps.HeaderDistance);
Console.WriteLine("Footer height: {0} points.", ps.FooterDistance);
Console.WriteLine("Height in Use: {0} points. And 72 points equal 1 inch.", bottom - top);
Console.WriteLine("Remaining height: {0} points.", ps.PageHeight - bottom);

Hope, this helps in achieving what you are looking for.

Hi,
Thanks for your reply, Your code is working perfectly but I have other issue. Please check my attached sample report. https://www.dropbox.com/s/p8c4n2a7w9n9ajl/Dummy_Report.docx?dl=0

Here my issue is “Contacts” section is dynamic (Multiple table rows) and there is section named “Description” which contains text content. My issue is when there are multiple rows in “Contacts” section and there is large text in “Description” section, Images in “Pictures/Sketches” moves to next page. Any Solution/advice for this?

@akoundal,

It is by design that when content grows vertically, MS Word pushes the content at bottom to next page. You can try reducing the font size of content of Description section, and/or decrease height/width of images or increase the Page’s Width/Height so that all desired content remains on a single page. Hope, this helps.

A post was split to a new topic: Get Remaining Page Size when Last Section in Word Document Spans Multiple Pages using C# .NET