2017-10-12 81 views
0

我試圖創建一個Windows窗體應用程序來查看PDF和Web瀏覽器中的圖像。在下面的代碼中圖像被縮放爲網頁瀏覽器的格式。然而,當我嘗試加載PDF,它給我的錯誤:在WebBrowser中縮放圖像並顯示PDF的錯誤C#

「類型‘System.NullReferenceException’的異常出現在AddMetadataToDocuments.exe但在用戶代碼中沒有處理」

代碼:

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"); 
} 

希望有人能幫助!

+0

的可能的複製[什麼是NullReferenceException,以及如何解決它?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – haindl

回答

0

我通過使用簡單,如果該文件與JPG或PNG結束,檢查的語句,如果是固定的:執行縮放方法,否則(PDF)什麼都不做:

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"); 
}