Web app with Windows app print pdf file from download link
2016-03-07 | Hits
Scenario
A web app that allow user to click on a link/button, then trigger the selected printer and print out the document directly.
Problem & Solution
Due to security reason, there is no way to trigger hardware via JavaScript. Thus, I create a Windows Form Application (WFA) using C#.
This application is actually just a wrapper that wrap a browser (I’m using CefSharp browser), so that I can get the printer list by using C#, then pass to the browser.
1. Create a Windows Form Application
I assume you know how to do this. I’m using Visual Studio in this case.
Also, you need to add a few references that required for this project:
// after the page loaded, check if the url is setup printers page privatevoidOnFrameLoadEnd(object sender, FrameLoadEndEventArgs e) { if (e.Url.Contains("setup/printers")) addPrinterOptionsToDropdown(); }
// Javascript privatevoidaddPrinterOptionsToDropdown() { // (Optional) Filter a few printer model Regex regex = new Regex(@"\b(EPSON|Canon)\b", RegexOptions.IgnoreCase);
string js = "$('select').empty();";
foreach (string sPrinters in System.Drawing.Printing.PrinterSettings.InstalledPrinters) { MatchCollection matches = regex.Matches(sPrinters); if (matches.Count < 1) continue;
privatestring suggestedFilename = null; // without the session, the file cannot be downloaded publicvoidsetSessionCookie(string sessionCookie) { this.sessionCookie = sessionCookie; }
publicvoidOnBeforeDownload(IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback) { if (!callback.IsDisposed) { using (callback) { callback.Continue(downloadItem.SuggestedFileName, showDialog: true); } } }