-1

I have HTML code something like -

<html>
<body>
<table><tr><td><h1>Heading</h1></td></tr></table>
</body>
</html>

In a specific requirement, I need to know in advance that how much height will this HTML will take to display in fullscreen. So that I keep that much space calculated specifically for that content.

What I thought was to render this code in WebBrowser control, and then take the height.

        this.webBrowser1.Url = new Uri(htmlFilePath);
        //The below code will force the webbrowser control to load the HTML in it.
        while (this.webBrowser1.Document.Body == null)
        {
            Application.DoEvents();
        }
        int height = this.webBrowser1.Document.Body.ScrollRectangle.Height;

But in console application I can't use WebBrowser control. Is there any other way I can accomplish this?

Arpit Gupta
  • 1,209
  • 1
  • 22
  • 39
  • 1
    You could look at [Headless Browsers](https://en.wikipedia.org/wiki/Headless_browser) but I wouldn't know how to get layout information from them. – bommelding Sep 26 '18 at 10:57
  • 1
    I don't think you can do that with c# as it is server side and run before the rendering has finished - if you need it then you would probably have to ajax it in after the document has been rendered – Pete Sep 26 '18 at 11:30
  • You **can** use the `WebBrowser` control in a console application. See https://stackoverflow.com/questions/6324810/using-webbrowser-in-a-console-application – Bradley Uffner Sep 26 '18 at 12:08
  • @BradleyUffner WebBrowser control will need some base for them. I mean, if they are drawn on form(full screen), then only I will get the actual html's height. Else it is giving me wrong size. – Arpit Gupta Sep 27 '18 at 06:22
  • 1
    It works perfectly fine headless. Just set the page height and width to a reasonable number, load the content, wait for DOM to complete, then read the body height. – Bradley Uffner Sep 27 '18 at 09:09
  • 1
    @BradleyUffner Wow, Thanks a lot. Its perfectly working. – Arpit Gupta Sep 27 '18 at 09:21

1 Answers1

0

Answering my own question -

All I needed to do was adding reference of System.Windows.Forms in my console application. After that I was able to use WebBrowser in headless form directly without creating any form element.

After using WebBrowser, I set the height/width of reasonable number. Something like below -

WebBrowser wb = new WebBrowser();
//Setting the page height and width to a reasonable number. So that whatever the content loaded in it gets aligned properly.
//For me 3000 works fine for my requirements.
wb.Width = 3000; 
wb.Height = 3000;

wb.Url = new Uri(htmlFilePath);
//the below code will force the webbrowser control to load the html in it.
while (wb.Document.Body == null)
{
    Application.DoEvents();
}
int height = wb.Document.Body.ScrollRectangle.Height;
Arpit Gupta
  • 1,209
  • 1
  • 22
  • 39