0

I'm trying to create a Windows Form Application to view PDF's and images in a webbrowser. Images are scaled to format of webbrowser, in the code below. However when i try to load a pdf, its giving me the error:

"An exception of type 'System.NullReferenceException' occurred in AddMetadataToDocuments.exe but was not handled in user code".

Code:

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
     webBrowser1.Document.Body.SetAttribute("scroll", "no");
     var img = webBrowser1.Document.GetElementsByTagName("img")
                         .Cast<HtmlElement>().FirstOrDefault();
     var w = img.ClientRectangle.Width;
     var h = img.ClientRectangle.Height;
     img.Style = string.Format("{0}: 100%", w > h ? "Width" : "Height");
}

Hope anyone can help!

Niels
  • 95
  • 2
  • 9
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – haindl Oct 12 '17 at 08:22

1 Answers1

0

I've fixed it by using an simple if statement which checks if the file ends with JPG or PNG, if yes: execute the scaling method, else(pdf) do nothing:

if (allFiles[index].EndsWith("JPG") || allFiles[index].EndsWith("PNG"))
{
     webBrowser1.Document.Body.SetAttribute("scroll", "no");
     var img = webBrowser1.Document.GetElementsByTagName("img")
                         .Cast<HtmlElement>().FirstOrDefault();
     var w = img.ClientRectangle.Width;
     var h = img.ClientRectangle.Height;
     img.Style = string.Format("{0}: 100%", w > h ? "Width" : "Height");
}    
Niels
  • 95
  • 2
  • 9