Saving pdf document from webbrowser control - vb.net

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.

you could test the URL when document completed fires and if its .pdf, then do the following then navigate back, for example.
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
You will need to make the filename "TEST" as a variable instead of a static string or else you will overwrite the same file each time. Perhaps:
WebBrowserEx1.DocumentTitle.ToString & ".pdf"
instead, which would save the file as pdf named by the webpage title. Only problem there is if the page contains illegal characters (that windows doesnt let you save with) it will throw an exception so that should be handled.

Related

Folder Browser Replacement

I want to be able to add multiple download links and for them to go into a single folder which is selected by the user in a Folder Browser Dialog
The code you see below works great except only for a single file. I have tried changing all 'savefiledialog1' to 'folderbrowserdialog1' instead. However this leads to me clicking download and nothing happening even if only a single link is entered.
Private Sub BtnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
If (SaveFileDialog1.ShowDialog() = DialogResult.OK) Then
txtSave1.Text = SaveFileDialog1.FileName
btnDownload.Enabled = True
End If
End Sub
' ------------ DOWNLOADING SECTION ------------
Private WithEvents HTTPCLIENT As WebClient
Private Sub BtnDownload_Click(sender As Object, e As EventArgs) Handles
btnDownload.Click
btnDownload.Enabled = False
txtSave1.Enabled = False
btnBrowse.Enabled = False
btnDownload.Enabled = False
HTTPCLIENT = New WebClient
Dim Download As String
Download = Links(i)
Dim User = Environment.UserName
Dim Save As String = txtSave1.Text
Try
HTTPCLIENT.DownloadFileAsync(New Uri(Download), Save)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
I expected the folder browser dialog to just be a general save path where the file being downloaded is placed into that folder, however I am given an error.
The code above works but only for a single file.
I have code that can retrieve the download name and extension which I plan to add to the path once i figure this part out.
You can use the FolderBrowserDialog. Once you get the path, you combine it with each filename you will download. Use System.IO.Path.Combine()
Private Sub BtnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
Using fbd As New FolderBrowserDialog()
If fbd.ShowDialog() = DialogResult.OK Then
txtSave1.Text = fbd.SelectedPath
btnDownload.Enabled = True
End If
End Using
End Sub
Private Sub BtnDownload_Click(sender As Object, e As EventArgs) Handles btnDownload.Click
Try
btnDownload.Enabled = False
txtSave1.Enabled = False
btnBrowse.Enabled = False
btnDownload.Enabled = False
Dim exceptionMessages As New List(Of String)
Using client = New WebClient()
' configure client here as needed i.e. add Credentials
For Each link In Links
Try
client.DownloadFileAsync(New Uri(link), Path.Combine(txtSave1.Text, link))
Catch ex As Exception
exceptionMessages.Add(ex.Message)
End Try
Next
End Using
If exceptionMessages.Any() Then MessageBox.Show($"Exception{If(exceptionMessages.Count > 1, "s", "")}: {String.Join(Environment.NewLine, exceptionMessages)}")
Finally
txtSave1.Enabled = True
btnBrowse.Enabled = True
btnDownload.Enabled = True
End Try
End Sub
Note that I will not post an answer with IDisposable objects without Using (in most cases) so FolderBrowserDialog and WebClient are both in Usings. You may need to add additional configuration to the WebClient before downloading.
Also, you probably don't want a separate message for each Exception, if any. So the messages can be cached and shown all at once.
I inserted a Finally for you to set control states back to default when done. This is up to you.
Lastly, the work is being done on a UI thread as evidenced by it being one inside the button click handler. You should move it off the UI even though you aren't blocking. This is outside the scope of the question.

Download Image under the Mouse pointer via WebBrowser

I'm navigating to Google Images using a WebBrowser control. The aim is to be able to right click on any image and download and populate a PictureBox background.
I have my own ContextMenuStrip with Copy on it and have disabled the built in context menu.
The issue I am having is that the coordinate returned from CurrentDocument.MouseMove are always relative to the first (top left) image.
So my code works correctly if the Image I want is the very first image on the page, however clicking on any other Images always returns the coordinates of the first image.
It would appear that the coordinates are relative to each Image rather than the page.
Private WithEvents CurrentDocument As HtmlDocument
Dim MousePoint As Point
Dim Ele As HtmlElement
Private Sub Google_covers_Load(sender As Object, e As EventArgs) Handles MyBase.Load
WebBrowser1.IsWebBrowserContextMenuEnabled = False
WebBrowser1.ContextMenuStrip = ContextMenuStrip1
End Sub
Private Sub WebBrowser1_Navigated(sender As Object, e As WebBrowserNavigatedEventArgs) Handles WebBrowser1.Navigated
CurrentDocument = WebBrowser1.Document
End Sub
Private Sub CurrentDocument_MouseMove(sender As Object, e As HtmlElementEventArgs) Handles CurrentDocument.MouseMove
MousePoint = New Point(e.MousePosition.X, e.MousePosition.Y)
Me.Text = e.MousePosition.X & " | " & e.MousePosition.Y
End Sub
Private Sub ContextMenuStrip1_Opening(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip1.Opening
Ele = CurrentDocument.GetElementFromPoint(MousePoint)
If Ele.TagName = "IMG" Then
CopyToolStripMenuItem.Visible = True
Else
CopyToolStripMenuItem.Visible = False
End If
End Sub
Private Sub CopyToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CopyToolStripMenuItem.Click
Dim ToImg = Ele.GetAttribute("src")
mp3_row_edit.PictureBox1.BackgroundImage = New System.Drawing.Bitmap(New IO.MemoryStream(New System.Net.WebClient().DownloadData(ToImg)))
ToImg = Nothing
End Sub
This code allow to use a standard WebBrowser control to navigate to the Google Image search page and select/download an Image with a right-click of the Mouse.
To test it, drop a WebBrowser Control and a FlowLayoutPanel on a Form and navigate to a Google Image search page.
Things to know:
WebBrowser.DocumentCompleted: This event is raised each time one of the Sub-Documents inside a main HtmlDocument page is completed. Thus, it can be raised multiple times. We need to check whether the WebBrowser.ReadyState = WebBrowserReadyState.Complete.
Read these note about this: How to get an HtmlElement value inside Frames/IFrames?
The images in the Google search page can be inserted in the Document in 2 different manners: both using a Base64Encoded string and using the classic src=[URI] format. We need to be ready to get both.
The mouse click position can be espressed in either absolute or relative coordinates, referenced by the e.ClientMousePosition or e.OffsetMousePosition.
Read the notes about this feature here: Getting mouse click coordinates in a WebBrowser Document
The WebBrowser emulation mode can be important. We should use the most recent compatible mode available in the current machine.
Read this answer and apply the modifications needed to have the most recent Internet Explorer mode available: How can I get the WebBrowser control to show modern contents?.
Note that an event handler is wired up when the current Document is completed and is removed when the Browser navigates to another page. This prevents undesired calls to the DocumentCompleted event.
When the current Document is complete, clicking with the right button of the Mouse on an Image, creates a new PictureBox control that is added to a FlowLayouPanel for presentation.
The code in the Mouse click handler (Protected Sub OnHtmlDocumentClick()) detects whether the current image is a Base64Encoded string or an external source URI.
In the first case, it calls Convert.FromBase64String to convert the string into a Byte array, in the second case, it uses a WebClient class to download the Image as a Byte array.
In both cases, the array is then passed to another method (Private Function GetBitmapFromByteArray()) that returns an Image from the array, using Image.FromStream() and a MemoryStream initialized with the Byte array.
The code here is not performing null checks and similar fail-proof tests. It ought to, that's up to you.
Public Class frmBrowser
Private WebBrowserDocumentEventSet As Boolean = False
Private base64Pattern As String = "base64,"
Private Sub frmBrowser_Load(sender As Object, e As EventArgs) Handles MyBase.Load
WebBrowser1.ScriptErrorsSuppressed = True
WebBrowser1.IsWebBrowserContextMenuEnabled = False
End Sub
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
If WebBrowser1.ReadyState = WebBrowserReadyState.Complete AndAlso WebBrowserDocumentEventSet = False Then
WebBrowserDocumentEventSet = True
AddHandler WebBrowser1.Document.MouseDown, AddressOf OnHtmlDocumentClick
End If
End Sub
Protected Sub OnHtmlDocumentClick(sender As Object, e As HtmlElementEventArgs)
Dim currentImage As Image = Nothing
If Not (e.MouseButtonsPressed = MouseButtons.Right) Then Return
Dim source As String = WebBrowser1.Document.GetElementFromPoint(e.ClientMousePosition).GetAttribute("src")
If source.Contains(base64Pattern) Then
Dim base64 As String = source.Substring(source.IndexOf(base64Pattern) + base64Pattern.Length)
currentImage = GetBitmapFromByteArray(Convert.FromBase64String(base64))
Else
Using wc As WebClient = New WebClient()
currentImage = GetBitmapFromByteArray(wc.DownloadData(source))
End Using
End If
Dim p As PictureBox = New PictureBox() With {
.Image = currentImage,
.Height = Math.Min(FlowLayoutPanel1.ClientRectangle.Height, FlowLayoutPanel1.ClientRectangle.Width)
.Width = .Height,
.SizeMode = PictureBoxSizeMode.Zoom
}
FlowLayoutPanel1.Controls.Add(p)
End Sub
Private Sub WebBrowser1_Navigating(sender As Object, e As WebBrowserNavigatingEventArgs) Handles WebBrowser1.Navigating
If WebBrowser1.Document IsNot Nothing Then
RemoveHandler WebBrowser1.Document.MouseDown, AddressOf OnHtmlDocumentClick
WebBrowserDocumentEventSet = False
End If
End Sub
Private Function GetBitmapFromByteArray(imageBytes As Byte()) As Image
Using ms As MemoryStream = New MemoryStream(imageBytes)
Return DirectCast(Image.FromStream(ms).Clone(), Image)
End Using
End Function
End Class

Streamwriter will not save to FileName entered by User with Default var.FileName initiated - VB.NET

I am new here, and relatively new to VB.NET. I have a specific problem with getting my StreamWriter to work properly. One of the requirements of my project is to give the file a default name when the user clicks the Save button, which I have done by setting mysave.Filename = "MyLog.log". I call a new instance of my streamwriter trying to save to the filename specified by the user (mySave.Filename again), but every time, it saves to the default MyLog.log file. I have pasted my code below.
If someone could tell me how I can make sure the data is being saved to the value entered by the user for File name, that would be greatly beneficial. Also, I apologize for the code format, its not perfectly readable, but I'm trying to learn how to use the 4 space indents to my advantage!!
Thanks!
Imports System.IO
Public Class Form1
Dim Initial As String = "C:\Users\Brian Frick\Documents\Visual Studio 2010\Projects\HW5_Frick_Creator\HW5_Frick_Creator\bin\Debug" 'give variable for full path without log file
Dim Fullpath As String = "C:\Users\Brian Frick\Documents\Visual Studio 2010\Projects\HW5_Frick_Creator\HW5_Frick_Creator\bin\Debug\MyLog.log" 'give one path for full path
Dim filewriter As New StreamWriter(Fullpath, True)
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Application.Exit() ' quit application
filewriter.Close()
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
Dim mySave As New SaveFileDialog
mySave.Filter = "LOG File (*.log)|*.log" 'set filter to .log
mySave.DefaultExt = "log" 'set default extension
mySave.InitialDirectory = Initial 'set default directory
mySave.FileName = "MyLog.log"
mySave.OverwritePrompt = True ' make sure to ask user if they want to over write
If mySave.ShowDialog() = DialogResult.OK Then
Dim filewriter As New StreamWriter(mySave.FileName, True)
filewriter.Close()
'filewriter = New StreamWriter(mySave.FileName, True)
'filewriter.Close() 'close filewriter to allow access to write directory
'Dim Stream As New StreamWriter(mySave.FileName, True) 'save file to path chosen by user in SaveDialog
'Stream.Close() ' Close stream to allow access to directory
' filewriter.Close()
Else
'dialog cancelled - no action
End If
filewriter.Close()
filewriter = New StreamWriter(Fullpath, True) 're initiate filewriter to be used in successive iterations through the program without error
End Sub
Private Sub SavingsDepositBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SavingsDepositBtn.Click
'write to file for SavDep
filewriter.WriteLine("SavDep")
filewriter.WriteLine(AccountBox.Text)
filewriter.WriteLine(AmountBox.Text)
End Sub
Private Sub SavingsWithdrawBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SavingsWithdrawBtn.Click
'write to file for SavWith
filewriter.WriteLine("SavWith")
filewriter.WriteLine(AccountBox.Text)
filewriter.WriteLine(AmountBox.Text)
End Sub
Private Sub CheckDepsotBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckDepsotBtn.Click
'write to file for CheckDep
filewriter.WriteLine("CheckDep")
filewriter.WriteLine(AccountBox.Text)
filewriter.WriteLine(AmountBox.Text)
End Sub
Private Sub CheckWithdrawBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckWithdrawBtn.Click
'write to file for CheckWith
filewriter.WriteLine("CheckWith")
filewriter.WriteLine(AccountBox.Text)
filewriter.WriteLine(AmountBox.Text)
End Sub
End Class
the general way you are using the filewriter won't work, and there are some other serious issues like that there are two 'FileWriter' variables with overlapping scope.
for your save routine, you can't just re-instantiate your filewriter to point it to a different path. that will destroy all the data that had been in the underlying stream, so you are just saving nothing.
try caching the data in memory while the program is running, and don't create the stream until you are ready to write all the data to it, and it to a file, all in one go. your current approach makes it very hard to prevent leaking handles to the log files, so if the app crashes the user will have to reboot to release the write lock before they can run it again. look into the 'using' construct and 'Try... Finally'

Error with code?

Hi can anyone tell me why the following dose not work:
(p.s I dont want the file to append upon clicking abutton just upon clicking the checkbox.
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
Dim FILE_NAME As String = "C:\RXF\log.txt"
'Adding items for AutoCAD 2006...
If CheckBox1.CheckState = CheckState.Checked Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine("module: 4FNV-67-5H")
objWriter.Close()
End If
End Sub
End Class
Not reproducible, even with your exact code as posted. This works perfectly fine for me, creating a text file in the specified location if one does not exist and appending the specified text to the end of the file.
The only thing I suggest is wrapping your StreamWriter object in a Using statement to ensure that its Dispose method always gets called, even if an exception is thrown (which is all the more likely when you're doing disk I/O). So, your existing code would simply change to:
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
Dim FILE_NAME As String = "C:\RXF\log.txt"
''#Adding items for AutoCAD 2006...
If CheckBox1.CheckState = CheckState.Checked Then
Using objWriter as New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine("module: 4FNV-67-5H")
objWriter.Close()
End Using
End If
End Sub
Also, if you anticipate this method getting called a lot (i.e., the user clicking and unclicking and clicking the checkbox repeatedly), you might consider creating the StreamWriter object once and saving it as a private class-level variable, instead of creating and disposing of it each time the method is called. Then you just have to make sure that you dispose of it whenever your class (presumably the containing form) is disposed.

Pressing a button in visual basic

I am new to Visual Basic.NET and I am just playing around with it. I have a book that tells me how to read from a file but not how to write to the file with a button click. All I have is a button and a textbox named fullNameBox. When I click the button it gives me an unhandled exception error. Here is my code:
Public Class Form1
Sub outputFile()
Dim oWrite As System.IO.StreamWriter
oWrite = System.IO.File.CreateText("C:\sample.txt")
oWrite.WriteLine(fullNameBox.Text)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
outputFile()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
Have you tried stepping through your application to see where the error is? With a quick glance, it looks like you might need to use System.IO.File on the fourth line (oWrite = IO.File...) instead of just IO, but I haven't tried to run it.
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SaveFileDialog1.FileName = ""
SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
SaveFileDialog1.ShowDialog()
If SaveFileDialog1.FileName.Trim.Length <> 0 Then
Dim fs As New FileStream(SaveFileDialog1.FileName.Trim, FileMode.Create)
Dim sr As New StreamWriter(fs)
sr.Write(TextBox1.Text)
fs.Flush()
sr.Close()
fs.Close()
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.FileName.Trim.Length <> 0 Then
Dim fs As New FileStream(OpenFileDialog1.FileName.Trim, FileMode.Open)
Dim sw As New StreamReader(fs)
TextBox1.Text = sw.ReadToEnd
fs.Flush()
sw.Close()
fs.Close()
End If
End Sub
End Class
this is a complete functional program if you want, you just need to drag drop a textbox, openfiledialog, and a savefiledialog.
feel free to play around with the code.
enjoy
by the way, the problem in your code is that you "must" close filestream when your done using it, doing so will release any resource such as sockets and file handles.
The .net framework is a very powerful framework. In the same way (however) it has easy and convenient methods for simple tasks. Most individuals tend to complicate things in order to display knowledge. But less code = less processing = faster and more efficient application (sometimes) so the large above method may not be suitable. Along with that, the above mentioned method would be better off written as a sub or if returning something then a function.
My.Computer.FileSystem.WriteAllText("File As String", "TextAsString", Append as Boolean)
A general Example would be
My.Computer.FileSystem.WriteAllText("C:\text.text", "this is what I would like to add", False)
this is what I would like to add
can be changed to the current text of a field as well.
so a more specific example would be
My.Computer.FileSystem.WriteAllText("C:\text.text", fullNameBox.text, True)
If you would like to understand the append part of the code
By setting append = true you are allowing your application to write the text at the end of file, leaving the rest of the text already in the file intact.
By setting append = false you will be removing and replacing all the text in the existing file with the new text
If you don't feel like writing that part of the code (though it is small) you could create a sub to handle it, however that method would be slightly different, just for etiquette. functionality would remain similar. (Using StreamWriter)
Private Sub WriteText()
Dim objWriter As New System.IO.StreamWriter("file.txt", append as boolean)
objWriter.WriteLine(textboxname.Text)
objWriter.Close()
End Sub
The Specific Example would be
Private Sub WriteText()
Dim objWriter As New System.IO.StreamWriter("file.txt", False)
objWriter.WriteLine(fullnamebox.Text)
objWriter.Close()
End Sub
then under the button_click event call:
writetext()
You can take this a step further as well. If you would like to create a more advabced Sub to handle any textbox and file.
Lets say you plan on having multiple separate files and multiple fields for each file (though there is a MUCH cleaner more elegant method) you could create a function. {i'll explain the concept behind the function as thoroughly as possible for this example}
below is a more advanced sub demonstration for your above request
Private Sub WriteText(Filename As String, app As Boolean, text As String)
Dim objWriter As New System.IO.StreamWriter(Filename, app)
objWriter.WriteLine(text)
objWriter.Close()
End Sub
What this does is allows us to (on the same form - if you need it global we can discuss that another time, it's not much more complex at all) call the function and input the information as needed.
Sub Use -> General Sample
WriteText(Filename As String, app As Boolean)
Sub Use -> Specific Sample
WriteText("C:\text.txt, False, fullnamebox.text)
But the best part about this method is you can change that to be anything as you need it.
Let's say you have Two Buttons* and **Two Boxes you can have the button_event for the first button trigger the above code and the second button trigger a different code.
Example
WriteText("C:\text2.txt, False, halfnamebox.text)
The best part about creating your own functions and subs are Control I won't get into it, because it will be off topic, but you could check to be sure the textbox has text first before writing the file. This will protect the files integrity.
Hope this helps!
Richard Sites.