1

I'm navigating from webbrowser control to an url like this; http://www.who.int/cancer/modules/Team%20building.pdf

It's shown in webbrowser control. What I want to do is to download this pdf file to computer. But I tried many ways;

Dim filepath As String
filepath = "D:\temp1.pdf"
Dim client As WebClient = New WebClient()
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(WebBrowserEx1.Url, filepath)

This one downloads a pdf but there is nothing in the file.

Also tried with

objWebClient.DownloadFile()

nothing changed.

I tried to show a save or print dialog;

WebBrowserEx1.ShowSaveAsDialog()
WebBrowserEx1.ShowPrintDialog()

but they didnt show any dialog. Maybe the last one is because it doesnt wait to load the the pdf into webbrowser completely.

When I try html files there is no problem to dowload, but in this .pdf file, I think I didn't manage to wait the file to be loaded as pdf into browser. This function(s);

 Private Sub WaitForPageLoad(ByVal adimno As String)
    If adimno = "1" Then
        AddHandler WebBrowserEx1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
        While Not pageReady
            Application.DoEvents()
        End While
        pageReady = False
    End If

End Sub

Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
    If WebBrowserEx1.ReadyState = WebBrowserReadyState.Complete Then
        pageReady = True
        RemoveHandler WebBrowserEx1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
    End If
End Sub

are not working for this situation. I mean it gets into infinite loop.

So anyone knows how to wait this to load pdf then save into computer.

4

1 回答 1

0

例如,您可以在文档完成触发时测试 URL,如果它的 .pdf,然后执行以下操作然后导航回来。

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    WebBrowserEx1.Navigate("http://www.who.int/cancer/modules/Team%20building.pdf")
End Sub

Private Sub WebBrowserEx1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowserEx1.DocumentCompleted

    If WebBrowserEx1.Url.ToString.Contains(".pdf") Then

        Using webClient = New WebClient()
            Dim bytes = webClient.DownloadData(WebBrowserEx1.Url.ToString) 'again variable here

            File.WriteAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TEST.pdf"), bytes) 'save to desktop or specialfolder. to list all the readily available user folders
        End Using

 'WebBrowserEx1.goback() 'could send browser back a page as well

    End If



End Sub

您需要将文件名“TEST”作为变量而不是静态字符串,否则每次都会覆盖同一个文件。也许:

 WebBrowserEx1.DocumentTitle.ToString & ".pdf"

相反,这会将文件保存为以网页标题命名的 pdf。唯一的问题是,如果页面包含非法字符(windows 不允许您保存),它将引发异常,因此应该进行处理。

于 2013-05-15T14:39:57.627 回答