Reputation: 11393
I want to Print my HTML document directly to a specific network printer without printer dialog window when the end user click on PRINT button. I do search and follow this but this opens a dialog window to save the document as pdf.
Based On The Comments:
public static class PrinterClass
{
[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetDefaultPrinter(string Printer);
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//List<string> st = new List<string>();
//foreach (string strPrinter in PrinterSettings.InstalledPrinters)
//{
// if (strPrinter.Contains("My Printer"))
// {
// PrinterClass.SetDefaultPrinter(strPrinter);
// }
// st.Add(strPrinter);
//}
SetDefaultPrinter("Send To OneNote 2016");
}
WebBrowser webBrowser = new WebBrowser();
void Print(string str)
{
webBrowser.DocumentText = str;
webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
}
void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
IHTMLDocument2 d2;
d2 = (IHTMLDocument2)((WebBrowser)sender).Document.DomDocument;
d2.execCommand("Print", false, null);
}
private void btn_print_Click(object sender, EventArgs e)
{
Print("<html><body>..some html code..</body></html>");
}
public static bool SetDefaultPrinter(string defaultPrinter)
{
using (ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer"))
{
using (ManagementObjectCollection objectCollection = objectSearcher.Get())
{
foreach (ManagementObject mo in objectCollection)
{
if (string.Compare(mo["Name"].ToString(), defaultPrinter, true) == 0)
{
mo.InvokeMethod("SetDefaultPrinter", null, null);
return true;
}
}
}
}
return false;
}
}
Upvotes: 1
Views: 5547
Reputation: 125197
In the recent versions of the WebBroswer
control, Print()
prints to the default printer without showing any dialog:
webBrowser1.Print();
It's equivalent to getting an instance of IWebBrowser2
from the WebBrowser.ActiveXInstance
property and then call its ExecWB
method by passing OLECMDID_PRINT
as command and OLECMDEXECOPT_DONTPROMPTUSER
to specify not showing the prompt:
int OLECMDID_PRINT = 6;
int OLECMDEXECOPT_DONTPROMPTUSER = 2;
dynamic iwb2 = webBrowser1.ActiveXInstance;
iwb2.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER, null, null);
Or in a single line of code:
((dynamic)webBrowser1.ActiveXInstance).ExecWB(6, 2, null, null);
Upvotes: 2