Open files downloaded from CEFSharp in default OS viewer application - c#

I have built a Winforms Application using .NET 4.7.2 and CEFSharp 84.4.10.
I have a website loaded that has links to various files PDF, TXT, DOCX etc...
The html for the links is like this:
icon_here
So when I click on a link to a docx for example, it CEFSharp opens a blank window over the top of my application and then opens the save file dialogue. When you press Save on the file dialogue it closes but the blank window stays open.
I want to do the following:
Not have the blank window open.
Detect the file type/mime being downloaded (my app only loads my site), and if they are PDF, TXT or DOCX then automatically download to a temp location, without showing the save dialogue, and open in the OS default viewer.
If not one of the above types then show the Save file dialogue and let user download to where they want.
I can work out how to open a file in the default OS viewer separately, I want to focus on automatic download of specific file types here.
I have spent hours searching for examples of how to do this and come up empty handed.
I was thinking I would be able to detect the type of file in DownloadHandler.OnBeforeDownload, and then based on the following post, just set showDialogue to false in the callback and then in DownloadHandler.OnDownloadUpdated detect downloadItem.IsComplete and then launch the file if it is of the correct type.
Force CEFSharp to download without showing dialog
However when I tried this I ran into the following issues:
The blank window still opens and stays open.
I find that if I set a break point in DownloadHandler.OnDownloadUpdated that I can see the ReceivedBytes go from zero to the TotalBytes, and InProgress being true, and then as I keep pressing F5 to continue ReceivedBytes changes back to zero, and InProgress is false, but IsComplete and IsCanceled remain false the entire time. I would have expected that once the download completed IsComplete would have been true.
I am enjoying working with CEFShap and any direction or examples that could be provided would be much appreciated.
Thanks for your time.
UPDATE 1:
The code I have tried as as follows:
NOTE: I found that after assigning a path to the callback.Continue in OBeforeDownload it fixed the IsComplete not being set to true issue. However the issue of the blank window opening remains.
In winform hosting CEFSharp I have initialised the control as follows:
browser = new ChromiumWebBrowser("https://localhost:44393/Default.aspx");
var downloadHandler = new DownloadHandler();
browser.DownloadHandler = downloadHandler;
In DownloadHandler.cs:
public class DownloadHandler : IDownloadHandler
{
public event EventHandler<DownloadItem> OnBeforeDownloadFired;
public event EventHandler<DownloadItem> OnDownloadUpdatedFired;
public void OnBeforeDownload(IWebBrowser chromiumWebBrowser, IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback)
{
OnBeforeDownloadFired?.Invoke(this, downloadItem);
if (!callback.IsDisposed)
{
using (callback)
{
//TODO: Detect file Type/Mime and auto download or show Save File dialogue as needed here
callback.Continue(Path.Combine(#"C:\Temp", downloadItem.SuggestedFileName), showDialog: false); // set to false so we don't show
}
}
}
public void OnDownloadUpdated(IWebBrowser chromiumWebBrowser, IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
{
OnDownloadUpdatedFired?.Invoke(this, downloadItem);
if (downloadItem.IsComplete)
{
//TODO: Detect File Type/Mime and automatically open in default OS viewer
}
}
}

Related

How to open url in new browser tab from Web browser control (displaying PDF having a link) c#

I am facing this issue, working on Active reports 9. Every thing is fine as per our application we generate the report and in UI user will be viewing in a c# Web browser control.
Now the issue am facing is when client(user) clicks on the link present in pdf i.e. on Web Browser control. With in the same window the link is opening. They want the link to open in new window.
The problem q=am facing is if its Html control i would have used target="_blank" property but not , and its a windows application i cant even use Java script. I just gone through the properties of Picture control used in Report, theres only Hyperlink property which states in pdf it converts it to href or a tag.
Need some assistance as soon as possible is that possible to do in web browser control or should change any properties for picture control in Code behind.
Hope this help you. It worked for me.
Add the Navigating event on your webBrowser control. This will open the link in a new Browser window. In my case Google Chrome.
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
try
{
if (!(e.Url.ToString().ToLower().Contains("file") || e.Url.ToString().ToLower().Contains("pdf")))
{
e.Cancel = true;
//Open Link
Process.Start(e.Url.ToString());
}
}
catch (Exception err)
{
//Handle Exception
}
}

Click on a link on C# WebBrowser to start download a file and also its link

I am using a C# WebBrowser to navigate to a page.
After navigate to that page I extract some link from its source code and then start to navigate to those sub_links in a loop which I get from its parent url.
On every sub_links there is a link which is look like:
<a onclick="sysMT('SYSext.Sup_Filetype','type','SYSext.Sup_Filename','Filename.exe','SYSext.Sup_Referer','http://abc.com');"
id="ctl00_UCDownloadFile1_Accept"
href="javascript:__doPostBack('ctl00$UCDownloadFile1$Accept','')">Accept</a>
the id of a button is "ctl00_UCDownloadFile1_Accept" is same in all its sub_links.
When I click on above link manually a file start to download.
I want to "click" on above button using c# code.
I am able to click on above button using this code on webBrowser1_DocumentCompleted event:
HtmlElement elementById = webBrowser1.Document.GetElementById("ctl00_UCDownloadFile1_Accept");
if (elementById != null)
{
elementById.InvokeMember("click");
Application.DoEvents();
}
But a script error message box appear saying
"An error has occured in the script on this page.
Error: The value of the property 'sysMT' is null or undefined, not a Function object.
Do you want to continue running script on this page?
Yes NO"
Not able to understand what I am missing in this. Did Parent url make some cookie which helps to download the file? Don't know how to download that file and also download file link.
I am new to C# WebBrowser.
Update
I am able to remove a script error message box using
webBrowser2.ScriptErrorsSuppressed = true;
But not able to download all file which are their in sub links i.e.
If I get 3 links from a parent url, then I navigate to first link, click on Accept link and then a box appear asking for a action to RUN SAVE CANCEL.
But I get this box only for third (last) link.
How to overcome with this problem, I want to download all file from each links without any prompt which asking for RUN SAVE CANCEL. Directly SAVE a file.

how can I upload a file via file input box using webbrowser in C#

May be this question is asked in past but I have searched and not found its solution yet.
I have tried all the options that I have found till now but all in vain.
SendKeys doesn't work as it does not fill the file input box with file path, that is to be uploaded.
Cannot set file input box "SetAttribute" value as there is no value attribute available:
thats all.
If I use element.focus() it pops up "choose file to upload" dialog and now I don't know how to fill it programmatically and open it in file input box.
I want it to be automated completed so that user does not have to interact with the application.
Application shall pick the file from hard disk from given file path and fill other fields of form then start uploading, all using webbrowser control in windows form application.
No solutions found!
Can anyone help please? (This is my first ever question on stackoverflow, therefore if I am doing anything wrong then please guide, I mean if I am not allowed to post such question!)
Here is the code:
HtmlElementCollection heCollection = doc.GetElementsByTagName("input");
foreach (HtmlElement heSpan in heCollection)
{
string strType = heSpan.GetAttribute("type");
string strName = heSpan.GetAttribute("name");
if (strType.Equals("file") && strName.Equals("file"))
{
heSpan.Focus();
//heSpan.SetAttribute("value", "test.jpg");
SendKeys.Send("C:\\1.txt");
//heSpan.InnerText = "c:\\1.txt";
}
//Title for the attachment
if (strName.Equals("field_title"))
{
heSpan.InnerText = "1.txt";
}
}
When this code executes, cursor starts blinking in fine input box (as I have set heSpan.focus()) but the file path doesn't show in the file input box.
If I implement
heSpan.InvokeMember("click");
It opens the choose a file to upload dialoge/popup window and there I get stuck, because I don't know how to fill that popup dynamically and then insert the file path in file input box.
Try setting the focus to the WebBrowser control right before you set the focus to the input field.
That worked for me.

Using the WebBrowser control to load several HTML files from disk

I am trying to display HTML files (containing local images) in a WebBrowser control. User can select the file using an OpenFileDialog, after which it is displayed in the control.
But I have these problems I am struggling to solve:
Since I've added the control to my Form, it's been loading really slowly. It takes almost 10s for the form to instantiate.
WebBrowser.Navigate only works the first time. When I try to load the second file, nothing happens. I have tried calling Refresh, Update, OpenNew, opening about:blank between two files, but I just don't have a clue how to do it properly. Only the initially opened file remains shown, no exceptions or warnings ever pop up when I try to navigate to a different page.
Am I doing something wrong? For example, Lutz Roeder's Writer starts instantly and loads subsequent files without problems, but it uses lots of interop (and is editable), so I am trying to avoid all that stuff.
The way I have been loading local .html files into a WebBrowser is like so:
OpenFileDialog ofd = new OpenFileDialog();
// Do filtering here
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
webBrowser1.DocumentText = System.IO.File.ReadAllText(ofd.FileName);
}
It can load files one after another with no problems. If you are trying to load a big html file when the form is initializing or is opening this could explain the 10 second loading time. My form loaded almost instantly when it had a WebBrowser control on it.
Hope this helps!
Edit: Try setting the stream of the WebBrowser:
System.IO.Stream s = System.IO.File.OpenRead(ofd.FileName);
webBrowser1.DocumentStream = s;

how to print .htm files in c#?

I can't seem to find a good way to print .htm files in c# using .net 4.0, visual studio 2010 and windows forms. When i tried to print it directly, it printed the raw html data instead of printing the "page" itself.
The only way i know to print it, is to use a WebBrowser control. When i print the document, it doesn't print colors and the page isn't printed correctly. For example, the edges are not drawn and so on.
Code for Web Browser :
public void Print()
{
// Create a WebBrowser instance.
WebBrowser webBrowserForPrinting = new WebBrowser();
// Add an event handler that prints the document after it loads.
webBrowserForPrinting.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(PrintDocument);
// Set the Url property to load the document.
webBrowserForPrinting.Url = new Uri(Core.textLog);
}
private void PrintDocument(object sender, WebBrowserDocumentCompletedEventArgs e)
{
((WebBrowser)sender).ShowPrintDialog();
//// Print the document now that it is fully loaded.
//((WebBrowser)sender).Print();
//// Dispose the WebBrowser now that the task is complete.
((WebBrowser)sender).Dispose();
}
What can i do?
Thank you!
Printing web pages will forever be the bane of your existence. There just isn't a solution out there that prints HTML directly to your printer really, really well. And even if you do find a program that does it well, it's only a matter of time until you try to print a page with some unsupported formatting, in which case you're right back where you started.
What we do is print HTML to a pdf file with a program called wkhtmltopdf. Then we open it in Acrobat (which has excellent printing support) and print from there. I can't say enough good things about wkhtmltopdf. It's command line driven, and its super, super fast. Best of all, its free. It has a companion program called wkhtmltoimage that will print to most popular image formats, too (bmp, jpg, png, etc).
After downloading/installing the program, you can run a quick test by going to your command prompt, navigating to the install folder, and typing:
wkhtmltopdf "http://YouWebAddress.com" "C:/YourSaveLocation.pdf"
It also has a ton of command line switches that give you greater control over the outputs (headers, footers, page numbering, etc etc).
Ok, as i said, problem was that edge are not drawn and neither are the backgrounds.
Here is how i solved it.
Hashtable values = new Hashtable();
values.Add("margin_left", "0.1");
values.Add("margin_right", "0.1");
values.Add("margin_top", "0.1");
values.Add("margin_bottom", "0.1");
values.Add("Print_Background", "yes");
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Internet Explorer\PageSetup", true))
{
if (key == null) return;
foreach (DictionaryEntry item in values)
{
string value = (string)key.GetValue(item.Key.ToString());
if (value != item.Value.ToString())
{
key.SetValue(item.Key.ToString(), item.Value);
}
}
}
So before i print, i go to regedit, change the values, and the document gets printed perfectly. Hope this helps other people that have the same problem when printing from webbrowser control in windows forms.

Categories